babylon.max.js 2.8 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773
  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 (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. }());
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. Color3.prototype.getClassName = function () {
  62. return "Color3";
  63. };
  64. Color3.prototype.getHashCode = function () {
  65. var hash = this.r || 0;
  66. hash = (hash * 397) ^ (this.g || 0);
  67. hash = (hash * 397) ^ (this.b || 0);
  68. return hash;
  69. };
  70. // Operators
  71. Color3.prototype.toArray = function (array, index) {
  72. if (index === undefined) {
  73. index = 0;
  74. }
  75. array[index] = this.r;
  76. array[index + 1] = this.g;
  77. array[index + 2] = this.b;
  78. return this;
  79. };
  80. Color3.prototype.toColor4 = function (alpha) {
  81. if (alpha === void 0) { alpha = 1; }
  82. return new Color4(this.r, this.g, this.b, alpha);
  83. };
  84. Color3.prototype.asArray = function () {
  85. var result = [];
  86. this.toArray(result, 0);
  87. return result;
  88. };
  89. Color3.prototype.toLuminance = function () {
  90. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  91. };
  92. Color3.prototype.multiply = function (otherColor) {
  93. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  94. };
  95. Color3.prototype.multiplyToRef = function (otherColor, result) {
  96. result.r = this.r * otherColor.r;
  97. result.g = this.g * otherColor.g;
  98. result.b = this.b * otherColor.b;
  99. return this;
  100. };
  101. Color3.prototype.equals = function (otherColor) {
  102. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  103. };
  104. Color3.prototype.equalsFloats = function (r, g, b) {
  105. return this.r === r && this.g === g && this.b === b;
  106. };
  107. Color3.prototype.scale = function (scale) {
  108. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  109. };
  110. Color3.prototype.scaleToRef = function (scale, result) {
  111. result.r = this.r * scale;
  112. result.g = this.g * scale;
  113. result.b = this.b * scale;
  114. return this;
  115. };
  116. Color3.prototype.add = function (otherColor) {
  117. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  118. };
  119. Color3.prototype.addToRef = function (otherColor, result) {
  120. result.r = this.r + otherColor.r;
  121. result.g = this.g + otherColor.g;
  122. result.b = this.b + otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.subtract = function (otherColor) {
  126. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  127. };
  128. Color3.prototype.subtractToRef = function (otherColor, result) {
  129. result.r = this.r - otherColor.r;
  130. result.g = this.g - otherColor.g;
  131. result.b = this.b - otherColor.b;
  132. return this;
  133. };
  134. Color3.prototype.clone = function () {
  135. return new Color3(this.r, this.g, this.b);
  136. };
  137. Color3.prototype.copyFrom = function (source) {
  138. this.r = source.r;
  139. this.g = source.g;
  140. this.b = source.b;
  141. return this;
  142. };
  143. Color3.prototype.copyFromFloats = function (r, g, b) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. return this;
  148. };
  149. Color3.prototype.toHexString = function () {
  150. var intR = (this.r * 255) | 0;
  151. var intG = (this.g * 255) | 0;
  152. var intB = (this.b * 255) | 0;
  153. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  154. };
  155. Color3.prototype.toLinearSpace = function () {
  156. var convertedColor = new Color3();
  157. this.toLinearSpaceToRef(convertedColor);
  158. return convertedColor;
  159. };
  160. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  164. return this;
  165. };
  166. Color3.prototype.toGammaSpace = function () {
  167. var convertedColor = new Color3();
  168. this.toGammaSpaceToRef(convertedColor);
  169. return convertedColor;
  170. };
  171. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  172. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  173. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  174. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  175. return this;
  176. };
  177. // Statics
  178. Color3.FromHexString = function (hex) {
  179. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  180. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  181. return new Color3(0, 0, 0);
  182. }
  183. var r = parseInt(hex.substring(1, 3), 16);
  184. var g = parseInt(hex.substring(3, 5), 16);
  185. var b = parseInt(hex.substring(5, 7), 16);
  186. return Color3.FromInts(r, g, b);
  187. };
  188. Color3.FromArray = function (array, offset) {
  189. if (offset === void 0) { offset = 0; }
  190. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  191. };
  192. Color3.FromInts = function (r, g, b) {
  193. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  194. };
  195. Color3.Lerp = function (start, end, amount) {
  196. var r = start.r + ((end.r - start.r) * amount);
  197. var g = start.g + ((end.g - start.g) * amount);
  198. var b = start.b + ((end.b - start.b) * amount);
  199. return new Color3(r, g, b);
  200. };
  201. Color3.Red = function () { return new Color3(1, 0, 0); };
  202. Color3.Green = function () { return new Color3(0, 1, 0); };
  203. Color3.Blue = function () { return new Color3(0, 0, 1); };
  204. Color3.Black = function () { return new Color3(0, 0, 0); };
  205. Color3.White = function () { return new Color3(1, 1, 1); };
  206. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  207. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  208. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  209. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  210. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  211. return Color3;
  212. }());
  213. BABYLON.Color3 = Color3;
  214. var Color4 = (function () {
  215. function Color4(r, g, b, a) {
  216. this.r = r;
  217. this.g = g;
  218. this.b = b;
  219. this.a = a;
  220. }
  221. // Operators
  222. Color4.prototype.addInPlace = function (right) {
  223. this.r += right.r;
  224. this.g += right.g;
  225. this.b += right.b;
  226. this.a += right.a;
  227. return this;
  228. };
  229. Color4.prototype.asArray = function () {
  230. var result = [];
  231. this.toArray(result, 0);
  232. return result;
  233. };
  234. Color4.prototype.toArray = function (array, index) {
  235. if (index === undefined) {
  236. index = 0;
  237. }
  238. array[index] = this.r;
  239. array[index + 1] = this.g;
  240. array[index + 2] = this.b;
  241. array[index + 3] = this.a;
  242. return this;
  243. };
  244. Color4.prototype.add = function (right) {
  245. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  246. };
  247. Color4.prototype.subtract = function (right) {
  248. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  249. };
  250. Color4.prototype.subtractToRef = function (right, result) {
  251. result.r = this.r - right.r;
  252. result.g = this.g - right.g;
  253. result.b = this.b - right.b;
  254. result.a = this.a - right.a;
  255. return this;
  256. };
  257. Color4.prototype.scale = function (scale) {
  258. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  259. };
  260. Color4.prototype.scaleToRef = function (scale, result) {
  261. result.r = this.r * scale;
  262. result.g = this.g * scale;
  263. result.b = this.b * scale;
  264. result.a = this.a * scale;
  265. return this;
  266. };
  267. /**
  268. * Multipy an RGBA Color4 value by another and return a new Color4 object
  269. * @param color The Color4 (RGBA) value to multiply by
  270. * @returns A new Color4.
  271. */
  272. Color4.prototype.multiply = function (color) {
  273. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  274. };
  275. /**
  276. * Multipy an RGBA Color4 value by another and push the result in a reference value
  277. * @param color The Color4 (RGBA) value to multiply by
  278. * @param result The Color4 (RGBA) to fill the result in
  279. * @returns the result Color4.
  280. */
  281. Color4.prototype.multiplyToRef = function (color, result) {
  282. result.r = this.r * color.r;
  283. result.g = this.g * color.g;
  284. result.b = this.b * color.b;
  285. result.a = this.a * color.a;
  286. return result;
  287. };
  288. Color4.prototype.toString = function () {
  289. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  290. };
  291. Color4.prototype.getClassName = function () {
  292. return "Color4";
  293. };
  294. Color4.prototype.getHashCode = function () {
  295. var hash = this.r || 0;
  296. hash = (hash * 397) ^ (this.g || 0);
  297. hash = (hash * 397) ^ (this.b || 0);
  298. hash = (hash * 397) ^ (this.a || 0);
  299. return hash;
  300. };
  301. Color4.prototype.clone = function () {
  302. return new Color4(this.r, this.g, this.b, this.a);
  303. };
  304. Color4.prototype.copyFrom = function (source) {
  305. this.r = source.r;
  306. this.g = source.g;
  307. this.b = source.b;
  308. this.a = source.a;
  309. return this;
  310. };
  311. Color4.prototype.toHexString = function () {
  312. var intR = (this.r * 255) | 0;
  313. var intG = (this.g * 255) | 0;
  314. var intB = (this.b * 255) | 0;
  315. var intA = (this.a * 255) | 0;
  316. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  317. };
  318. // Statics
  319. Color4.FromHexString = function (hex) {
  320. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  321. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  322. return new Color4(0, 0, 0, 0);
  323. }
  324. var r = parseInt(hex.substring(1, 3), 16);
  325. var g = parseInt(hex.substring(3, 5), 16);
  326. var b = parseInt(hex.substring(5, 7), 16);
  327. var a = parseInt(hex.substring(7, 9), 16);
  328. return Color4.FromInts(r, g, b, a);
  329. };
  330. Color4.Lerp = function (left, right, amount) {
  331. var result = new Color4(0, 0, 0, 0);
  332. Color4.LerpToRef(left, right, amount, result);
  333. return result;
  334. };
  335. Color4.LerpToRef = function (left, right, amount, result) {
  336. result.r = left.r + (right.r - left.r) * amount;
  337. result.g = left.g + (right.g - left.g) * amount;
  338. result.b = left.b + (right.b - left.b) * amount;
  339. result.a = left.a + (right.a - left.a) * amount;
  340. };
  341. Color4.FromArray = function (array, offset) {
  342. if (offset === void 0) { offset = 0; }
  343. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  344. };
  345. Color4.FromInts = function (r, g, b, a) {
  346. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  347. };
  348. Color4.CheckColors4 = function (colors, count) {
  349. // Check if color3 was used
  350. if (colors.length === count * 3) {
  351. var colors4 = [];
  352. for (var index = 0; index < colors.length; index += 3) {
  353. var newIndex = (index / 3) * 4;
  354. colors4[newIndex] = colors[index];
  355. colors4[newIndex + 1] = colors[index + 1];
  356. colors4[newIndex + 2] = colors[index + 2];
  357. colors4[newIndex + 3] = 1.0;
  358. }
  359. return colors4;
  360. }
  361. return colors;
  362. };
  363. return Color4;
  364. }());
  365. BABYLON.Color4 = Color4;
  366. var Vector2 = (function () {
  367. function Vector2(x, y) {
  368. this.x = x;
  369. this.y = y;
  370. }
  371. Vector2.prototype.toString = function () {
  372. return "{X: " + this.x + " Y:" + this.y + "}";
  373. };
  374. Vector2.prototype.getClassName = function () {
  375. return "Vector2";
  376. };
  377. Vector2.prototype.getHashCode = function () {
  378. var hash = this.x || 0;
  379. hash = (hash * 397) ^ (this.y || 0);
  380. return hash;
  381. };
  382. // Operators
  383. Vector2.prototype.toArray = function (array, index) {
  384. if (index === void 0) { index = 0; }
  385. array[index] = this.x;
  386. array[index + 1] = this.y;
  387. return this;
  388. };
  389. Vector2.prototype.asArray = function () {
  390. var result = [];
  391. this.toArray(result, 0);
  392. return result;
  393. };
  394. Vector2.prototype.copyFrom = function (source) {
  395. this.x = source.x;
  396. this.y = source.y;
  397. return this;
  398. };
  399. Vector2.prototype.copyFromFloats = function (x, y) {
  400. this.x = x;
  401. this.y = y;
  402. return this;
  403. };
  404. Vector2.prototype.add = function (otherVector) {
  405. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  406. };
  407. Vector2.prototype.addToRef = function (otherVector, result) {
  408. result.x = this.x + otherVector.x;
  409. result.y = this.y + otherVector.y;
  410. return this;
  411. };
  412. Vector2.prototype.addInPlace = function (otherVector) {
  413. this.x += otherVector.x;
  414. this.y += otherVector.y;
  415. return this;
  416. };
  417. Vector2.prototype.addVector3 = function (otherVector) {
  418. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  419. };
  420. Vector2.prototype.subtract = function (otherVector) {
  421. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  422. };
  423. Vector2.prototype.subtractToRef = function (otherVector, result) {
  424. result.x = this.x - otherVector.x;
  425. result.y = this.y - otherVector.y;
  426. return this;
  427. };
  428. Vector2.prototype.subtractInPlace = function (otherVector) {
  429. this.x -= otherVector.x;
  430. this.y -= otherVector.y;
  431. return this;
  432. };
  433. Vector2.prototype.multiplyInPlace = function (otherVector) {
  434. this.x *= otherVector.x;
  435. this.y *= otherVector.y;
  436. return this;
  437. };
  438. Vector2.prototype.multiply = function (otherVector) {
  439. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  440. };
  441. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  442. result.x = this.x * otherVector.x;
  443. result.y = this.y * otherVector.y;
  444. return this;
  445. };
  446. Vector2.prototype.multiplyByFloats = function (x, y) {
  447. return new Vector2(this.x * x, this.y * y);
  448. };
  449. Vector2.prototype.divide = function (otherVector) {
  450. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  451. };
  452. Vector2.prototype.divideToRef = function (otherVector, result) {
  453. result.x = this.x / otherVector.x;
  454. result.y = this.y / otherVector.y;
  455. return this;
  456. };
  457. Vector2.prototype.negate = function () {
  458. return new Vector2(-this.x, -this.y);
  459. };
  460. Vector2.prototype.scaleInPlace = function (scale) {
  461. this.x *= scale;
  462. this.y *= scale;
  463. return this;
  464. };
  465. Vector2.prototype.scale = function (scale) {
  466. return new Vector2(this.x * scale, this.y * scale);
  467. };
  468. Vector2.prototype.equals = function (otherVector) {
  469. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  470. };
  471. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  472. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  473. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  474. };
  475. // Properties
  476. Vector2.prototype.length = function () {
  477. return Math.sqrt(this.x * this.x + this.y * this.y);
  478. };
  479. Vector2.prototype.lengthSquared = function () {
  480. return (this.x * this.x + this.y * this.y);
  481. };
  482. // Methods
  483. Vector2.prototype.normalize = function () {
  484. var len = this.length();
  485. if (len === 0)
  486. return this;
  487. var num = 1.0 / len;
  488. this.x *= num;
  489. this.y *= num;
  490. return this;
  491. };
  492. Vector2.prototype.clone = function () {
  493. return new Vector2(this.x, this.y);
  494. };
  495. // Statics
  496. Vector2.Zero = function () {
  497. return new Vector2(0, 0);
  498. };
  499. Vector2.FromArray = function (array, offset) {
  500. if (offset === void 0) { offset = 0; }
  501. return new Vector2(array[offset], array[offset + 1]);
  502. };
  503. Vector2.FromArrayToRef = function (array, offset, result) {
  504. result.x = array[offset];
  505. result.y = array[offset + 1];
  506. };
  507. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  508. var squared = amount * amount;
  509. var cubed = amount * squared;
  510. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  511. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  512. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  513. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  514. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  515. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  516. return new Vector2(x, y);
  517. };
  518. Vector2.Clamp = function (value, min, max) {
  519. var x = value.x;
  520. x = (x > max.x) ? max.x : x;
  521. x = (x < min.x) ? min.x : x;
  522. var y = value.y;
  523. y = (y > max.y) ? max.y : y;
  524. y = (y < min.y) ? min.y : y;
  525. return new Vector2(x, y);
  526. };
  527. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  528. var squared = amount * amount;
  529. var cubed = amount * squared;
  530. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  531. var part2 = (-2.0 * cubed) + (3.0 * squared);
  532. var part3 = (cubed - (2.0 * squared)) + amount;
  533. var part4 = cubed - squared;
  534. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  535. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  536. return new Vector2(x, y);
  537. };
  538. Vector2.Lerp = function (start, end, amount) {
  539. var x = start.x + ((end.x - start.x) * amount);
  540. var y = start.y + ((end.y - start.y) * amount);
  541. return new Vector2(x, y);
  542. };
  543. Vector2.Dot = function (left, right) {
  544. return left.x * right.x + left.y * right.y;
  545. };
  546. Vector2.Normalize = function (vector) {
  547. var newVector = vector.clone();
  548. newVector.normalize();
  549. return newVector;
  550. };
  551. Vector2.Minimize = function (left, right) {
  552. var x = (left.x < right.x) ? left.x : right.x;
  553. var y = (left.y < right.y) ? left.y : right.y;
  554. return new Vector2(x, y);
  555. };
  556. Vector2.Maximize = function (left, right) {
  557. var x = (left.x > right.x) ? left.x : right.x;
  558. var y = (left.y > right.y) ? left.y : right.y;
  559. return new Vector2(x, y);
  560. };
  561. Vector2.Transform = function (vector, transformation) {
  562. var r = Vector2.Zero();
  563. Vector2.TransformToRef(vector, transformation, r);
  564. return r;
  565. };
  566. Vector2.TransformToRef = function (vector, transformation, result) {
  567. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  568. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  569. result.x = x;
  570. result.y = y;
  571. };
  572. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  573. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  574. var sign = a < 0 ? -1 : 1;
  575. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  576. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  577. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  578. };
  579. Vector2.Distance = function (value1, value2) {
  580. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  581. };
  582. Vector2.DistanceSquared = function (value1, value2) {
  583. var x = value1.x - value2.x;
  584. var y = value1.y - value2.y;
  585. return (x * x) + (y * y);
  586. };
  587. Vector2.Center = function (value1, value2) {
  588. var center = value1.add(value2);
  589. center.scaleInPlace(0.5);
  590. return center;
  591. };
  592. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  593. var l2 = Vector2.DistanceSquared(segA, segB);
  594. if (l2 === 0.0) {
  595. return Vector2.Distance(p, segA);
  596. }
  597. var v = segB.subtract(segA);
  598. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  599. var proj = segA.add(v.multiplyByFloats(t, t));
  600. return Vector2.Distance(p, proj);
  601. };
  602. return Vector2;
  603. }());
  604. BABYLON.Vector2 = Vector2;
  605. var Vector3 = (function () {
  606. function Vector3(x, y, z) {
  607. this.x = x;
  608. this.y = y;
  609. this.z = z;
  610. }
  611. Vector3.prototype.toString = function () {
  612. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  613. };
  614. Vector3.prototype.getClassName = function () {
  615. return "Vector3";
  616. };
  617. Vector3.prototype.getHashCode = function () {
  618. var hash = this.x || 0;
  619. hash = (hash * 397) ^ (this.y || 0);
  620. hash = (hash * 397) ^ (this.z || 0);
  621. return hash;
  622. };
  623. // Operators
  624. Vector3.prototype.asArray = function () {
  625. var result = [];
  626. this.toArray(result, 0);
  627. return result;
  628. };
  629. Vector3.prototype.toArray = function (array, index) {
  630. if (index === void 0) { index = 0; }
  631. array[index] = this.x;
  632. array[index + 1] = this.y;
  633. array[index + 2] = this.z;
  634. return this;
  635. };
  636. Vector3.prototype.toQuaternion = function () {
  637. var result = new Quaternion(0, 0, 0, 1);
  638. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  639. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  640. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  641. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  642. var cosy = Math.cos(this.y * 0.5);
  643. var siny = Math.sin(this.y * 0.5);
  644. result.x = coszMinusx * siny;
  645. result.y = -sinzMinusx * siny;
  646. result.z = sinxPlusz * cosy;
  647. result.w = cosxPlusz * cosy;
  648. return result;
  649. };
  650. Vector3.prototype.addInPlace = function (otherVector) {
  651. this.x += otherVector.x;
  652. this.y += otherVector.y;
  653. this.z += otherVector.z;
  654. return this;
  655. };
  656. Vector3.prototype.add = function (otherVector) {
  657. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  658. };
  659. Vector3.prototype.addToRef = function (otherVector, result) {
  660. result.x = this.x + otherVector.x;
  661. result.y = this.y + otherVector.y;
  662. result.z = this.z + otherVector.z;
  663. return this;
  664. };
  665. Vector3.prototype.subtractInPlace = function (otherVector) {
  666. this.x -= otherVector.x;
  667. this.y -= otherVector.y;
  668. this.z -= otherVector.z;
  669. return this;
  670. };
  671. Vector3.prototype.subtract = function (otherVector) {
  672. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  673. };
  674. Vector3.prototype.subtractToRef = function (otherVector, result) {
  675. result.x = this.x - otherVector.x;
  676. result.y = this.y - otherVector.y;
  677. result.z = this.z - otherVector.z;
  678. return this;
  679. };
  680. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  681. return new Vector3(this.x - x, this.y - y, this.z - z);
  682. };
  683. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  684. result.x = this.x - x;
  685. result.y = this.y - y;
  686. result.z = this.z - z;
  687. return this;
  688. };
  689. Vector3.prototype.negate = function () {
  690. return new Vector3(-this.x, -this.y, -this.z);
  691. };
  692. Vector3.prototype.scaleInPlace = function (scale) {
  693. this.x *= scale;
  694. this.y *= scale;
  695. this.z *= scale;
  696. return this;
  697. };
  698. Vector3.prototype.scale = function (scale) {
  699. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  700. };
  701. Vector3.prototype.scaleToRef = function (scale, result) {
  702. result.x = this.x * scale;
  703. result.y = this.y * scale;
  704. result.z = this.z * scale;
  705. };
  706. Vector3.prototype.equals = function (otherVector) {
  707. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  708. };
  709. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  710. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  711. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  712. };
  713. Vector3.prototype.equalsToFloats = function (x, y, z) {
  714. return this.x === x && this.y === y && this.z === z;
  715. };
  716. Vector3.prototype.multiplyInPlace = function (otherVector) {
  717. this.x *= otherVector.x;
  718. this.y *= otherVector.y;
  719. this.z *= otherVector.z;
  720. return this;
  721. };
  722. Vector3.prototype.multiply = function (otherVector) {
  723. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  724. };
  725. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  726. result.x = this.x * otherVector.x;
  727. result.y = this.y * otherVector.y;
  728. result.z = this.z * otherVector.z;
  729. return this;
  730. };
  731. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  732. return new Vector3(this.x * x, this.y * y, this.z * z);
  733. };
  734. Vector3.prototype.divide = function (otherVector) {
  735. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  736. };
  737. Vector3.prototype.divideToRef = function (otherVector, result) {
  738. result.x = this.x / otherVector.x;
  739. result.y = this.y / otherVector.y;
  740. result.z = this.z / otherVector.z;
  741. return this;
  742. };
  743. Vector3.prototype.MinimizeInPlace = function (other) {
  744. if (other.x < this.x)
  745. this.x = other.x;
  746. if (other.y < this.y)
  747. this.y = other.y;
  748. if (other.z < this.z)
  749. this.z = other.z;
  750. return this;
  751. };
  752. Vector3.prototype.MaximizeInPlace = function (other) {
  753. if (other.x > this.x)
  754. this.x = other.x;
  755. if (other.y > this.y)
  756. this.y = other.y;
  757. if (other.z > this.z)
  758. this.z = other.z;
  759. return this;
  760. };
  761. // Properties
  762. Vector3.prototype.length = function () {
  763. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  764. };
  765. Vector3.prototype.lengthSquared = function () {
  766. return (this.x * this.x + this.y * this.y + this.z * this.z);
  767. };
  768. // Methods
  769. Vector3.prototype.normalize = function () {
  770. var len = this.length();
  771. if (len === 0 || len === 1.0)
  772. return this;
  773. var num = 1.0 / len;
  774. this.x *= num;
  775. this.y *= num;
  776. this.z *= num;
  777. return this;
  778. };
  779. Vector3.prototype.clone = function () {
  780. return new Vector3(this.x, this.y, this.z);
  781. };
  782. Vector3.prototype.copyFrom = function (source) {
  783. this.x = source.x;
  784. this.y = source.y;
  785. this.z = source.z;
  786. return this;
  787. };
  788. Vector3.prototype.copyFromFloats = function (x, y, z) {
  789. this.x = x;
  790. this.y = y;
  791. this.z = z;
  792. return this;
  793. };
  794. // Statics
  795. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  796. var d0 = Vector3.Dot(vector0, axis) - size;
  797. var d1 = Vector3.Dot(vector1, axis) - size;
  798. var s = d0 / (d0 - d1);
  799. return s;
  800. };
  801. Vector3.FromArray = function (array, offset) {
  802. if (!offset) {
  803. offset = 0;
  804. }
  805. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  806. };
  807. Vector3.FromFloatArray = function (array, offset) {
  808. if (!offset) {
  809. offset = 0;
  810. }
  811. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  812. };
  813. Vector3.FromArrayToRef = function (array, offset, result) {
  814. result.x = array[offset];
  815. result.y = array[offset + 1];
  816. result.z = array[offset + 2];
  817. };
  818. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  819. result.x = array[offset];
  820. result.y = array[offset + 1];
  821. result.z = array[offset + 2];
  822. };
  823. Vector3.FromFloatsToRef = function (x, y, z, result) {
  824. result.x = x;
  825. result.y = y;
  826. result.z = z;
  827. };
  828. Vector3.Zero = function () {
  829. return new Vector3(0, 0, 0);
  830. };
  831. Vector3.Up = function () {
  832. return new Vector3(0, 1.0, 0);
  833. };
  834. Vector3.Forward = function () {
  835. return new Vector3(0, 0, 1.0);
  836. };
  837. Vector3.Right = function () {
  838. return new Vector3(1.0, 0, 0);
  839. };
  840. Vector3.Left = function () {
  841. return new Vector3(-1.0, 0, 0);
  842. };
  843. Vector3.TransformCoordinates = function (vector, transformation) {
  844. var result = Vector3.Zero();
  845. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  846. return result;
  847. };
  848. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  849. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  850. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  851. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  852. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  853. result.x = x / w;
  854. result.y = y / w;
  855. result.z = z / w;
  856. };
  857. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  858. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  859. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  860. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  861. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  862. result.x = rx / rw;
  863. result.y = ry / rw;
  864. result.z = rz / rw;
  865. };
  866. Vector3.TransformNormal = function (vector, transformation) {
  867. var result = Vector3.Zero();
  868. Vector3.TransformNormalToRef(vector, transformation, result);
  869. return result;
  870. };
  871. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  872. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  873. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  874. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  875. result.x = x;
  876. result.y = y;
  877. result.z = z;
  878. };
  879. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  880. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  881. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  882. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  883. };
  884. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  885. var squared = amount * amount;
  886. var cubed = amount * squared;
  887. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  888. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  889. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  890. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  891. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  892. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  893. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  894. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  895. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  896. return new Vector3(x, y, z);
  897. };
  898. Vector3.Clamp = function (value, min, max) {
  899. var x = value.x;
  900. x = (x > max.x) ? max.x : x;
  901. x = (x < min.x) ? min.x : x;
  902. var y = value.y;
  903. y = (y > max.y) ? max.y : y;
  904. y = (y < min.y) ? min.y : y;
  905. var z = value.z;
  906. z = (z > max.z) ? max.z : z;
  907. z = (z < min.z) ? min.z : z;
  908. return new Vector3(x, y, z);
  909. };
  910. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  911. var squared = amount * amount;
  912. var cubed = amount * squared;
  913. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  914. var part2 = (-2.0 * cubed) + (3.0 * squared);
  915. var part3 = (cubed - (2.0 * squared)) + amount;
  916. var part4 = cubed - squared;
  917. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  918. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  919. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  920. return new Vector3(x, y, z);
  921. };
  922. Vector3.Lerp = function (start, end, amount) {
  923. var result = new Vector3(0, 0, 0);
  924. Vector3.LerpToRef(start, end, amount, result);
  925. return result;
  926. };
  927. Vector3.LerpToRef = function (start, end, amount, result) {
  928. result.x = start.x + ((end.x - start.x) * amount);
  929. result.y = start.y + ((end.y - start.y) * amount);
  930. result.z = start.z + ((end.z - start.z) * amount);
  931. };
  932. Vector3.Dot = function (left, right) {
  933. return (left.x * right.x + left.y * right.y + left.z * right.z);
  934. };
  935. Vector3.Cross = function (left, right) {
  936. var result = Vector3.Zero();
  937. Vector3.CrossToRef(left, right, result);
  938. return result;
  939. };
  940. Vector3.CrossToRef = function (left, right, result) {
  941. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  942. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  943. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  944. result.copyFrom(Tmp.Vector3[0]);
  945. };
  946. Vector3.Normalize = function (vector) {
  947. var result = Vector3.Zero();
  948. Vector3.NormalizeToRef(vector, result);
  949. return result;
  950. };
  951. Vector3.NormalizeToRef = function (vector, result) {
  952. result.copyFrom(vector);
  953. result.normalize();
  954. };
  955. Vector3.Project = function (vector, world, transform, viewport) {
  956. var cw = viewport.width;
  957. var ch = viewport.height;
  958. var cx = viewport.x;
  959. var cy = viewport.y;
  960. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  961. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1, viewportMatrix);
  962. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  963. world.multiplyToRef(transform, matrix);
  964. matrix.multiplyToRef(viewportMatrix, matrix);
  965. return Vector3.TransformCoordinates(vector, matrix);
  966. };
  967. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  968. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  969. world.multiplyToRef(transform, matrix);
  970. matrix.invert();
  971. source.x = source.x / viewportWidth * 2 - 1;
  972. source.y = -(source.y / viewportHeight * 2 - 1);
  973. var vector = Vector3.TransformCoordinates(source, matrix);
  974. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  975. if (MathTools.WithinEpsilon(num, 1.0)) {
  976. vector = vector.scale(1.0 / num);
  977. }
  978. return vector;
  979. };
  980. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  981. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  982. world.multiplyToRef(view, matrix);
  983. matrix.multiplyToRef(projection, matrix);
  984. matrix.invert();
  985. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  986. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  987. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  988. if (MathTools.WithinEpsilon(num, 1.0)) {
  989. vector = vector.scale(1.0 / num);
  990. }
  991. return vector;
  992. };
  993. Vector3.Minimize = function (left, right) {
  994. var min = left.clone();
  995. min.MinimizeInPlace(right);
  996. return min;
  997. };
  998. Vector3.Maximize = function (left, right) {
  999. var max = left.clone();
  1000. max.MaximizeInPlace(right);
  1001. return max;
  1002. };
  1003. Vector3.Distance = function (value1, value2) {
  1004. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1005. };
  1006. Vector3.DistanceSquared = function (value1, value2) {
  1007. var x = value1.x - value2.x;
  1008. var y = value1.y - value2.y;
  1009. var z = value1.z - value2.z;
  1010. return (x * x) + (y * y) + (z * z);
  1011. };
  1012. Vector3.Center = function (value1, value2) {
  1013. var center = value1.add(value2);
  1014. center.scaleInPlace(0.5);
  1015. return center;
  1016. };
  1017. /**
  1018. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1019. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1020. * to something in order to rotate it from its local system to the given target system.
  1021. */
  1022. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1023. var rotation = Vector3.Zero();
  1024. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1025. return rotation;
  1026. };
  1027. /**
  1028. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1029. */
  1030. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1031. var u = axis1.normalize();
  1032. var w = axis3.normalize();
  1033. // world axis
  1034. var X = Axis.X;
  1035. var Y = Axis.Y;
  1036. // equation unknowns and vars
  1037. var yaw = 0.0;
  1038. var pitch = 0.0;
  1039. var roll = 0.0;
  1040. var x = 0.0;
  1041. var y = 0.0;
  1042. var z = 0.0;
  1043. var t = 0.0;
  1044. var sign = -1.0;
  1045. var nbRevert = 0;
  1046. var cross = Tmp.Vector3[0];
  1047. var dot = 0.0;
  1048. // step 1 : rotation around w
  1049. // Rv3(u) = u1, and u1 belongs to plane xOz
  1050. // Rv3(w) = w1 = w invariant
  1051. var u1 = Tmp.Vector3[1];
  1052. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1053. z = 1.0;
  1054. }
  1055. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1056. x = 1.0;
  1057. }
  1058. else {
  1059. t = w.z / w.x;
  1060. x = -t * Math.sqrt(1 / (1 + t * t));
  1061. z = Math.sqrt(1 / (1 + t * t));
  1062. }
  1063. u1.x = x;
  1064. u1.y = y;
  1065. u1.z = z;
  1066. u1.normalize();
  1067. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1068. cross.normalize();
  1069. if (Vector3.Dot(w, cross) < 0) {
  1070. sign = 1.0;
  1071. }
  1072. dot = Vector3.Dot(u, u1);
  1073. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1074. roll = Math.acos(dot) * sign;
  1075. if (Vector3.Dot(u1, X) < 0) {
  1076. roll = Math.PI + roll;
  1077. u1 = u1.scaleInPlace(-1);
  1078. nbRevert++;
  1079. }
  1080. // step 2 : rotate around u1
  1081. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1082. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1083. var w2 = Tmp.Vector3[2];
  1084. var v2 = Tmp.Vector3[3];
  1085. x = 0.0;
  1086. y = 0.0;
  1087. z = 0.0;
  1088. sign = -1.0;
  1089. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1090. x = 1.0;
  1091. }
  1092. else {
  1093. t = u1.z / u1.x;
  1094. x = -t * Math.sqrt(1 / (1 + t * t));
  1095. z = Math.sqrt(1 / (1 + t * t));
  1096. }
  1097. w2.x = x;
  1098. w2.y = y;
  1099. w2.z = z;
  1100. w2.normalize();
  1101. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1102. v2.normalize();
  1103. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1104. cross.normalize();
  1105. if (Vector3.Dot(u1, cross) < 0) {
  1106. sign = 1.0;
  1107. }
  1108. dot = Vector3.Dot(w, w2);
  1109. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1110. pitch = Math.acos(dot) * sign;
  1111. if (Vector3.Dot(v2, Y) < 0) {
  1112. pitch = Math.PI + pitch;
  1113. nbRevert++;
  1114. }
  1115. // step 3 : rotate around v2
  1116. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1117. sign = -1.0;
  1118. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1119. cross.normalize();
  1120. if (Vector3.Dot(cross, Y) < 0) {
  1121. sign = 1.0;
  1122. }
  1123. dot = Vector3.Dot(u1, X);
  1124. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1125. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1126. if (dot < 0 && nbRevert < 2) {
  1127. yaw = Math.PI + yaw;
  1128. }
  1129. ref.x = pitch;
  1130. ref.y = yaw;
  1131. ref.z = roll;
  1132. };
  1133. return Vector3;
  1134. }());
  1135. BABYLON.Vector3 = Vector3;
  1136. //Vector4 class created for EulerAngle class conversion to Quaternion
  1137. var Vector4 = (function () {
  1138. function Vector4(x, y, z, w) {
  1139. this.x = x;
  1140. this.y = y;
  1141. this.z = z;
  1142. this.w = w;
  1143. }
  1144. Vector4.prototype.toString = function () {
  1145. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1146. };
  1147. Vector4.prototype.getClassName = function () {
  1148. return "Vector4";
  1149. };
  1150. Vector4.prototype.getHashCode = function () {
  1151. var hash = this.x || 0;
  1152. hash = (hash * 397) ^ (this.y || 0);
  1153. hash = (hash * 397) ^ (this.z || 0);
  1154. hash = (hash * 397) ^ (this.w || 0);
  1155. return hash;
  1156. };
  1157. // Operators
  1158. Vector4.prototype.asArray = function () {
  1159. var result = [];
  1160. this.toArray(result, 0);
  1161. return result;
  1162. };
  1163. Vector4.prototype.toArray = function (array, index) {
  1164. if (index === undefined) {
  1165. index = 0;
  1166. }
  1167. array[index] = this.x;
  1168. array[index + 1] = this.y;
  1169. array[index + 2] = this.z;
  1170. array[index + 3] = this.w;
  1171. return this;
  1172. };
  1173. Vector4.prototype.addInPlace = function (otherVector) {
  1174. this.x += otherVector.x;
  1175. this.y += otherVector.y;
  1176. this.z += otherVector.z;
  1177. this.w += otherVector.w;
  1178. return this;
  1179. };
  1180. Vector4.prototype.add = function (otherVector) {
  1181. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1182. };
  1183. Vector4.prototype.addToRef = function (otherVector, result) {
  1184. result.x = this.x + otherVector.x;
  1185. result.y = this.y + otherVector.y;
  1186. result.z = this.z + otherVector.z;
  1187. result.w = this.w + otherVector.w;
  1188. return this;
  1189. };
  1190. Vector4.prototype.subtractInPlace = function (otherVector) {
  1191. this.x -= otherVector.x;
  1192. this.y -= otherVector.y;
  1193. this.z -= otherVector.z;
  1194. this.w -= otherVector.w;
  1195. return this;
  1196. };
  1197. Vector4.prototype.subtract = function (otherVector) {
  1198. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1199. };
  1200. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1201. result.x = this.x - otherVector.x;
  1202. result.y = this.y - otherVector.y;
  1203. result.z = this.z - otherVector.z;
  1204. result.w = this.w - otherVector.w;
  1205. return this;
  1206. };
  1207. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1208. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1209. };
  1210. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1211. result.x = this.x - x;
  1212. result.y = this.y - y;
  1213. result.z = this.z - z;
  1214. result.w = this.w - w;
  1215. return this;
  1216. };
  1217. Vector4.prototype.negate = function () {
  1218. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1219. };
  1220. Vector4.prototype.scaleInPlace = function (scale) {
  1221. this.x *= scale;
  1222. this.y *= scale;
  1223. this.z *= scale;
  1224. this.w *= scale;
  1225. return this;
  1226. };
  1227. Vector4.prototype.scale = function (scale) {
  1228. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1229. };
  1230. Vector4.prototype.scaleToRef = function (scale, result) {
  1231. result.x = this.x * scale;
  1232. result.y = this.y * scale;
  1233. result.z = this.z * scale;
  1234. result.w = this.w * scale;
  1235. };
  1236. Vector4.prototype.equals = function (otherVector) {
  1237. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1238. };
  1239. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1240. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1241. return otherVector
  1242. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1243. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1244. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1245. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1246. };
  1247. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1248. return this.x === x && this.y === y && this.z === z && this.w === w;
  1249. };
  1250. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1251. this.x *= otherVector.x;
  1252. this.y *= otherVector.y;
  1253. this.z *= otherVector.z;
  1254. this.w *= otherVector.w;
  1255. return this;
  1256. };
  1257. Vector4.prototype.multiply = function (otherVector) {
  1258. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1259. };
  1260. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1261. result.x = this.x * otherVector.x;
  1262. result.y = this.y * otherVector.y;
  1263. result.z = this.z * otherVector.z;
  1264. result.w = this.w * otherVector.w;
  1265. return this;
  1266. };
  1267. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1268. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1269. };
  1270. Vector4.prototype.divide = function (otherVector) {
  1271. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1272. };
  1273. Vector4.prototype.divideToRef = function (otherVector, result) {
  1274. result.x = this.x / otherVector.x;
  1275. result.y = this.y / otherVector.y;
  1276. result.z = this.z / otherVector.z;
  1277. result.w = this.w / otherVector.w;
  1278. return this;
  1279. };
  1280. Vector4.prototype.MinimizeInPlace = function (other) {
  1281. if (other.x < this.x)
  1282. this.x = other.x;
  1283. if (other.y < this.y)
  1284. this.y = other.y;
  1285. if (other.z < this.z)
  1286. this.z = other.z;
  1287. if (other.w < this.w)
  1288. this.w = other.w;
  1289. return this;
  1290. };
  1291. Vector4.prototype.MaximizeInPlace = function (other) {
  1292. if (other.x > this.x)
  1293. this.x = other.x;
  1294. if (other.y > this.y)
  1295. this.y = other.y;
  1296. if (other.z > this.z)
  1297. this.z = other.z;
  1298. if (other.w > this.w)
  1299. this.w = other.w;
  1300. return this;
  1301. };
  1302. // Properties
  1303. Vector4.prototype.length = function () {
  1304. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1305. };
  1306. Vector4.prototype.lengthSquared = function () {
  1307. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1308. };
  1309. // Methods
  1310. Vector4.prototype.normalize = function () {
  1311. var len = this.length();
  1312. if (len === 0)
  1313. return this;
  1314. var num = 1.0 / len;
  1315. this.x *= num;
  1316. this.y *= num;
  1317. this.z *= num;
  1318. this.w *= num;
  1319. return this;
  1320. };
  1321. Vector4.prototype.toVector3 = function () {
  1322. return new Vector3(this.x, this.y, this.z);
  1323. };
  1324. Vector4.prototype.clone = function () {
  1325. return new Vector4(this.x, this.y, this.z, this.w);
  1326. };
  1327. Vector4.prototype.copyFrom = function (source) {
  1328. this.x = source.x;
  1329. this.y = source.y;
  1330. this.z = source.z;
  1331. this.w = source.w;
  1332. return this;
  1333. };
  1334. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1335. this.x = x;
  1336. this.y = y;
  1337. this.z = z;
  1338. this.w = w;
  1339. return this;
  1340. };
  1341. // Statics
  1342. Vector4.FromArray = function (array, offset) {
  1343. if (!offset) {
  1344. offset = 0;
  1345. }
  1346. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1347. };
  1348. Vector4.FromArrayToRef = function (array, offset, result) {
  1349. result.x = array[offset];
  1350. result.y = array[offset + 1];
  1351. result.z = array[offset + 2];
  1352. result.w = array[offset + 3];
  1353. };
  1354. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1355. result.x = array[offset];
  1356. result.y = array[offset + 1];
  1357. result.z = array[offset + 2];
  1358. result.w = array[offset + 3];
  1359. };
  1360. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1361. result.x = x;
  1362. result.y = y;
  1363. result.z = z;
  1364. result.w = w;
  1365. };
  1366. Vector4.Zero = function () {
  1367. return new Vector4(0, 0, 0, 0);
  1368. };
  1369. Vector4.Normalize = function (vector) {
  1370. var result = Vector4.Zero();
  1371. Vector4.NormalizeToRef(vector, result);
  1372. return result;
  1373. };
  1374. Vector4.NormalizeToRef = function (vector, result) {
  1375. result.copyFrom(vector);
  1376. result.normalize();
  1377. };
  1378. Vector4.Minimize = function (left, right) {
  1379. var min = left.clone();
  1380. min.MinimizeInPlace(right);
  1381. return min;
  1382. };
  1383. Vector4.Maximize = function (left, right) {
  1384. var max = left.clone();
  1385. max.MaximizeInPlace(right);
  1386. return max;
  1387. };
  1388. Vector4.Distance = function (value1, value2) {
  1389. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1390. };
  1391. Vector4.DistanceSquared = function (value1, value2) {
  1392. var x = value1.x - value2.x;
  1393. var y = value1.y - value2.y;
  1394. var z = value1.z - value2.z;
  1395. var w = value1.w - value2.w;
  1396. return (x * x) + (y * y) + (z * z) + (w * w);
  1397. };
  1398. Vector4.Center = function (value1, value2) {
  1399. var center = value1.add(value2);
  1400. center.scaleInPlace(0.5);
  1401. return center;
  1402. };
  1403. return Vector4;
  1404. }());
  1405. BABYLON.Vector4 = Vector4;
  1406. var Size = (function () {
  1407. function Size(width, height) {
  1408. this.width = width;
  1409. this.height = height;
  1410. }
  1411. Size.prototype.toString = function () {
  1412. return "{W: " + this.width + ", H: " + this.height + "}";
  1413. };
  1414. Size.prototype.getClassName = function () {
  1415. return "Size";
  1416. };
  1417. Size.prototype.getHashCode = function () {
  1418. var hash = this.width || 0;
  1419. hash = (hash * 397) ^ (this.height || 0);
  1420. return hash;
  1421. };
  1422. Size.prototype.copyFrom = function (src) {
  1423. this.width = src.width;
  1424. this.height = src.height;
  1425. };
  1426. Size.prototype.copyFromFloats = function (width, height) {
  1427. this.width = width;
  1428. this.height = height;
  1429. };
  1430. Size.prototype.multiplyByFloats = function (w, h) {
  1431. return new Size(this.width * w, this.height * h);
  1432. };
  1433. Size.prototype.clone = function () {
  1434. return new Size(this.width, this.height);
  1435. };
  1436. Size.prototype.equals = function (other) {
  1437. if (!other) {
  1438. return false;
  1439. }
  1440. return (this.width === other.width) && (this.height === other.height);
  1441. };
  1442. Object.defineProperty(Size.prototype, "surface", {
  1443. get: function () {
  1444. return this.width * this.height;
  1445. },
  1446. enumerable: true,
  1447. configurable: true
  1448. });
  1449. Size.Zero = function () {
  1450. return new Size(0, 0);
  1451. };
  1452. Size.prototype.add = function (otherSize) {
  1453. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1454. return r;
  1455. };
  1456. Size.prototype.substract = function (otherSize) {
  1457. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1458. return r;
  1459. };
  1460. Size.Lerp = function (start, end, amount) {
  1461. var w = start.width + ((end.width - start.width) * amount);
  1462. var h = start.height + ((end.height - start.height) * amount);
  1463. return new Size(w, h);
  1464. };
  1465. return Size;
  1466. }());
  1467. BABYLON.Size = Size;
  1468. var Quaternion = (function () {
  1469. function Quaternion(x, y, z, w) {
  1470. if (x === void 0) { x = 0; }
  1471. if (y === void 0) { y = 0; }
  1472. if (z === void 0) { z = 0; }
  1473. if (w === void 0) { w = 1; }
  1474. this.x = x;
  1475. this.y = y;
  1476. this.z = z;
  1477. this.w = w;
  1478. }
  1479. Quaternion.prototype.toString = function () {
  1480. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1481. };
  1482. Quaternion.prototype.getClassName = function () {
  1483. return "Quaternion";
  1484. };
  1485. Quaternion.prototype.getHashCode = function () {
  1486. var hash = this.x || 0;
  1487. hash = (hash * 397) ^ (this.y || 0);
  1488. hash = (hash * 397) ^ (this.z || 0);
  1489. hash = (hash * 397) ^ (this.w || 0);
  1490. return hash;
  1491. };
  1492. Quaternion.prototype.asArray = function () {
  1493. return [this.x, this.y, this.z, this.w];
  1494. };
  1495. Quaternion.prototype.equals = function (otherQuaternion) {
  1496. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1497. };
  1498. Quaternion.prototype.clone = function () {
  1499. return new Quaternion(this.x, this.y, this.z, this.w);
  1500. };
  1501. Quaternion.prototype.copyFrom = function (other) {
  1502. this.x = other.x;
  1503. this.y = other.y;
  1504. this.z = other.z;
  1505. this.w = other.w;
  1506. return this;
  1507. };
  1508. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1509. this.x = x;
  1510. this.y = y;
  1511. this.z = z;
  1512. this.w = w;
  1513. return this;
  1514. };
  1515. Quaternion.prototype.add = function (other) {
  1516. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1517. };
  1518. Quaternion.prototype.subtract = function (other) {
  1519. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1520. };
  1521. Quaternion.prototype.scale = function (value) {
  1522. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1523. };
  1524. Quaternion.prototype.multiply = function (q1) {
  1525. var result = new Quaternion(0, 0, 0, 1.0);
  1526. this.multiplyToRef(q1, result);
  1527. return result;
  1528. };
  1529. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1530. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1531. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1532. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1533. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1534. result.copyFromFloats(x, y, z, w);
  1535. return this;
  1536. };
  1537. Quaternion.prototype.multiplyInPlace = function (q1) {
  1538. this.multiplyToRef(q1, this);
  1539. return this;
  1540. };
  1541. Quaternion.prototype.conjugateToRef = function (ref) {
  1542. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1543. return this;
  1544. };
  1545. Quaternion.prototype.conjugateInPlace = function () {
  1546. this.x *= -1;
  1547. this.y *= -1;
  1548. this.z *= -1;
  1549. return this;
  1550. };
  1551. Quaternion.prototype.conjugate = function () {
  1552. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1553. return result;
  1554. };
  1555. Quaternion.prototype.length = function () {
  1556. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1557. };
  1558. Quaternion.prototype.normalize = function () {
  1559. var length = 1.0 / this.length();
  1560. this.x *= length;
  1561. this.y *= length;
  1562. this.z *= length;
  1563. this.w *= length;
  1564. return this;
  1565. };
  1566. Quaternion.prototype.toEulerAngles = function (order) {
  1567. if (order === void 0) { order = "YZX"; }
  1568. var result = Vector3.Zero();
  1569. this.toEulerAnglesToRef(result, order);
  1570. return result;
  1571. };
  1572. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1573. if (order === void 0) { order = "YZX"; }
  1574. var qz = this.z;
  1575. var qx = this.x;
  1576. var qy = this.y;
  1577. var qw = this.w;
  1578. var sqw = qw * qw;
  1579. var sqz = qz * qz;
  1580. var sqx = qx * qx;
  1581. var sqy = qy * qy;
  1582. var zAxisY = qy * qz - qx * qw;
  1583. var limit = .4999999;
  1584. if (zAxisY < -limit) {
  1585. result.y = 2 * Math.atan2(qy, qw);
  1586. result.x = Math.PI / 2;
  1587. result.z = 0;
  1588. }
  1589. else if (zAxisY > limit) {
  1590. result.y = 2 * Math.atan2(qy, qw);
  1591. result.x = -Math.PI / 2;
  1592. result.z = 0;
  1593. }
  1594. else {
  1595. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  1596. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  1597. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  1598. }
  1599. return this;
  1600. };
  1601. Quaternion.prototype.toRotationMatrix = function (result) {
  1602. var xx = this.x * this.x;
  1603. var yy = this.y * this.y;
  1604. var zz = this.z * this.z;
  1605. var xy = this.x * this.y;
  1606. var zw = this.z * this.w;
  1607. var zx = this.z * this.x;
  1608. var yw = this.y * this.w;
  1609. var yz = this.y * this.z;
  1610. var xw = this.x * this.w;
  1611. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1612. result.m[1] = 2.0 * (xy + zw);
  1613. result.m[2] = 2.0 * (zx - yw);
  1614. result.m[3] = 0;
  1615. result.m[4] = 2.0 * (xy - zw);
  1616. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1617. result.m[6] = 2.0 * (yz + xw);
  1618. result.m[7] = 0;
  1619. result.m[8] = 2.0 * (zx + yw);
  1620. result.m[9] = 2.0 * (yz - xw);
  1621. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1622. result.m[11] = 0;
  1623. result.m[12] = 0;
  1624. result.m[13] = 0;
  1625. result.m[14] = 0;
  1626. result.m[15] = 1.0;
  1627. return this;
  1628. };
  1629. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1630. Quaternion.FromRotationMatrixToRef(matrix, this);
  1631. return this;
  1632. };
  1633. // Statics
  1634. Quaternion.FromRotationMatrix = function (matrix) {
  1635. var result = new Quaternion();
  1636. Quaternion.FromRotationMatrixToRef(matrix, result);
  1637. return result;
  1638. };
  1639. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1640. var data = matrix.m;
  1641. var m11 = data[0], m12 = data[4], m13 = data[8];
  1642. var m21 = data[1], m22 = data[5], m23 = data[9];
  1643. var m31 = data[2], m32 = data[6], m33 = data[10];
  1644. var trace = m11 + m22 + m33;
  1645. var s;
  1646. if (trace > 0) {
  1647. s = 0.5 / Math.sqrt(trace + 1.0);
  1648. result.w = 0.25 / s;
  1649. result.x = (m32 - m23) * s;
  1650. result.y = (m13 - m31) * s;
  1651. result.z = (m21 - m12) * s;
  1652. }
  1653. else if (m11 > m22 && m11 > m33) {
  1654. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1655. result.w = (m32 - m23) / s;
  1656. result.x = 0.25 * s;
  1657. result.y = (m12 + m21) / s;
  1658. result.z = (m13 + m31) / s;
  1659. }
  1660. else if (m22 > m33) {
  1661. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1662. result.w = (m13 - m31) / s;
  1663. result.x = (m12 + m21) / s;
  1664. result.y = 0.25 * s;
  1665. result.z = (m23 + m32) / s;
  1666. }
  1667. else {
  1668. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1669. result.w = (m21 - m12) / s;
  1670. result.x = (m13 + m31) / s;
  1671. result.y = (m23 + m32) / s;
  1672. result.z = 0.25 * s;
  1673. }
  1674. };
  1675. Quaternion.Inverse = function (q) {
  1676. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1677. };
  1678. Quaternion.Identity = function () {
  1679. return new Quaternion(0, 0, 0, 1);
  1680. };
  1681. Quaternion.RotationAxis = function (axis, angle) {
  1682. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1683. };
  1684. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1685. var sin = Math.sin(angle / 2);
  1686. axis.normalize();
  1687. result.w = Math.cos(angle / 2);
  1688. result.x = axis.x * sin;
  1689. result.y = axis.y * sin;
  1690. result.z = axis.z * sin;
  1691. return result;
  1692. };
  1693. Quaternion.FromArray = function (array, offset) {
  1694. if (!offset) {
  1695. offset = 0;
  1696. }
  1697. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1698. };
  1699. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1700. var q = new Quaternion();
  1701. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1702. return q;
  1703. };
  1704. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1705. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1706. var halfRoll = roll * 0.5;
  1707. var halfPitch = pitch * 0.5;
  1708. var halfYaw = yaw * 0.5;
  1709. var sinRoll = Math.sin(halfRoll);
  1710. var cosRoll = Math.cos(halfRoll);
  1711. var sinPitch = Math.sin(halfPitch);
  1712. var cosPitch = Math.cos(halfPitch);
  1713. var sinYaw = Math.sin(halfYaw);
  1714. var cosYaw = Math.cos(halfYaw);
  1715. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1716. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1717. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1718. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1719. };
  1720. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1721. var result = new Quaternion();
  1722. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1723. return result;
  1724. };
  1725. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1726. // Produces a quaternion from Euler angles in the z-x-z orientation
  1727. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1728. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1729. var halfBeta = beta * 0.5;
  1730. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1731. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1732. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1733. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1734. };
  1735. Quaternion.Slerp = function (left, right, amount) {
  1736. var result = Quaternion.Identity();
  1737. Quaternion.SlerpToRef(left, right, amount, result);
  1738. return result;
  1739. };
  1740. Quaternion.SlerpToRef = function (left, right, amount, result) {
  1741. var num2;
  1742. var num3;
  1743. var num = amount;
  1744. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1745. var flag = false;
  1746. if (num4 < 0) {
  1747. flag = true;
  1748. num4 = -num4;
  1749. }
  1750. if (num4 > 0.999999) {
  1751. num3 = 1 - num;
  1752. num2 = flag ? -num : num;
  1753. }
  1754. else {
  1755. var num5 = Math.acos(num4);
  1756. var num6 = (1.0 / Math.sin(num5));
  1757. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1758. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1759. }
  1760. result.x = (num3 * left.x) + (num2 * right.x);
  1761. result.y = (num3 * left.y) + (num2 * right.y);
  1762. result.z = (num3 * left.z) + (num2 * right.z);
  1763. result.w = (num3 * left.w) + (num2 * right.w);
  1764. };
  1765. return Quaternion;
  1766. }());
  1767. BABYLON.Quaternion = Quaternion;
  1768. var Matrix = (function () {
  1769. function Matrix() {
  1770. this.m = new Float32Array(16);
  1771. }
  1772. // Properties
  1773. Matrix.prototype.isIdentity = function () {
  1774. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1775. return false;
  1776. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1777. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1778. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1779. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1780. return false;
  1781. return true;
  1782. };
  1783. Matrix.prototype.determinant = function () {
  1784. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1785. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1786. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1787. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1788. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1789. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1790. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1791. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1792. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1793. };
  1794. // Methods
  1795. Matrix.prototype.toArray = function () {
  1796. return this.m;
  1797. };
  1798. Matrix.prototype.asArray = function () {
  1799. return this.toArray();
  1800. };
  1801. Matrix.prototype.invert = function () {
  1802. this.invertToRef(this);
  1803. return this;
  1804. };
  1805. Matrix.prototype.reset = function () {
  1806. for (var index = 0; index < 16; index++) {
  1807. this.m[index] = 0;
  1808. }
  1809. return this;
  1810. };
  1811. Matrix.prototype.add = function (other) {
  1812. var result = new Matrix();
  1813. this.addToRef(other, result);
  1814. return result;
  1815. };
  1816. Matrix.prototype.addToRef = function (other, result) {
  1817. for (var index = 0; index < 16; index++) {
  1818. result.m[index] = this.m[index] + other.m[index];
  1819. }
  1820. return this;
  1821. };
  1822. Matrix.prototype.addToSelf = function (other) {
  1823. for (var index = 0; index < 16; index++) {
  1824. this.m[index] += other.m[index];
  1825. }
  1826. return this;
  1827. };
  1828. Matrix.prototype.invertToRef = function (other) {
  1829. var l1 = this.m[0];
  1830. var l2 = this.m[1];
  1831. var l3 = this.m[2];
  1832. var l4 = this.m[3];
  1833. var l5 = this.m[4];
  1834. var l6 = this.m[5];
  1835. var l7 = this.m[6];
  1836. var l8 = this.m[7];
  1837. var l9 = this.m[8];
  1838. var l10 = this.m[9];
  1839. var l11 = this.m[10];
  1840. var l12 = this.m[11];
  1841. var l13 = this.m[12];
  1842. var l14 = this.m[13];
  1843. var l15 = this.m[14];
  1844. var l16 = this.m[15];
  1845. var l17 = (l11 * l16) - (l12 * l15);
  1846. var l18 = (l10 * l16) - (l12 * l14);
  1847. var l19 = (l10 * l15) - (l11 * l14);
  1848. var l20 = (l9 * l16) - (l12 * l13);
  1849. var l21 = (l9 * l15) - (l11 * l13);
  1850. var l22 = (l9 * l14) - (l10 * l13);
  1851. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1852. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1853. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1854. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1855. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1856. var l28 = (l7 * l16) - (l8 * l15);
  1857. var l29 = (l6 * l16) - (l8 * l14);
  1858. var l30 = (l6 * l15) - (l7 * l14);
  1859. var l31 = (l5 * l16) - (l8 * l13);
  1860. var l32 = (l5 * l15) - (l7 * l13);
  1861. var l33 = (l5 * l14) - (l6 * l13);
  1862. var l34 = (l7 * l12) - (l8 * l11);
  1863. var l35 = (l6 * l12) - (l8 * l10);
  1864. var l36 = (l6 * l11) - (l7 * l10);
  1865. var l37 = (l5 * l12) - (l8 * l9);
  1866. var l38 = (l5 * l11) - (l7 * l9);
  1867. var l39 = (l5 * l10) - (l6 * l9);
  1868. other.m[0] = l23 * l27;
  1869. other.m[4] = l24 * l27;
  1870. other.m[8] = l25 * l27;
  1871. other.m[12] = l26 * l27;
  1872. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1873. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1874. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1875. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1876. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1877. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1878. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1879. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1880. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1881. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1882. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1883. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1884. return this;
  1885. };
  1886. Matrix.prototype.setTranslation = function (vector3) {
  1887. this.m[12] = vector3.x;
  1888. this.m[13] = vector3.y;
  1889. this.m[14] = vector3.z;
  1890. return this;
  1891. };
  1892. Matrix.prototype.getTranslation = function () {
  1893. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1894. };
  1895. Matrix.prototype.multiply = function (other) {
  1896. var result = new Matrix();
  1897. this.multiplyToRef(other, result);
  1898. return result;
  1899. };
  1900. Matrix.prototype.copyFrom = function (other) {
  1901. for (var index = 0; index < 16; index++) {
  1902. this.m[index] = other.m[index];
  1903. }
  1904. return this;
  1905. };
  1906. Matrix.prototype.copyToArray = function (array, offset) {
  1907. if (offset === void 0) { offset = 0; }
  1908. for (var index = 0; index < 16; index++) {
  1909. array[offset + index] = this.m[index];
  1910. }
  1911. return this;
  1912. };
  1913. Matrix.prototype.multiplyToRef = function (other, result) {
  1914. this.multiplyToArray(other, result.m, 0);
  1915. return this;
  1916. };
  1917. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1918. var tm0 = this.m[0];
  1919. var tm1 = this.m[1];
  1920. var tm2 = this.m[2];
  1921. var tm3 = this.m[3];
  1922. var tm4 = this.m[4];
  1923. var tm5 = this.m[5];
  1924. var tm6 = this.m[6];
  1925. var tm7 = this.m[7];
  1926. var tm8 = this.m[8];
  1927. var tm9 = this.m[9];
  1928. var tm10 = this.m[10];
  1929. var tm11 = this.m[11];
  1930. var tm12 = this.m[12];
  1931. var tm13 = this.m[13];
  1932. var tm14 = this.m[14];
  1933. var tm15 = this.m[15];
  1934. var om0 = other.m[0];
  1935. var om1 = other.m[1];
  1936. var om2 = other.m[2];
  1937. var om3 = other.m[3];
  1938. var om4 = other.m[4];
  1939. var om5 = other.m[5];
  1940. var om6 = other.m[6];
  1941. var om7 = other.m[7];
  1942. var om8 = other.m[8];
  1943. var om9 = other.m[9];
  1944. var om10 = other.m[10];
  1945. var om11 = other.m[11];
  1946. var om12 = other.m[12];
  1947. var om13 = other.m[13];
  1948. var om14 = other.m[14];
  1949. var om15 = other.m[15];
  1950. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1951. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1952. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1953. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1954. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1955. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1956. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1957. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1958. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1959. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1960. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1961. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1962. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1963. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1964. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1965. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1966. return this;
  1967. };
  1968. Matrix.prototype.equals = function (value) {
  1969. return value &&
  1970. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1971. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1972. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1973. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1974. };
  1975. Matrix.prototype.clone = function () {
  1976. 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]);
  1977. };
  1978. Matrix.prototype.getClassName = function () {
  1979. return "Matrix";
  1980. };
  1981. Matrix.prototype.getHashCode = function () {
  1982. var hash = this.m[0] || 0;
  1983. for (var i = 1; i < 16; i++) {
  1984. hash = (hash * 397) ^ (this.m[i] || 0);
  1985. }
  1986. return hash;
  1987. };
  1988. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1989. translation.x = this.m[12];
  1990. translation.y = this.m[13];
  1991. translation.z = this.m[14];
  1992. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1993. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1994. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1995. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1996. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1997. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1998. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1999. rotation.x = 0;
  2000. rotation.y = 0;
  2001. rotation.z = 0;
  2002. rotation.w = 1;
  2003. return false;
  2004. }
  2005. 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, Tmp.Matrix[0]);
  2006. Quaternion.FromRotationMatrixToRef(Tmp.Matrix[0], rotation);
  2007. return true;
  2008. };
  2009. Matrix.prototype.getRotationMatrix = function () {
  2010. var result = Matrix.Identity();
  2011. this.getRotationMatrixToRef(result);
  2012. return result;
  2013. };
  2014. Matrix.prototype.getRotationMatrixToRef = function (result) {
  2015. var m = this.m;
  2016. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  2017. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  2018. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  2019. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  2020. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  2021. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  2022. 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);
  2023. };
  2024. // Statics
  2025. Matrix.FromArray = function (array, offset) {
  2026. var result = new Matrix();
  2027. if (!offset) {
  2028. offset = 0;
  2029. }
  2030. Matrix.FromArrayToRef(array, offset, result);
  2031. return result;
  2032. };
  2033. Matrix.FromArrayToRef = function (array, offset, result) {
  2034. for (var index = 0; index < 16; index++) {
  2035. result.m[index] = array[index + offset];
  2036. }
  2037. };
  2038. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2039. for (var index = 0; index < 16; index++) {
  2040. result.m[index] = array[index + offset] * scale;
  2041. }
  2042. };
  2043. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2044. result.m[0] = initialM11;
  2045. result.m[1] = initialM12;
  2046. result.m[2] = initialM13;
  2047. result.m[3] = initialM14;
  2048. result.m[4] = initialM21;
  2049. result.m[5] = initialM22;
  2050. result.m[6] = initialM23;
  2051. result.m[7] = initialM24;
  2052. result.m[8] = initialM31;
  2053. result.m[9] = initialM32;
  2054. result.m[10] = initialM33;
  2055. result.m[11] = initialM34;
  2056. result.m[12] = initialM41;
  2057. result.m[13] = initialM42;
  2058. result.m[14] = initialM43;
  2059. result.m[15] = initialM44;
  2060. };
  2061. Matrix.prototype.getRow = function (index) {
  2062. if (index < 0 || index > 3) {
  2063. return null;
  2064. }
  2065. var i = index * 4;
  2066. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2067. };
  2068. Matrix.prototype.setRow = function (index, row) {
  2069. if (index < 0 || index > 3) {
  2070. return this;
  2071. }
  2072. var i = index * 4;
  2073. this.m[i + 0] = row.x;
  2074. this.m[i + 1] = row.y;
  2075. this.m[i + 2] = row.z;
  2076. this.m[i + 3] = row.w;
  2077. return this;
  2078. };
  2079. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2080. var result = new Matrix();
  2081. result.m[0] = initialM11;
  2082. result.m[1] = initialM12;
  2083. result.m[2] = initialM13;
  2084. result.m[3] = initialM14;
  2085. result.m[4] = initialM21;
  2086. result.m[5] = initialM22;
  2087. result.m[6] = initialM23;
  2088. result.m[7] = initialM24;
  2089. result.m[8] = initialM31;
  2090. result.m[9] = initialM32;
  2091. result.m[10] = initialM33;
  2092. result.m[11] = initialM34;
  2093. result.m[12] = initialM41;
  2094. result.m[13] = initialM42;
  2095. result.m[14] = initialM43;
  2096. result.m[15] = initialM44;
  2097. return result;
  2098. };
  2099. Matrix.Compose = function (scale, rotation, translation) {
  2100. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2101. var rotationMatrix = Matrix.Identity();
  2102. rotation.toRotationMatrix(rotationMatrix);
  2103. result = result.multiply(rotationMatrix);
  2104. result.setTranslation(translation);
  2105. return result;
  2106. };
  2107. Matrix.Identity = function () {
  2108. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2109. };
  2110. Matrix.IdentityToRef = function (result) {
  2111. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2112. };
  2113. Matrix.Zero = function () {
  2114. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2115. };
  2116. Matrix.RotationX = function (angle) {
  2117. var result = new Matrix();
  2118. Matrix.RotationXToRef(angle, result);
  2119. return result;
  2120. };
  2121. Matrix.Invert = function (source) {
  2122. var result = new Matrix();
  2123. source.invertToRef(result);
  2124. return result;
  2125. };
  2126. Matrix.RotationXToRef = function (angle, result) {
  2127. var s = Math.sin(angle);
  2128. var c = Math.cos(angle);
  2129. result.m[0] = 1.0;
  2130. result.m[15] = 1.0;
  2131. result.m[5] = c;
  2132. result.m[10] = c;
  2133. result.m[9] = -s;
  2134. result.m[6] = s;
  2135. result.m[1] = 0;
  2136. result.m[2] = 0;
  2137. result.m[3] = 0;
  2138. result.m[4] = 0;
  2139. result.m[7] = 0;
  2140. result.m[8] = 0;
  2141. result.m[11] = 0;
  2142. result.m[12] = 0;
  2143. result.m[13] = 0;
  2144. result.m[14] = 0;
  2145. };
  2146. Matrix.RotationY = function (angle) {
  2147. var result = new Matrix();
  2148. Matrix.RotationYToRef(angle, result);
  2149. return result;
  2150. };
  2151. Matrix.RotationYToRef = function (angle, result) {
  2152. var s = Math.sin(angle);
  2153. var c = Math.cos(angle);
  2154. result.m[5] = 1.0;
  2155. result.m[15] = 1.0;
  2156. result.m[0] = c;
  2157. result.m[2] = -s;
  2158. result.m[8] = s;
  2159. result.m[10] = c;
  2160. result.m[1] = 0;
  2161. result.m[3] = 0;
  2162. result.m[4] = 0;
  2163. result.m[6] = 0;
  2164. result.m[7] = 0;
  2165. result.m[9] = 0;
  2166. result.m[11] = 0;
  2167. result.m[12] = 0;
  2168. result.m[13] = 0;
  2169. result.m[14] = 0;
  2170. };
  2171. Matrix.RotationZ = function (angle) {
  2172. var result = new Matrix();
  2173. Matrix.RotationZToRef(angle, result);
  2174. return result;
  2175. };
  2176. Matrix.RotationZToRef = function (angle, result) {
  2177. var s = Math.sin(angle);
  2178. var c = Math.cos(angle);
  2179. result.m[10] = 1.0;
  2180. result.m[15] = 1.0;
  2181. result.m[0] = c;
  2182. result.m[1] = s;
  2183. result.m[4] = -s;
  2184. result.m[5] = c;
  2185. result.m[2] = 0;
  2186. result.m[3] = 0;
  2187. result.m[6] = 0;
  2188. result.m[7] = 0;
  2189. result.m[8] = 0;
  2190. result.m[9] = 0;
  2191. result.m[11] = 0;
  2192. result.m[12] = 0;
  2193. result.m[13] = 0;
  2194. result.m[14] = 0;
  2195. };
  2196. Matrix.RotationAxis = function (axis, angle) {
  2197. var result = Matrix.Zero();
  2198. Matrix.RotationAxisToRef(axis, angle, result);
  2199. return result;
  2200. };
  2201. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2202. var s = Math.sin(-angle);
  2203. var c = Math.cos(-angle);
  2204. var c1 = 1 - c;
  2205. axis.normalize();
  2206. result.m[0] = (axis.x * axis.x) * c1 + c;
  2207. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2208. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2209. result.m[3] = 0.0;
  2210. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2211. result.m[5] = (axis.y * axis.y) * c1 + c;
  2212. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2213. result.m[7] = 0.0;
  2214. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2215. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2216. result.m[10] = (axis.z * axis.z) * c1 + c;
  2217. result.m[11] = 0.0;
  2218. result.m[15] = 1.0;
  2219. };
  2220. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2221. var result = new Matrix();
  2222. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2223. return result;
  2224. };
  2225. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2226. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2227. this._tempQuaternion.toRotationMatrix(result);
  2228. };
  2229. Matrix.Scaling = function (x, y, z) {
  2230. var result = Matrix.Zero();
  2231. Matrix.ScalingToRef(x, y, z, result);
  2232. return result;
  2233. };
  2234. Matrix.ScalingToRef = function (x, y, z, result) {
  2235. result.m[0] = x;
  2236. result.m[1] = 0;
  2237. result.m[2] = 0;
  2238. result.m[3] = 0;
  2239. result.m[4] = 0;
  2240. result.m[5] = y;
  2241. result.m[6] = 0;
  2242. result.m[7] = 0;
  2243. result.m[8] = 0;
  2244. result.m[9] = 0;
  2245. result.m[10] = z;
  2246. result.m[11] = 0;
  2247. result.m[12] = 0;
  2248. result.m[13] = 0;
  2249. result.m[14] = 0;
  2250. result.m[15] = 1.0;
  2251. };
  2252. Matrix.Translation = function (x, y, z) {
  2253. var result = Matrix.Identity();
  2254. Matrix.TranslationToRef(x, y, z, result);
  2255. return result;
  2256. };
  2257. Matrix.TranslationToRef = function (x, y, z, result) {
  2258. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2259. };
  2260. Matrix.Lerp = function (startValue, endValue, gradient) {
  2261. var result = Matrix.Zero();
  2262. for (var index = 0; index < 16; index++) {
  2263. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2264. }
  2265. return result;
  2266. };
  2267. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2268. var startScale = new Vector3(0, 0, 0);
  2269. var startRotation = new Quaternion();
  2270. var startTranslation = new Vector3(0, 0, 0);
  2271. startValue.decompose(startScale, startRotation, startTranslation);
  2272. var endScale = new Vector3(0, 0, 0);
  2273. var endRotation = new Quaternion();
  2274. var endTranslation = new Vector3(0, 0, 0);
  2275. endValue.decompose(endScale, endRotation, endTranslation);
  2276. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2277. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2278. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2279. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2280. };
  2281. Matrix.LookAtLH = function (eye, target, up) {
  2282. var result = Matrix.Zero();
  2283. Matrix.LookAtLHToRef(eye, target, up, result);
  2284. return result;
  2285. };
  2286. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2287. // Z axis
  2288. target.subtractToRef(eye, this._zAxis);
  2289. this._zAxis.normalize();
  2290. // X axis
  2291. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2292. if (this._xAxis.lengthSquared() === 0) {
  2293. this._xAxis.x = 1.0;
  2294. }
  2295. else {
  2296. this._xAxis.normalize();
  2297. }
  2298. // Y axis
  2299. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2300. this._yAxis.normalize();
  2301. // Eye angles
  2302. var ex = -Vector3.Dot(this._xAxis, eye);
  2303. var ey = -Vector3.Dot(this._yAxis, eye);
  2304. var ez = -Vector3.Dot(this._zAxis, eye);
  2305. 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);
  2306. };
  2307. Matrix.LookAtRH = function (eye, target, up) {
  2308. var result = Matrix.Zero();
  2309. Matrix.LookAtRHToRef(eye, target, up, result);
  2310. return result;
  2311. };
  2312. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  2313. // Z axis
  2314. eye.subtractToRef(target, this._zAxis);
  2315. this._zAxis.normalize();
  2316. // X axis
  2317. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2318. if (this._xAxis.lengthSquared() === 0) {
  2319. this._xAxis.x = 1.0;
  2320. }
  2321. else {
  2322. this._xAxis.normalize();
  2323. }
  2324. // Y axis
  2325. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2326. this._yAxis.normalize();
  2327. // Eye angles
  2328. var ex = -Vector3.Dot(this._xAxis, eye);
  2329. var ey = -Vector3.Dot(this._yAxis, eye);
  2330. var ez = -Vector3.Dot(this._zAxis, eye);
  2331. 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);
  2332. };
  2333. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2334. var matrix = Matrix.Zero();
  2335. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2336. return matrix;
  2337. };
  2338. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2339. var n = znear;
  2340. var f = zfar;
  2341. var a = 2.0 / width;
  2342. var b = 2.0 / height;
  2343. var c = 2.0 / (f - n);
  2344. var d = -(f + n) / (f - n);
  2345. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 0, 0, 0, d, 1, result);
  2346. };
  2347. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2348. var matrix = Matrix.Zero();
  2349. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2350. return matrix;
  2351. };
  2352. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2353. var n = znear;
  2354. var f = zfar;
  2355. var a = 2.0 / (right - left);
  2356. var b = 2.0 / (top - bottom);
  2357. var c = 2.0 / (f - n);
  2358. var d = -(f + n) / (f - n);
  2359. var i0 = (left + right) / (left - right);
  2360. var i1 = (top + bottom) / (bottom - top);
  2361. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 0, i0, i1, d, 1, result);
  2362. };
  2363. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  2364. var matrix = Matrix.Zero();
  2365. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  2366. return matrix;
  2367. };
  2368. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2369. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  2370. result.m[10] *= -1.0;
  2371. };
  2372. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2373. var matrix = Matrix.Zero();
  2374. var n = znear;
  2375. var f = zfar;
  2376. var a = 2.0 * n / width;
  2377. var b = 2.0 * n / height;
  2378. var c = (f + n) / (f - n);
  2379. var d = -2.0 * f * n / (f - n);
  2380. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 1, 0, 0, d, 0, matrix);
  2381. return matrix;
  2382. };
  2383. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2384. var matrix = Matrix.Zero();
  2385. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2386. return matrix;
  2387. };
  2388. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2389. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2390. var n = znear;
  2391. var f = zfar;
  2392. var t = 1.0 / (Math.tan(fov * 0.5));
  2393. var a = isVerticalFovFixed ? (t / aspect) : t;
  2394. var b = isVerticalFovFixed ? t : (t * aspect);
  2395. var c = (f + n) / (f - n);
  2396. var d = -2.0 * f * n / (f - n);
  2397. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 1, 0, 0, d, 0, result);
  2398. };
  2399. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  2400. var matrix = Matrix.Zero();
  2401. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  2402. return matrix;
  2403. };
  2404. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2405. //alternatively this could be expressed as:
  2406. // m = PerspectiveFovLHToRef
  2407. // m[10] *= -1.0;
  2408. // m[11] *= -1.0;
  2409. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2410. var n = znear;
  2411. var f = zfar;
  2412. var t = 1.0 / (Math.tan(fov * 0.5));
  2413. var a = isVerticalFovFixed ? (t / aspect) : t;
  2414. var b = isVerticalFovFixed ? t : (t * aspect);
  2415. var c = -(f + n) / (f - n);
  2416. var d = -2 * f * n / (f - n);
  2417. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, -1, 0, 0, d, 0, result);
  2418. };
  2419. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
  2420. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2421. //left handed
  2422. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  2423. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  2424. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  2425. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  2426. var xScale = 2.0 / (leftTan + rightTan);
  2427. var yScale = 2.0 / (upTan + downTan);
  2428. result.m[0] = xScale;
  2429. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  2430. result.m[5] = yScale;
  2431. result.m[6] = result.m[7] = 0.0;
  2432. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  2433. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  2434. result.m[10] = -(znear + zfar) / (zfar - znear);
  2435. // result.m[10] = -zfar / (znear - zfar);
  2436. result.m[11] = 1.0;
  2437. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2438. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  2439. // result.m[14] = (znear * zfar) / (znear - zfar);
  2440. };
  2441. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2442. var cw = viewport.width;
  2443. var ch = viewport.height;
  2444. var cx = viewport.x;
  2445. var cy = viewport.y;
  2446. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2447. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2448. };
  2449. Matrix.GetAsMatrix2x2 = function (matrix) {
  2450. return new Float32Array([
  2451. matrix.m[0], matrix.m[1],
  2452. matrix.m[4], matrix.m[5]
  2453. ]);
  2454. };
  2455. Matrix.GetAsMatrix3x3 = function (matrix) {
  2456. return new Float32Array([
  2457. matrix.m[0], matrix.m[1], matrix.m[2],
  2458. matrix.m[4], matrix.m[5], matrix.m[6],
  2459. matrix.m[8], matrix.m[9], matrix.m[10]
  2460. ]);
  2461. };
  2462. Matrix.Transpose = function (matrix) {
  2463. var result = new Matrix();
  2464. result.m[0] = matrix.m[0];
  2465. result.m[1] = matrix.m[4];
  2466. result.m[2] = matrix.m[8];
  2467. result.m[3] = matrix.m[12];
  2468. result.m[4] = matrix.m[1];
  2469. result.m[5] = matrix.m[5];
  2470. result.m[6] = matrix.m[9];
  2471. result.m[7] = matrix.m[13];
  2472. result.m[8] = matrix.m[2];
  2473. result.m[9] = matrix.m[6];
  2474. result.m[10] = matrix.m[10];
  2475. result.m[11] = matrix.m[14];
  2476. result.m[12] = matrix.m[3];
  2477. result.m[13] = matrix.m[7];
  2478. result.m[14] = matrix.m[11];
  2479. result.m[15] = matrix.m[15];
  2480. return result;
  2481. };
  2482. Matrix.Reflection = function (plane) {
  2483. var matrix = new Matrix();
  2484. Matrix.ReflectionToRef(plane, matrix);
  2485. return matrix;
  2486. };
  2487. Matrix.ReflectionToRef = function (plane, result) {
  2488. plane.normalize();
  2489. var x = plane.normal.x;
  2490. var y = plane.normal.y;
  2491. var z = plane.normal.z;
  2492. var temp = -2 * x;
  2493. var temp2 = -2 * y;
  2494. var temp3 = -2 * z;
  2495. result.m[0] = (temp * x) + 1;
  2496. result.m[1] = temp2 * x;
  2497. result.m[2] = temp3 * x;
  2498. result.m[3] = 0.0;
  2499. result.m[4] = temp * y;
  2500. result.m[5] = (temp2 * y) + 1;
  2501. result.m[6] = temp3 * y;
  2502. result.m[7] = 0.0;
  2503. result.m[8] = temp * z;
  2504. result.m[9] = temp2 * z;
  2505. result.m[10] = (temp3 * z) + 1;
  2506. result.m[11] = 0.0;
  2507. result.m[12] = temp * plane.d;
  2508. result.m[13] = temp2 * plane.d;
  2509. result.m[14] = temp3 * plane.d;
  2510. result.m[15] = 1.0;
  2511. };
  2512. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, mat) {
  2513. mat.m[0] = xaxis.x;
  2514. mat.m[1] = xaxis.y;
  2515. mat.m[2] = xaxis.z;
  2516. mat.m[3] = 0;
  2517. mat.m[4] = yaxis.x;
  2518. mat.m[5] = yaxis.y;
  2519. mat.m[6] = yaxis.z;
  2520. mat.m[7] = 0;
  2521. mat.m[8] = zaxis.x;
  2522. mat.m[9] = zaxis.y;
  2523. mat.m[10] = zaxis.z;
  2524. mat.m[11] = 0;
  2525. mat.m[12] = 0;
  2526. mat.m[13] = 0;
  2527. mat.m[14] = 0;
  2528. mat.m[15] = 1;
  2529. };
  2530. Matrix.FromQuaternionToRef = function (quat, result) {
  2531. var xx = quat.x * quat.x;
  2532. var yy = quat.y * quat.y;
  2533. var zz = quat.z * quat.z;
  2534. var xy = quat.x * quat.y;
  2535. var zw = quat.z * quat.w;
  2536. var zx = quat.z * quat.x;
  2537. var yw = quat.y * quat.w;
  2538. var yz = quat.y * quat.z;
  2539. var xw = quat.x * quat.w;
  2540. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2541. result.m[1] = 2.0 * (xy + zw);
  2542. result.m[2] = 2.0 * (zx - yw);
  2543. result.m[3] = 0;
  2544. result.m[4] = 2.0 * (xy - zw);
  2545. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2546. result.m[6] = 2.0 * (yz + xw);
  2547. result.m[7] = 0;
  2548. result.m[8] = 2.0 * (zx + yw);
  2549. result.m[9] = 2.0 * (yz - xw);
  2550. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2551. result.m[11] = 0;
  2552. result.m[12] = 0;
  2553. result.m[13] = 0;
  2554. result.m[14] = 0;
  2555. result.m[15] = 1.0;
  2556. };
  2557. return Matrix;
  2558. }());
  2559. Matrix._tempQuaternion = new Quaternion();
  2560. Matrix._xAxis = Vector3.Zero();
  2561. Matrix._yAxis = Vector3.Zero();
  2562. Matrix._zAxis = Vector3.Zero();
  2563. BABYLON.Matrix = Matrix;
  2564. var Plane = (function () {
  2565. function Plane(a, b, c, d) {
  2566. this.normal = new Vector3(a, b, c);
  2567. this.d = d;
  2568. }
  2569. Plane.prototype.asArray = function () {
  2570. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2571. };
  2572. // Methods
  2573. Plane.prototype.clone = function () {
  2574. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2575. };
  2576. Plane.prototype.getClassName = function () {
  2577. return "Plane";
  2578. };
  2579. Plane.prototype.getHashCode = function () {
  2580. var hash = this.normal.getHashCode();
  2581. hash = (hash * 397) ^ (this.d || 0);
  2582. return hash;
  2583. };
  2584. Plane.prototype.normalize = function () {
  2585. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2586. var magnitude = 0;
  2587. if (norm !== 0) {
  2588. magnitude = 1.0 / norm;
  2589. }
  2590. this.normal.x *= magnitude;
  2591. this.normal.y *= magnitude;
  2592. this.normal.z *= magnitude;
  2593. this.d *= magnitude;
  2594. return this;
  2595. };
  2596. Plane.prototype.transform = function (transformation) {
  2597. var transposedMatrix = Matrix.Transpose(transformation);
  2598. var x = this.normal.x;
  2599. var y = this.normal.y;
  2600. var z = this.normal.z;
  2601. var d = this.d;
  2602. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2603. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2604. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2605. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2606. return new Plane(normalX, normalY, normalZ, finalD);
  2607. };
  2608. Plane.prototype.dotCoordinate = function (point) {
  2609. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2610. };
  2611. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2612. var x1 = point2.x - point1.x;
  2613. var y1 = point2.y - point1.y;
  2614. var z1 = point2.z - point1.z;
  2615. var x2 = point3.x - point1.x;
  2616. var y2 = point3.y - point1.y;
  2617. var z2 = point3.z - point1.z;
  2618. var yz = (y1 * z2) - (z1 * y2);
  2619. var xz = (z1 * x2) - (x1 * z2);
  2620. var xy = (x1 * y2) - (y1 * x2);
  2621. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2622. var invPyth;
  2623. if (pyth !== 0) {
  2624. invPyth = 1.0 / pyth;
  2625. }
  2626. else {
  2627. invPyth = 0;
  2628. }
  2629. this.normal.x = yz * invPyth;
  2630. this.normal.y = xz * invPyth;
  2631. this.normal.z = xy * invPyth;
  2632. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2633. return this;
  2634. };
  2635. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2636. var dot = Vector3.Dot(this.normal, direction);
  2637. return (dot <= epsilon);
  2638. };
  2639. Plane.prototype.signedDistanceTo = function (point) {
  2640. return Vector3.Dot(point, this.normal) + this.d;
  2641. };
  2642. // Statics
  2643. Plane.FromArray = function (array) {
  2644. return new Plane(array[0], array[1], array[2], array[3]);
  2645. };
  2646. Plane.FromPoints = function (point1, point2, point3) {
  2647. var result = new Plane(0, 0, 0, 0);
  2648. result.copyFromPoints(point1, point2, point3);
  2649. return result;
  2650. };
  2651. Plane.FromPositionAndNormal = function (origin, normal) {
  2652. var result = new Plane(0, 0, 0, 0);
  2653. normal.normalize();
  2654. result.normal = normal;
  2655. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2656. return result;
  2657. };
  2658. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2659. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2660. return Vector3.Dot(point, normal) + d;
  2661. };
  2662. return Plane;
  2663. }());
  2664. BABYLON.Plane = Plane;
  2665. var Viewport = (function () {
  2666. function Viewport(x, y, width, height) {
  2667. this.x = x;
  2668. this.y = y;
  2669. this.width = width;
  2670. this.height = height;
  2671. }
  2672. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2673. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2674. };
  2675. return Viewport;
  2676. }());
  2677. BABYLON.Viewport = Viewport;
  2678. var Frustum = (function () {
  2679. function Frustum() {
  2680. }
  2681. Frustum.GetPlanes = function (transform) {
  2682. var frustumPlanes = [];
  2683. for (var index = 0; index < 6; index++) {
  2684. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2685. }
  2686. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2687. return frustumPlanes;
  2688. };
  2689. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2690. // Near
  2691. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2692. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2693. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2694. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2695. frustumPlanes[0].normalize();
  2696. // Far
  2697. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2698. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2699. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2700. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2701. frustumPlanes[1].normalize();
  2702. // Left
  2703. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2704. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2705. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2706. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2707. frustumPlanes[2].normalize();
  2708. // Right
  2709. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2710. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2711. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2712. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2713. frustumPlanes[3].normalize();
  2714. // Top
  2715. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2716. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2717. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2718. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2719. frustumPlanes[4].normalize();
  2720. // Bottom
  2721. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2722. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2723. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2724. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2725. frustumPlanes[5].normalize();
  2726. };
  2727. return Frustum;
  2728. }());
  2729. BABYLON.Frustum = Frustum;
  2730. var Space;
  2731. (function (Space) {
  2732. Space[Space["LOCAL"] = 0] = "LOCAL";
  2733. Space[Space["WORLD"] = 1] = "WORLD";
  2734. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  2735. var Axis = (function () {
  2736. function Axis() {
  2737. }
  2738. return Axis;
  2739. }());
  2740. Axis.X = new Vector3(1, 0, 0);
  2741. Axis.Y = new Vector3(0, 1, 0);
  2742. Axis.Z = new Vector3(0, 0, 1);
  2743. BABYLON.Axis = Axis;
  2744. ;
  2745. var BezierCurve = (function () {
  2746. function BezierCurve() {
  2747. }
  2748. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2749. // Extract X (which is equal to time here)
  2750. var f0 = 1 - 3 * x2 + 3 * x1;
  2751. var f1 = 3 * x2 - 6 * x1;
  2752. var f2 = 3 * x1;
  2753. var refinedT = t;
  2754. for (var i = 0; i < 5; i++) {
  2755. var refinedT2 = refinedT * refinedT;
  2756. var refinedT3 = refinedT2 * refinedT;
  2757. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2758. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2759. refinedT -= (x - t) * slope;
  2760. refinedT = Math.min(1, Math.max(0, refinedT));
  2761. }
  2762. // Resolve cubic bezier for the given x
  2763. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2764. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2765. Math.pow(refinedT, 3);
  2766. };
  2767. return BezierCurve;
  2768. }());
  2769. BABYLON.BezierCurve = BezierCurve;
  2770. var Orientation;
  2771. (function (Orientation) {
  2772. Orientation[Orientation["CW"] = 0] = "CW";
  2773. Orientation[Orientation["CCW"] = 1] = "CCW";
  2774. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  2775. var Angle = (function () {
  2776. function Angle(radians) {
  2777. var _this = this;
  2778. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2779. this.radians = function () { return _this._radians; };
  2780. this._radians = radians;
  2781. if (this._radians < 0)
  2782. this._radians += (2 * Math.PI);
  2783. }
  2784. Angle.BetweenTwoPoints = function (a, b) {
  2785. var delta = b.subtract(a);
  2786. var theta = Math.atan2(delta.y, delta.x);
  2787. return new Angle(theta);
  2788. };
  2789. Angle.FromRadians = function (radians) {
  2790. return new Angle(radians);
  2791. };
  2792. Angle.FromDegrees = function (degrees) {
  2793. return new Angle(degrees * Math.PI / 180);
  2794. };
  2795. return Angle;
  2796. }());
  2797. BABYLON.Angle = Angle;
  2798. var Arc2 = (function () {
  2799. function Arc2(startPoint, midPoint, endPoint) {
  2800. this.startPoint = startPoint;
  2801. this.midPoint = midPoint;
  2802. this.endPoint = endPoint;
  2803. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2804. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2805. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2806. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2807. 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);
  2808. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2809. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2810. var a1 = this.startAngle.degrees();
  2811. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2812. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2813. // angles correction
  2814. if (a2 - a1 > +180.0)
  2815. a2 -= 360.0;
  2816. if (a2 - a1 < -180.0)
  2817. a2 += 360.0;
  2818. if (a3 - a2 > +180.0)
  2819. a3 -= 360.0;
  2820. if (a3 - a2 < -180.0)
  2821. a3 += 360.0;
  2822. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2823. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2824. }
  2825. return Arc2;
  2826. }());
  2827. BABYLON.Arc2 = Arc2;
  2828. var Path2 = (function () {
  2829. function Path2(x, y) {
  2830. this._points = new Array();
  2831. this._length = 0;
  2832. this.closed = false;
  2833. this._points.push(new Vector2(x, y));
  2834. }
  2835. Path2.prototype.addLineTo = function (x, y) {
  2836. if (closed) {
  2837. //Tools.Error("cannot add lines to closed paths");
  2838. return this;
  2839. }
  2840. var newPoint = new Vector2(x, y);
  2841. var previousPoint = this._points[this._points.length - 1];
  2842. this._points.push(newPoint);
  2843. this._length += newPoint.subtract(previousPoint).length();
  2844. return this;
  2845. };
  2846. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2847. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2848. if (closed) {
  2849. //Tools.Error("cannot add arcs to closed paths");
  2850. return this;
  2851. }
  2852. var startPoint = this._points[this._points.length - 1];
  2853. var midPoint = new Vector2(midX, midY);
  2854. var endPoint = new Vector2(endX, endY);
  2855. var arc = new Arc2(startPoint, midPoint, endPoint);
  2856. var increment = arc.angle.radians() / numberOfSegments;
  2857. if (arc.orientation === Orientation.CW)
  2858. increment *= -1;
  2859. var currentAngle = arc.startAngle.radians() + increment;
  2860. for (var i = 0; i < numberOfSegments; i++) {
  2861. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2862. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2863. this.addLineTo(x, y);
  2864. currentAngle += increment;
  2865. }
  2866. return this;
  2867. };
  2868. Path2.prototype.close = function () {
  2869. this.closed = true;
  2870. return this;
  2871. };
  2872. Path2.prototype.length = function () {
  2873. var result = this._length;
  2874. if (!this.closed) {
  2875. var lastPoint = this._points[this._points.length - 1];
  2876. var firstPoint = this._points[0];
  2877. result += (firstPoint.subtract(lastPoint).length());
  2878. }
  2879. return result;
  2880. };
  2881. Path2.prototype.getPoints = function () {
  2882. return this._points;
  2883. };
  2884. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2885. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2886. //Tools.Error("normalized length position should be between 0 and 1.");
  2887. return Vector2.Zero();
  2888. }
  2889. var lengthPosition = normalizedLengthPosition * this.length();
  2890. var previousOffset = 0;
  2891. for (var i = 0; i < this._points.length; i++) {
  2892. var j = (i + 1) % this._points.length;
  2893. var a = this._points[i];
  2894. var b = this._points[j];
  2895. var bToA = b.subtract(a);
  2896. var nextOffset = (bToA.length() + previousOffset);
  2897. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2898. var dir = bToA.normalize();
  2899. var localOffset = lengthPosition - previousOffset;
  2900. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2901. }
  2902. previousOffset = nextOffset;
  2903. }
  2904. //Tools.Error("internal error");
  2905. return Vector2.Zero();
  2906. };
  2907. Path2.StartingAt = function (x, y) {
  2908. return new Path2(x, y);
  2909. };
  2910. return Path2;
  2911. }());
  2912. BABYLON.Path2 = Path2;
  2913. var Path3D = (function () {
  2914. /**
  2915. * new Path3D(path, normal, raw)
  2916. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2917. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2918. * path : an array of Vector3, the curve axis of the Path3D
  2919. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2920. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2921. */
  2922. function Path3D(path, firstNormal, raw) {
  2923. this.path = path;
  2924. this._curve = new Array();
  2925. this._distances = new Array();
  2926. this._tangents = new Array();
  2927. this._normals = new Array();
  2928. this._binormals = new Array();
  2929. for (var p = 0; p < path.length; p++) {
  2930. this._curve[p] = path[p].clone(); // hard copy
  2931. }
  2932. this._raw = raw || false;
  2933. this._compute(firstNormal);
  2934. }
  2935. /**
  2936. * Returns the Path3D array of successive Vector3 designing its curve.
  2937. */
  2938. Path3D.prototype.getCurve = function () {
  2939. return this._curve;
  2940. };
  2941. /**
  2942. * Returns an array populated with tangent vectors on each Path3D curve point.
  2943. */
  2944. Path3D.prototype.getTangents = function () {
  2945. return this._tangents;
  2946. };
  2947. /**
  2948. * Returns an array populated with normal vectors on each Path3D curve point.
  2949. */
  2950. Path3D.prototype.getNormals = function () {
  2951. return this._normals;
  2952. };
  2953. /**
  2954. * Returns an array populated with binormal vectors on each Path3D curve point.
  2955. */
  2956. Path3D.prototype.getBinormals = function () {
  2957. return this._binormals;
  2958. };
  2959. /**
  2960. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2961. */
  2962. Path3D.prototype.getDistances = function () {
  2963. return this._distances;
  2964. };
  2965. /**
  2966. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2967. * Returns the same object updated.
  2968. */
  2969. Path3D.prototype.update = function (path, firstNormal) {
  2970. for (var p = 0; p < path.length; p++) {
  2971. this._curve[p].x = path[p].x;
  2972. this._curve[p].y = path[p].y;
  2973. this._curve[p].z = path[p].z;
  2974. }
  2975. this._compute(firstNormal);
  2976. return this;
  2977. };
  2978. // private function compute() : computes tangents, normals and binormals
  2979. Path3D.prototype._compute = function (firstNormal) {
  2980. var l = this._curve.length;
  2981. // first and last tangents
  2982. this._tangents[0] = this._getFirstNonNullVector(0);
  2983. if (!this._raw) {
  2984. this._tangents[0].normalize();
  2985. }
  2986. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2987. if (!this._raw) {
  2988. this._tangents[l - 1].normalize();
  2989. }
  2990. // normals and binormals at first point : arbitrary vector with _normalVector()
  2991. var tg0 = this._tangents[0];
  2992. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2993. this._normals[0] = pp0;
  2994. if (!this._raw) {
  2995. this._normals[0].normalize();
  2996. }
  2997. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2998. if (!this._raw) {
  2999. this._binormals[0].normalize();
  3000. }
  3001. this._distances[0] = 0.0;
  3002. // normals and binormals : next points
  3003. var prev; // previous vector (segment)
  3004. var cur; // current vector (segment)
  3005. var curTang; // current tangent
  3006. // previous normal
  3007. var prevBinor; // previous binormal
  3008. for (var i = 1; i < l; i++) {
  3009. // tangents
  3010. prev = this._getLastNonNullVector(i);
  3011. if (i < l - 1) {
  3012. cur = this._getFirstNonNullVector(i);
  3013. this._tangents[i] = prev.add(cur);
  3014. this._tangents[i].normalize();
  3015. }
  3016. this._distances[i] = this._distances[i - 1] + prev.length();
  3017. // normals and binormals
  3018. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  3019. curTang = this._tangents[i];
  3020. prevBinor = this._binormals[i - 1];
  3021. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  3022. if (!this._raw) {
  3023. this._normals[i].normalize();
  3024. }
  3025. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  3026. if (!this._raw) {
  3027. this._binormals[i].normalize();
  3028. }
  3029. }
  3030. };
  3031. // private function getFirstNonNullVector(index)
  3032. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  3033. Path3D.prototype._getFirstNonNullVector = function (index) {
  3034. var i = 1;
  3035. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  3036. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  3037. i++;
  3038. nNVector = this._curve[index + i].subtract(this._curve[index]);
  3039. }
  3040. return nNVector;
  3041. };
  3042. // private function getLastNonNullVector(index)
  3043. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  3044. Path3D.prototype._getLastNonNullVector = function (index) {
  3045. var i = 1;
  3046. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  3047. while (nLVector.length() === 0 && index > i + 1) {
  3048. i++;
  3049. nLVector = this._curve[index].subtract(this._curve[index - i]);
  3050. }
  3051. return nLVector;
  3052. };
  3053. // private function normalVector(v0, vt, va) :
  3054. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  3055. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  3056. Path3D.prototype._normalVector = function (v0, vt, va) {
  3057. var normal0;
  3058. var tgl = vt.length();
  3059. if (tgl === 0.0) {
  3060. tgl = 1.0;
  3061. }
  3062. if (va === undefined || va === null) {
  3063. var point;
  3064. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  3065. point = new Vector3(0.0, -1.0, 0.0);
  3066. }
  3067. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  3068. point = new Vector3(1.0, 0.0, 0.0);
  3069. }
  3070. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  3071. point = new Vector3(0.0, 0.0, 1.0);
  3072. }
  3073. normal0 = Vector3.Cross(vt, point);
  3074. }
  3075. else {
  3076. normal0 = Vector3.Cross(vt, va);
  3077. Vector3.CrossToRef(normal0, vt, normal0);
  3078. }
  3079. normal0.normalize();
  3080. return normal0;
  3081. };
  3082. return Path3D;
  3083. }());
  3084. BABYLON.Path3D = Path3D;
  3085. var Curve3 = (function () {
  3086. /**
  3087. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  3088. * A Curve3 is designed from a series of successive Vector3.
  3089. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  3090. */
  3091. function Curve3(points) {
  3092. this._length = 0.0;
  3093. this._points = points;
  3094. this._length = this._computeLength(points);
  3095. }
  3096. /**
  3097. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  3098. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  3099. * @param v1 (Vector3) the control point
  3100. * @param v2 (Vector3) the end point of the Quadratic Bezier
  3101. * @param nbPoints (integer) the wanted number of points in the curve
  3102. */
  3103. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  3104. nbPoints = nbPoints > 2 ? nbPoints : 3;
  3105. var bez = new Array();
  3106. var equation = function (t, val0, val1, val2) {
  3107. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  3108. return res;
  3109. };
  3110. for (var i = 0; i <= nbPoints; i++) {
  3111. 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)));
  3112. }
  3113. return new Curve3(bez);
  3114. };
  3115. /**
  3116. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  3117. * @param v0 (Vector3) the origin point of the Cubic Bezier
  3118. * @param v1 (Vector3) the first control point
  3119. * @param v2 (Vector3) the second control point
  3120. * @param v3 (Vector3) the end point of the Cubic Bezier
  3121. * @param nbPoints (integer) the wanted number of points in the curve
  3122. */
  3123. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3124. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3125. var bez = new Array();
  3126. var equation = function (t, val0, val1, val2, val3) {
  3127. 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;
  3128. return res;
  3129. };
  3130. for (var i = 0; i <= nbPoints; i++) {
  3131. 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)));
  3132. }
  3133. return new Curve3(bez);
  3134. };
  3135. /**
  3136. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  3137. * @param p1 (Vector3) the origin point of the Hermite Spline
  3138. * @param t1 (Vector3) the tangent vector at the origin point
  3139. * @param p2 (Vector3) the end point of the Hermite Spline
  3140. * @param t2 (Vector3) the tangent vector at the end point
  3141. * @param nbPoints (integer) the wanted number of points in the curve
  3142. */
  3143. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3144. var hermite = new Array();
  3145. var step = 1.0 / nbPoints;
  3146. for (var i = 0; i <= nbPoints; i++) {
  3147. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3148. }
  3149. return new Curve3(hermite);
  3150. };
  3151. /**
  3152. * Returns the Curve3 stored array of successive Vector3
  3153. */
  3154. Curve3.prototype.getPoints = function () {
  3155. return this._points;
  3156. };
  3157. /**
  3158. * Returns the computed length (float) of the curve.
  3159. */
  3160. Curve3.prototype.length = function () {
  3161. return this._length;
  3162. };
  3163. /**
  3164. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3165. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3166. * curveA and curveB keep unchanged.
  3167. */
  3168. Curve3.prototype.continue = function (curve) {
  3169. var lastPoint = this._points[this._points.length - 1];
  3170. var continuedPoints = this._points.slice();
  3171. var curvePoints = curve.getPoints();
  3172. for (var i = 1; i < curvePoints.length; i++) {
  3173. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3174. }
  3175. var continuedCurve = new Curve3(continuedPoints);
  3176. return continuedCurve;
  3177. };
  3178. Curve3.prototype._computeLength = function (path) {
  3179. var l = 0;
  3180. for (var i = 1; i < path.length; i++) {
  3181. l += (path[i].subtract(path[i - 1])).length();
  3182. }
  3183. return l;
  3184. };
  3185. return Curve3;
  3186. }());
  3187. BABYLON.Curve3 = Curve3;
  3188. // SphericalHarmonics
  3189. var SphericalHarmonics = (function () {
  3190. function SphericalHarmonics() {
  3191. this.L00 = Vector3.Zero();
  3192. this.L1_1 = Vector3.Zero();
  3193. this.L10 = Vector3.Zero();
  3194. this.L11 = Vector3.Zero();
  3195. this.L2_2 = Vector3.Zero();
  3196. this.L2_1 = Vector3.Zero();
  3197. this.L20 = Vector3.Zero();
  3198. this.L21 = Vector3.Zero();
  3199. this.L22 = Vector3.Zero();
  3200. }
  3201. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3202. var colorVector = new Vector3(color.r, color.g, color.b);
  3203. var c = colorVector.scale(deltaSolidAngle);
  3204. this.L00 = this.L00.add(c.scale(0.282095));
  3205. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3206. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3207. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3208. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3209. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3210. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3211. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3212. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3213. };
  3214. SphericalHarmonics.prototype.scale = function (scale) {
  3215. this.L00 = this.L00.scale(scale);
  3216. this.L1_1 = this.L1_1.scale(scale);
  3217. this.L10 = this.L10.scale(scale);
  3218. this.L11 = this.L11.scale(scale);
  3219. this.L2_2 = this.L2_2.scale(scale);
  3220. this.L2_1 = this.L2_1.scale(scale);
  3221. this.L20 = this.L20.scale(scale);
  3222. this.L21 = this.L21.scale(scale);
  3223. this.L22 = this.L22.scale(scale);
  3224. };
  3225. return SphericalHarmonics;
  3226. }());
  3227. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3228. // SphericalPolynomial
  3229. var SphericalPolynomial = (function () {
  3230. function SphericalPolynomial() {
  3231. this.x = Vector3.Zero();
  3232. this.y = Vector3.Zero();
  3233. this.z = Vector3.Zero();
  3234. this.xx = Vector3.Zero();
  3235. this.yy = Vector3.Zero();
  3236. this.zz = Vector3.Zero();
  3237. this.xy = Vector3.Zero();
  3238. this.yz = Vector3.Zero();
  3239. this.zx = Vector3.Zero();
  3240. }
  3241. SphericalPolynomial.prototype.addAmbient = function (color) {
  3242. var colorVector = new Vector3(color.r, color.g, color.b);
  3243. this.xx = this.xx.add(colorVector);
  3244. this.yy = this.yy.add(colorVector);
  3245. this.zz = this.zz.add(colorVector);
  3246. };
  3247. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3248. var result = new SphericalPolynomial();
  3249. result.x = harmonics.L11.scale(1.02333);
  3250. result.y = harmonics.L1_1.scale(1.02333);
  3251. result.z = harmonics.L10.scale(1.02333);
  3252. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3253. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3254. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3255. result.yz = harmonics.L2_1.scale(0.858086);
  3256. result.zx = harmonics.L21.scale(0.858086);
  3257. result.xy = harmonics.L2_2.scale(0.858086);
  3258. return result;
  3259. };
  3260. return SphericalPolynomial;
  3261. }());
  3262. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3263. // Vertex formats
  3264. var PositionNormalVertex = (function () {
  3265. function PositionNormalVertex(position, normal) {
  3266. if (position === void 0) { position = Vector3.Zero(); }
  3267. if (normal === void 0) { normal = Vector3.Up(); }
  3268. this.position = position;
  3269. this.normal = normal;
  3270. }
  3271. PositionNormalVertex.prototype.clone = function () {
  3272. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3273. };
  3274. return PositionNormalVertex;
  3275. }());
  3276. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3277. var PositionNormalTextureVertex = (function () {
  3278. function PositionNormalTextureVertex(position, normal, uv) {
  3279. if (position === void 0) { position = Vector3.Zero(); }
  3280. if (normal === void 0) { normal = Vector3.Up(); }
  3281. if (uv === void 0) { uv = Vector2.Zero(); }
  3282. this.position = position;
  3283. this.normal = normal;
  3284. this.uv = uv;
  3285. }
  3286. PositionNormalTextureVertex.prototype.clone = function () {
  3287. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3288. };
  3289. return PositionNormalTextureVertex;
  3290. }());
  3291. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3292. // Temporary pre-allocated objects for engine internal use
  3293. // usage in any internal function :
  3294. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3295. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3296. var Tmp = (function () {
  3297. function Tmp() {
  3298. }
  3299. return Tmp;
  3300. }());
  3301. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3302. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3303. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3304. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3305. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3306. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3307. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3308. Matrix.Zero(), Matrix.Zero(),
  3309. Matrix.Zero(), Matrix.Zero(),
  3310. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3311. BABYLON.Tmp = Tmp;
  3312. })(BABYLON || (BABYLON = {}));
  3313. //# sourceMappingURL=babylon.math.js.map
  3314. //# sourceMappingURL=babylon.mixins.js.map
  3315. var BABYLON;
  3316. (function (BABYLON) {
  3317. function generateSerializableMember(type, sourceName) {
  3318. return function (target, propertyKey) {
  3319. if (!target.__serializableMembers) {
  3320. target.__serializableMembers = {};
  3321. }
  3322. if (!target.__serializableMembers[propertyKey]) {
  3323. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3324. }
  3325. };
  3326. }
  3327. function serialize(sourceName) {
  3328. return generateSerializableMember(0, sourceName); // value member
  3329. }
  3330. BABYLON.serialize = serialize;
  3331. function serializeAsTexture(sourceName) {
  3332. return generateSerializableMember(1, sourceName); // texture member
  3333. }
  3334. BABYLON.serializeAsTexture = serializeAsTexture;
  3335. function serializeAsColor3(sourceName) {
  3336. return generateSerializableMember(2, sourceName); // color3 member
  3337. }
  3338. BABYLON.serializeAsColor3 = serializeAsColor3;
  3339. function serializeAsFresnelParameters(sourceName) {
  3340. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3341. }
  3342. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3343. function serializeAsVector2(sourceName) {
  3344. return generateSerializableMember(4, sourceName); // vector2 member
  3345. }
  3346. BABYLON.serializeAsVector2 = serializeAsVector2;
  3347. function serializeAsVector3(sourceName) {
  3348. return generateSerializableMember(5, sourceName); // vector3 member
  3349. }
  3350. BABYLON.serializeAsVector3 = serializeAsVector3;
  3351. function serializeAsMeshReference(sourceName) {
  3352. return generateSerializableMember(6, sourceName); // mesh reference member
  3353. }
  3354. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3355. function serializeAsColorCurves(sourceName) {
  3356. return generateSerializableMember(7, sourceName); // color curves
  3357. }
  3358. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3359. var SerializationHelper = (function () {
  3360. function SerializationHelper() {
  3361. }
  3362. SerializationHelper.Serialize = function (entity, serializationObject) {
  3363. if (!serializationObject) {
  3364. serializationObject = {};
  3365. }
  3366. // Tags
  3367. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3368. // Properties
  3369. for (var property in entity.__serializableMembers) {
  3370. var propertyDescriptor = entity.__serializableMembers[property];
  3371. var targetPropertyName = propertyDescriptor.sourceName || property;
  3372. var propertyType = propertyDescriptor.type;
  3373. var sourceProperty = entity[property];
  3374. if (sourceProperty !== undefined && sourceProperty !== null) {
  3375. switch (propertyType) {
  3376. case 0:
  3377. serializationObject[targetPropertyName] = sourceProperty;
  3378. break;
  3379. case 1:
  3380. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3381. break;
  3382. case 2:
  3383. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3384. break;
  3385. case 3:
  3386. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3387. break;
  3388. case 4:
  3389. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3390. break;
  3391. case 5:
  3392. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3393. break;
  3394. case 6:
  3395. serializationObject[targetPropertyName] = sourceProperty.id;
  3396. break;
  3397. case 7:
  3398. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3399. break;
  3400. }
  3401. }
  3402. }
  3403. return serializationObject;
  3404. };
  3405. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3406. var destination = creationFunction();
  3407. // Tags
  3408. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3409. // Properties
  3410. for (var property in destination.__serializableMembers) {
  3411. var propertyDescriptor = destination.__serializableMembers[property];
  3412. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3413. var propertyType = propertyDescriptor.type;
  3414. if (sourceProperty !== undefined && sourceProperty !== null) {
  3415. switch (propertyType) {
  3416. case 0:
  3417. destination[property] = sourceProperty;
  3418. break;
  3419. case 1:
  3420. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3421. break;
  3422. case 2:
  3423. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3424. break;
  3425. case 3:
  3426. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3427. break;
  3428. case 4:
  3429. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3430. break;
  3431. case 5:
  3432. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3433. break;
  3434. case 6:
  3435. destination[property] = scene.getLastMeshByID(sourceProperty);
  3436. break;
  3437. case 7:
  3438. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3439. break;
  3440. }
  3441. }
  3442. }
  3443. return destination;
  3444. };
  3445. SerializationHelper.Clone = function (creationFunction, source) {
  3446. var destination = creationFunction();
  3447. // Tags
  3448. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3449. // Properties
  3450. for (var property in destination.__serializableMembers) {
  3451. var propertyDescriptor = destination.__serializableMembers[property];
  3452. var sourceProperty = source[property];
  3453. var propertyType = propertyDescriptor.type;
  3454. if (sourceProperty !== undefined && sourceProperty !== null) {
  3455. switch (propertyType) {
  3456. case 0: // Value
  3457. case 6:
  3458. destination[property] = sourceProperty;
  3459. break;
  3460. case 1: // Texture
  3461. case 2: // Color3
  3462. case 3: // FresnelParameters
  3463. case 4: // Vector2
  3464. case 5: // Vector3
  3465. case 7:
  3466. destination[property] = sourceProperty.clone();
  3467. break;
  3468. }
  3469. }
  3470. }
  3471. return destination;
  3472. };
  3473. return SerializationHelper;
  3474. }());
  3475. BABYLON.SerializationHelper = SerializationHelper;
  3476. })(BABYLON || (BABYLON = {}));
  3477. //# sourceMappingURL=babylon.decorators.js.map
  3478. var BABYLON;
  3479. (function (BABYLON) {
  3480. /**
  3481. * A class serves as a medium between the observable and its observers
  3482. */
  3483. var EventState = (function () {
  3484. /**
  3485. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3486. */
  3487. function EventState(mask, skipNextObservers) {
  3488. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3489. this.initalize(mask, skipNextObservers);
  3490. }
  3491. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3492. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3493. this.mask = mask;
  3494. this.skipNextObservers = skipNextObservers;
  3495. return this;
  3496. };
  3497. return EventState;
  3498. }());
  3499. BABYLON.EventState = EventState;
  3500. /**
  3501. * Represent an Observer registered to a given Observable object.
  3502. */
  3503. var Observer = (function () {
  3504. function Observer(callback, mask) {
  3505. this.callback = callback;
  3506. this.mask = mask;
  3507. }
  3508. return Observer;
  3509. }());
  3510. BABYLON.Observer = Observer;
  3511. /**
  3512. * The Observable class is a simple implementation of the Observable pattern.
  3513. * 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.
  3514. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3515. * 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).
  3516. * 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.
  3517. */
  3518. var Observable = (function () {
  3519. function Observable() {
  3520. this._observers = new Array();
  3521. this._eventState = new EventState(0);
  3522. }
  3523. /**
  3524. * Create a new Observer with the specified callback
  3525. * @param callback the callback that will be executed for that Observer
  3526. * @param mask the mask used to filter observers
  3527. * @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.
  3528. */
  3529. Observable.prototype.add = function (callback, mask, insertFirst) {
  3530. if (mask === void 0) { mask = -1; }
  3531. if (insertFirst === void 0) { insertFirst = false; }
  3532. if (!callback) {
  3533. return null;
  3534. }
  3535. var observer = new Observer(callback, mask);
  3536. if (insertFirst) {
  3537. this._observers.unshift(observer);
  3538. }
  3539. else {
  3540. this._observers.push(observer);
  3541. }
  3542. return observer;
  3543. };
  3544. /**
  3545. * Remove an Observer from the Observable object
  3546. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3547. */
  3548. Observable.prototype.remove = function (observer) {
  3549. var index = this._observers.indexOf(observer);
  3550. if (index !== -1) {
  3551. this._observers.splice(index, 1);
  3552. return true;
  3553. }
  3554. return false;
  3555. };
  3556. /**
  3557. * Remove a callback from the Observable object
  3558. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3559. */
  3560. Observable.prototype.removeCallback = function (callback) {
  3561. for (var index = 0; index < this._observers.length; index++) {
  3562. if (this._observers[index].callback === callback) {
  3563. this._observers.splice(index, 1);
  3564. return true;
  3565. }
  3566. }
  3567. return false;
  3568. };
  3569. /**
  3570. * Notify all Observers by calling their respective callback with the given data
  3571. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  3572. * @param eventData
  3573. * @param mask
  3574. */
  3575. Observable.prototype.notifyObservers = function (eventData, mask) {
  3576. if (mask === void 0) { mask = -1; }
  3577. var state = this._eventState;
  3578. state.mask = mask;
  3579. state.skipNextObservers = false;
  3580. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3581. var obs = _a[_i];
  3582. if (obs.mask & mask) {
  3583. obs.callback(eventData, state);
  3584. }
  3585. if (state.skipNextObservers) {
  3586. return false;
  3587. }
  3588. }
  3589. return true;
  3590. };
  3591. /**
  3592. * return true is the Observable has at least one Observer registered
  3593. */
  3594. Observable.prototype.hasObservers = function () {
  3595. return this._observers.length > 0;
  3596. };
  3597. /**
  3598. * Clear the list of observers
  3599. */
  3600. Observable.prototype.clear = function () {
  3601. this._observers = new Array();
  3602. };
  3603. /**
  3604. * Clone the current observable
  3605. */
  3606. Observable.prototype.clone = function () {
  3607. var result = new Observable();
  3608. result._observers = this._observers.slice(0);
  3609. return result;
  3610. };
  3611. return Observable;
  3612. }());
  3613. BABYLON.Observable = Observable;
  3614. })(BABYLON || (BABYLON = {}));
  3615. //# sourceMappingURL=babylon.observable.js.map
  3616. var BABYLON;
  3617. (function (BABYLON) {
  3618. var Database = (function () {
  3619. function Database(urlToScene, callbackManifestChecked) {
  3620. // Handling various flavors of prefixed version of IndexedDB
  3621. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3622. this.callbackManifestChecked = callbackManifestChecked;
  3623. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3624. this.db = null;
  3625. this.enableSceneOffline = false;
  3626. this.enableTexturesOffline = false;
  3627. this.manifestVersionFound = 0;
  3628. this.mustUpdateRessources = false;
  3629. this.hasReachedQuota = false;
  3630. if (!Database.IDBStorageEnabled) {
  3631. this.callbackManifestChecked(true);
  3632. }
  3633. else {
  3634. this.checkManifestFile();
  3635. }
  3636. }
  3637. Database.prototype.checkManifestFile = function () {
  3638. var _this = this;
  3639. function noManifestFile() {
  3640. that.enableSceneOffline = false;
  3641. that.enableTexturesOffline = false;
  3642. that.callbackManifestChecked(false);
  3643. }
  3644. var that = this;
  3645. var timeStampUsed = false;
  3646. var manifestURL = this.currentSceneUrl + ".manifest";
  3647. var xhr = new XMLHttpRequest();
  3648. if (navigator.onLine) {
  3649. // Adding a timestamp to by-pass browsers' cache
  3650. timeStampUsed = true;
  3651. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3652. }
  3653. xhr.open("GET", manifestURL, true);
  3654. xhr.addEventListener("load", function () {
  3655. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3656. try {
  3657. var manifestFile = JSON.parse(xhr.response);
  3658. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3659. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3660. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3661. _this.manifestVersionFound = manifestFile.version;
  3662. }
  3663. if (_this.callbackManifestChecked) {
  3664. _this.callbackManifestChecked(true);
  3665. }
  3666. }
  3667. catch (ex) {
  3668. noManifestFile();
  3669. }
  3670. }
  3671. else {
  3672. noManifestFile();
  3673. }
  3674. }, false);
  3675. xhr.addEventListener("error", function (event) {
  3676. if (timeStampUsed) {
  3677. timeStampUsed = false;
  3678. // Let's retry without the timeStamp
  3679. // It could fail when coupled with HTML5 Offline API
  3680. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3681. xhr.open("GET", retryManifestURL, true);
  3682. xhr.send();
  3683. }
  3684. else {
  3685. noManifestFile();
  3686. }
  3687. }, false);
  3688. try {
  3689. xhr.send();
  3690. }
  3691. catch (ex) {
  3692. BABYLON.Tools.Error("Error on XHR send request.");
  3693. that.callbackManifestChecked(false);
  3694. }
  3695. };
  3696. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3697. var _this = this;
  3698. function handleError() {
  3699. that.isSupported = false;
  3700. if (errorCallback)
  3701. errorCallback();
  3702. }
  3703. var that = this;
  3704. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3705. // Your browser doesn't support IndexedDB
  3706. this.isSupported = false;
  3707. if (errorCallback)
  3708. errorCallback();
  3709. }
  3710. else {
  3711. // If the DB hasn't been opened or created yet
  3712. if (!this.db) {
  3713. this.hasReachedQuota = false;
  3714. this.isSupported = true;
  3715. var request = this.idbFactory.open("babylonjs", 1);
  3716. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3717. request.onerror = function (event) {
  3718. handleError();
  3719. };
  3720. // executes when a version change transaction cannot complete due to other active transactions
  3721. request.onblocked = function (event) {
  3722. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3723. handleError();
  3724. };
  3725. // DB has been opened successfully
  3726. request.onsuccess = function (event) {
  3727. _this.db = request.result;
  3728. successCallback();
  3729. };
  3730. // Initialization of the DB. Creating Scenes & Textures stores
  3731. request.onupgradeneeded = function (event) {
  3732. _this.db = (event.target).result;
  3733. try {
  3734. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3735. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3736. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3737. }
  3738. catch (ex) {
  3739. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3740. handleError();
  3741. }
  3742. };
  3743. }
  3744. else {
  3745. if (successCallback)
  3746. successCallback();
  3747. }
  3748. }
  3749. };
  3750. Database.prototype.loadImageFromDB = function (url, image) {
  3751. var _this = this;
  3752. var completeURL = Database.ReturnFullUrlLocation(url);
  3753. var saveAndLoadImage = function () {
  3754. if (!_this.hasReachedQuota && _this.db !== null) {
  3755. // the texture is not yet in the DB, let's try to save it
  3756. _this._saveImageIntoDBAsync(completeURL, image);
  3757. }
  3758. else {
  3759. image.src = url;
  3760. }
  3761. };
  3762. if (!this.mustUpdateRessources) {
  3763. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3764. }
  3765. else {
  3766. saveAndLoadImage();
  3767. }
  3768. };
  3769. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3770. if (this.isSupported && this.db !== null) {
  3771. var texture;
  3772. var transaction = this.db.transaction(["textures"]);
  3773. transaction.onabort = function (event) {
  3774. image.src = url;
  3775. };
  3776. transaction.oncomplete = function (event) {
  3777. var blobTextureURL;
  3778. if (texture) {
  3779. var URL = window.URL || window.webkitURL;
  3780. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3781. image.onerror = function () {
  3782. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3783. image.src = url;
  3784. };
  3785. image.src = blobTextureURL;
  3786. }
  3787. else {
  3788. notInDBCallback();
  3789. }
  3790. };
  3791. var getRequest = transaction.objectStore("textures").get(url);
  3792. getRequest.onsuccess = function (event) {
  3793. texture = (event.target).result;
  3794. };
  3795. getRequest.onerror = function (event) {
  3796. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3797. image.src = url;
  3798. };
  3799. }
  3800. else {
  3801. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3802. image.src = url;
  3803. }
  3804. };
  3805. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3806. var _this = this;
  3807. if (this.isSupported) {
  3808. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3809. var generateBlobUrl = function () {
  3810. var blobTextureURL;
  3811. if (blob) {
  3812. var URL = window.URL || window.webkitURL;
  3813. try {
  3814. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3815. }
  3816. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3817. catch (ex) {
  3818. blobTextureURL = URL.createObjectURL(blob);
  3819. }
  3820. }
  3821. image.src = blobTextureURL;
  3822. };
  3823. if (Database.IsUASupportingBlobStorage) {
  3824. var xhr = new XMLHttpRequest(), blob;
  3825. xhr.open("GET", url, true);
  3826. xhr.responseType = "blob";
  3827. xhr.addEventListener("load", function () {
  3828. if (xhr.status === 200) {
  3829. // Blob as response (XHR2)
  3830. blob = xhr.response;
  3831. var transaction = _this.db.transaction(["textures"], "readwrite");
  3832. // the transaction could abort because of a QuotaExceededError error
  3833. transaction.onabort = function (event) {
  3834. try {
  3835. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3836. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3837. _this.hasReachedQuota = true;
  3838. }
  3839. }
  3840. catch (ex) { }
  3841. generateBlobUrl();
  3842. };
  3843. transaction.oncomplete = function (event) {
  3844. generateBlobUrl();
  3845. };
  3846. var newTexture = { textureUrl: url, data: blob };
  3847. try {
  3848. // Put the blob into the dabase
  3849. var addRequest = transaction.objectStore("textures").put(newTexture);
  3850. addRequest.onsuccess = function (event) {
  3851. };
  3852. addRequest.onerror = function (event) {
  3853. generateBlobUrl();
  3854. };
  3855. }
  3856. catch (ex) {
  3857. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3858. if (ex.code === 25) {
  3859. Database.IsUASupportingBlobStorage = false;
  3860. }
  3861. image.src = url;
  3862. }
  3863. }
  3864. else {
  3865. image.src = url;
  3866. }
  3867. }, false);
  3868. xhr.addEventListener("error", function (event) {
  3869. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3870. image.src = url;
  3871. }, false);
  3872. xhr.send();
  3873. }
  3874. else {
  3875. image.src = url;
  3876. }
  3877. }
  3878. else {
  3879. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3880. image.src = url;
  3881. }
  3882. };
  3883. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3884. var _this = this;
  3885. var updateVersion = function (event) {
  3886. // the version is not yet in the DB or we need to update it
  3887. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3888. };
  3889. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3890. };
  3891. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3892. var _this = this;
  3893. if (this.isSupported) {
  3894. var version;
  3895. try {
  3896. var transaction = this.db.transaction(["versions"]);
  3897. transaction.oncomplete = function (event) {
  3898. if (version) {
  3899. // If the version in the JSON file is > than the version in DB
  3900. if (_this.manifestVersionFound > version.data) {
  3901. _this.mustUpdateRessources = true;
  3902. updateInDBCallback();
  3903. }
  3904. else {
  3905. callback(version.data);
  3906. }
  3907. }
  3908. else {
  3909. _this.mustUpdateRessources = true;
  3910. updateInDBCallback();
  3911. }
  3912. };
  3913. transaction.onabort = function (event) {
  3914. callback(-1);
  3915. };
  3916. var getRequest = transaction.objectStore("versions").get(url);
  3917. getRequest.onsuccess = function (event) {
  3918. version = (event.target).result;
  3919. };
  3920. getRequest.onerror = function (event) {
  3921. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3922. callback(-1);
  3923. };
  3924. }
  3925. catch (ex) {
  3926. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3927. callback(-1);
  3928. }
  3929. }
  3930. else {
  3931. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3932. callback(-1);
  3933. }
  3934. };
  3935. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3936. var _this = this;
  3937. if (this.isSupported && !this.hasReachedQuota) {
  3938. try {
  3939. // Open a transaction to the database
  3940. var transaction = this.db.transaction(["versions"], "readwrite");
  3941. // the transaction could abort because of a QuotaExceededError error
  3942. transaction.onabort = function (event) {
  3943. try {
  3944. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3945. _this.hasReachedQuota = true;
  3946. }
  3947. }
  3948. catch (ex) { }
  3949. callback(-1);
  3950. };
  3951. transaction.oncomplete = function (event) {
  3952. callback(_this.manifestVersionFound);
  3953. };
  3954. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3955. // Put the scene into the database
  3956. var addRequest = transaction.objectStore("versions").put(newVersion);
  3957. addRequest.onsuccess = function (event) {
  3958. };
  3959. addRequest.onerror = function (event) {
  3960. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3961. };
  3962. }
  3963. catch (ex) {
  3964. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3965. callback(-1);
  3966. }
  3967. }
  3968. else {
  3969. callback(-1);
  3970. }
  3971. };
  3972. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3973. var _this = this;
  3974. var completeUrl = Database.ReturnFullUrlLocation(url);
  3975. var saveAndLoadFile = function (event) {
  3976. // the scene is not yet in the DB, let's try to save it
  3977. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3978. };
  3979. this._checkVersionFromDB(completeUrl, function (version) {
  3980. if (version !== -1) {
  3981. if (!_this.mustUpdateRessources) {
  3982. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3983. }
  3984. else {
  3985. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3986. }
  3987. }
  3988. else {
  3989. errorCallback();
  3990. }
  3991. });
  3992. };
  3993. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3994. if (this.isSupported) {
  3995. var targetStore;
  3996. if (url.indexOf(".babylon") !== -1) {
  3997. targetStore = "scenes";
  3998. }
  3999. else {
  4000. targetStore = "textures";
  4001. }
  4002. var file;
  4003. var transaction = this.db.transaction([targetStore]);
  4004. transaction.oncomplete = function (event) {
  4005. if (file) {
  4006. callback(file.data);
  4007. }
  4008. else {
  4009. notInDBCallback();
  4010. }
  4011. };
  4012. transaction.onabort = function (event) {
  4013. notInDBCallback();
  4014. };
  4015. var getRequest = transaction.objectStore(targetStore).get(url);
  4016. getRequest.onsuccess = function (event) {
  4017. file = (event.target).result;
  4018. };
  4019. getRequest.onerror = function (event) {
  4020. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  4021. notInDBCallback();
  4022. };
  4023. }
  4024. else {
  4025. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4026. callback();
  4027. }
  4028. };
  4029. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  4030. var _this = this;
  4031. if (this.isSupported) {
  4032. var targetStore;
  4033. if (url.indexOf(".babylon") !== -1) {
  4034. targetStore = "scenes";
  4035. }
  4036. else {
  4037. targetStore = "textures";
  4038. }
  4039. // Create XHR
  4040. var xhr = new XMLHttpRequest(), fileData;
  4041. xhr.open("GET", url, true);
  4042. if (useArrayBuffer) {
  4043. xhr.responseType = "arraybuffer";
  4044. }
  4045. xhr.onprogress = progressCallback;
  4046. xhr.addEventListener("load", function () {
  4047. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  4048. // Blob as response (XHR2)
  4049. //fileData = xhr.responseText;
  4050. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  4051. if (!_this.hasReachedQuota) {
  4052. // Open a transaction to the database
  4053. var transaction = _this.db.transaction([targetStore], "readwrite");
  4054. // the transaction could abort because of a QuotaExceededError error
  4055. transaction.onabort = function (event) {
  4056. try {
  4057. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  4058. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  4059. _this.hasReachedQuota = true;
  4060. }
  4061. }
  4062. catch (ex) { }
  4063. callback(fileData);
  4064. };
  4065. transaction.oncomplete = function (event) {
  4066. callback(fileData);
  4067. };
  4068. var newFile;
  4069. if (targetStore === "scenes") {
  4070. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  4071. }
  4072. else {
  4073. newFile = { textureUrl: url, data: fileData };
  4074. }
  4075. try {
  4076. // Put the scene into the database
  4077. var addRequest = transaction.objectStore(targetStore).put(newFile);
  4078. addRequest.onsuccess = function (event) {
  4079. };
  4080. addRequest.onerror = function (event) {
  4081. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  4082. };
  4083. }
  4084. catch (ex) {
  4085. callback(fileData);
  4086. }
  4087. }
  4088. else {
  4089. callback(fileData);
  4090. }
  4091. }
  4092. else {
  4093. callback();
  4094. }
  4095. }, false);
  4096. xhr.addEventListener("error", function (event) {
  4097. BABYLON.Tools.Error("error on XHR request.");
  4098. callback();
  4099. }, false);
  4100. xhr.send();
  4101. }
  4102. else {
  4103. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4104. callback();
  4105. }
  4106. };
  4107. return Database;
  4108. }());
  4109. Database.IsUASupportingBlobStorage = true;
  4110. Database.IDBStorageEnabled = true;
  4111. Database.parseURL = function (url) {
  4112. var a = document.createElement('a');
  4113. a.href = url;
  4114. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  4115. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  4116. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  4117. return absLocation;
  4118. };
  4119. Database.ReturnFullUrlLocation = function (url) {
  4120. if (url.indexOf("http:/") === -1) {
  4121. return (Database.parseURL(window.location.href) + url);
  4122. }
  4123. else {
  4124. return url;
  4125. }
  4126. };
  4127. BABYLON.Database = Database;
  4128. })(BABYLON || (BABYLON = {}));
  4129. //# sourceMappingURL=babylon.database.js.map
  4130. var BABYLON;
  4131. (function (BABYLON) {
  4132. var Internals;
  4133. (function (Internals) {
  4134. /*
  4135. * Based on jsTGALoader - Javascript loader for TGA file
  4136. * By Vincent Thibault
  4137. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  4138. */
  4139. var TGATools = (function () {
  4140. function TGATools() {
  4141. }
  4142. TGATools.GetTGAHeader = function (data) {
  4143. var offset = 0;
  4144. var header = {
  4145. id_length: data[offset++],
  4146. colormap_type: data[offset++],
  4147. image_type: data[offset++],
  4148. colormap_index: data[offset++] | data[offset++] << 8,
  4149. colormap_length: data[offset++] | data[offset++] << 8,
  4150. colormap_size: data[offset++],
  4151. origin: [
  4152. data[offset++] | data[offset++] << 8,
  4153. data[offset++] | data[offset++] << 8
  4154. ],
  4155. width: data[offset++] | data[offset++] << 8,
  4156. height: data[offset++] | data[offset++] << 8,
  4157. pixel_size: data[offset++],
  4158. flags: data[offset++]
  4159. };
  4160. return header;
  4161. };
  4162. TGATools.UploadContent = function (gl, data) {
  4163. // Not enough data to contain header ?
  4164. if (data.length < 19) {
  4165. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4166. return;
  4167. }
  4168. // Read Header
  4169. var offset = 18;
  4170. var header = TGATools.GetTGAHeader(data);
  4171. // Assume it's a valid Targa file.
  4172. if (header.id_length + offset > data.length) {
  4173. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4174. return;
  4175. }
  4176. // Skip not needed data
  4177. offset += header.id_length;
  4178. var use_rle = false;
  4179. var use_pal = false;
  4180. var use_rgb = false;
  4181. var use_grey = false;
  4182. // Get some informations.
  4183. switch (header.image_type) {
  4184. case TGATools._TYPE_RLE_INDEXED:
  4185. use_rle = true;
  4186. case TGATools._TYPE_INDEXED:
  4187. use_pal = true;
  4188. break;
  4189. case TGATools._TYPE_RLE_RGB:
  4190. use_rle = true;
  4191. case TGATools._TYPE_RGB:
  4192. use_rgb = true;
  4193. break;
  4194. case TGATools._TYPE_RLE_GREY:
  4195. use_rle = true;
  4196. case TGATools._TYPE_GREY:
  4197. use_grey = true;
  4198. break;
  4199. }
  4200. var pixel_data;
  4201. var numAlphaBits = header.flags & 0xf;
  4202. var pixel_size = header.pixel_size >> 3;
  4203. var pixel_total = header.width * header.height * pixel_size;
  4204. // Read palettes
  4205. var palettes;
  4206. if (use_pal) {
  4207. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4208. }
  4209. // Read LRE
  4210. if (use_rle) {
  4211. pixel_data = new Uint8Array(pixel_total);
  4212. var c, count, i;
  4213. var localOffset = 0;
  4214. var pixels = new Uint8Array(pixel_size);
  4215. while (offset < pixel_total && localOffset < pixel_total) {
  4216. c = data[offset++];
  4217. count = (c & 0x7f) + 1;
  4218. // RLE pixels
  4219. if (c & 0x80) {
  4220. // Bind pixel tmp array
  4221. for (i = 0; i < pixel_size; ++i) {
  4222. pixels[i] = data[offset++];
  4223. }
  4224. // Copy pixel array
  4225. for (i = 0; i < count; ++i) {
  4226. pixel_data.set(pixels, localOffset + i * pixel_size);
  4227. }
  4228. localOffset += pixel_size * count;
  4229. }
  4230. else {
  4231. count *= pixel_size;
  4232. for (i = 0; i < count; ++i) {
  4233. pixel_data[localOffset + i] = data[offset++];
  4234. }
  4235. localOffset += count;
  4236. }
  4237. }
  4238. }
  4239. else {
  4240. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4241. }
  4242. // Load to texture
  4243. var x_start, y_start, x_step, y_step, y_end, x_end;
  4244. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4245. default:
  4246. case TGATools._ORIGIN_UL:
  4247. x_start = 0;
  4248. x_step = 1;
  4249. x_end = header.width;
  4250. y_start = 0;
  4251. y_step = 1;
  4252. y_end = header.height;
  4253. break;
  4254. case TGATools._ORIGIN_BL:
  4255. x_start = 0;
  4256. x_step = 1;
  4257. x_end = header.width;
  4258. y_start = header.height - 1;
  4259. y_step = -1;
  4260. y_end = -1;
  4261. break;
  4262. case TGATools._ORIGIN_UR:
  4263. x_start = header.width - 1;
  4264. x_step = -1;
  4265. x_end = -1;
  4266. y_start = 0;
  4267. y_step = 1;
  4268. y_end = header.height;
  4269. break;
  4270. case TGATools._ORIGIN_BR:
  4271. x_start = header.width - 1;
  4272. x_step = -1;
  4273. x_end = -1;
  4274. y_start = header.height - 1;
  4275. y_step = -1;
  4276. y_end = -1;
  4277. break;
  4278. }
  4279. // Load the specify method
  4280. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4281. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4282. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4283. };
  4284. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4285. var image = pixel_data, colormap = palettes;
  4286. var width = header.width, height = header.height;
  4287. var color, i = 0, x, y;
  4288. var imageData = new Uint8Array(width * height * 4);
  4289. for (y = y_start; y !== y_end; y += y_step) {
  4290. for (x = x_start; x !== x_end; x += x_step, i++) {
  4291. color = image[i];
  4292. imageData[(x + width * y) * 4 + 3] = 255;
  4293. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4294. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4295. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4296. }
  4297. }
  4298. return imageData;
  4299. };
  4300. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4301. var image = pixel_data;
  4302. var width = header.width, height = header.height;
  4303. var color, i = 0, x, y;
  4304. var imageData = new Uint8Array(width * height * 4);
  4305. for (y = y_start; y !== y_end; y += y_step) {
  4306. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4307. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4308. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4309. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4310. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4311. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4312. }
  4313. }
  4314. return imageData;
  4315. };
  4316. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4317. var image = pixel_data;
  4318. var width = header.width, height = header.height;
  4319. var i = 0, x, y;
  4320. var imageData = new Uint8Array(width * height * 4);
  4321. for (y = y_start; y !== y_end; y += y_step) {
  4322. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4323. imageData[(x + width * y) * 4 + 3] = 255;
  4324. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4325. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4326. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4327. }
  4328. }
  4329. return imageData;
  4330. };
  4331. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4332. var image = pixel_data;
  4333. var width = header.width, height = header.height;
  4334. var i = 0, x, y;
  4335. var imageData = new Uint8Array(width * height * 4);
  4336. for (y = y_start; y !== y_end; y += y_step) {
  4337. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4338. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4339. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4340. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4341. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4342. }
  4343. }
  4344. return imageData;
  4345. };
  4346. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4347. var image = pixel_data;
  4348. var width = header.width, height = header.height;
  4349. var color, i = 0, x, y;
  4350. var imageData = new Uint8Array(width * height * 4);
  4351. for (y = y_start; y !== y_end; y += y_step) {
  4352. for (x = x_start; x !== x_end; x += x_step, i++) {
  4353. color = image[i];
  4354. imageData[(x + width * y) * 4 + 0] = color;
  4355. imageData[(x + width * y) * 4 + 1] = color;
  4356. imageData[(x + width * y) * 4 + 2] = color;
  4357. imageData[(x + width * y) * 4 + 3] = 255;
  4358. }
  4359. }
  4360. return imageData;
  4361. };
  4362. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4363. var image = pixel_data;
  4364. var width = header.width, height = header.height;
  4365. var i = 0, x, y;
  4366. var imageData = new Uint8Array(width * height * 4);
  4367. for (y = y_start; y !== y_end; y += y_step) {
  4368. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4369. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4370. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4371. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4372. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4373. }
  4374. }
  4375. return imageData;
  4376. };
  4377. return TGATools;
  4378. }());
  4379. TGATools._TYPE_NO_DATA = 0;
  4380. TGATools._TYPE_INDEXED = 1;
  4381. TGATools._TYPE_RGB = 2;
  4382. TGATools._TYPE_GREY = 3;
  4383. TGATools._TYPE_RLE_INDEXED = 9;
  4384. TGATools._TYPE_RLE_RGB = 10;
  4385. TGATools._TYPE_RLE_GREY = 11;
  4386. TGATools._ORIGIN_MASK = 0x30;
  4387. TGATools._ORIGIN_SHIFT = 0x04;
  4388. TGATools._ORIGIN_BL = 0x00;
  4389. TGATools._ORIGIN_BR = 0x01;
  4390. TGATools._ORIGIN_UL = 0x02;
  4391. TGATools._ORIGIN_UR = 0x03;
  4392. Internals.TGATools = TGATools;
  4393. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4394. })(BABYLON || (BABYLON = {}));
  4395. //# sourceMappingURL=babylon.tools.tga.js.map
  4396. var BABYLON;
  4397. (function (BABYLON) {
  4398. var SmartArray = (function () {
  4399. function SmartArray(capacity) {
  4400. this.length = 0;
  4401. this._duplicateId = 0;
  4402. this.data = new Array(capacity);
  4403. this._id = SmartArray._GlobalId++;
  4404. }
  4405. SmartArray.prototype.push = function (value) {
  4406. this.data[this.length++] = value;
  4407. if (this.length > this.data.length) {
  4408. this.data.length *= 2;
  4409. }
  4410. if (!value.__smartArrayFlags) {
  4411. value.__smartArrayFlags = {};
  4412. }
  4413. value.__smartArrayFlags[this._id] = this._duplicateId;
  4414. };
  4415. SmartArray.prototype.pushNoDuplicate = function (value) {
  4416. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4417. return false;
  4418. }
  4419. this.push(value);
  4420. return true;
  4421. };
  4422. SmartArray.prototype.sort = function (compareFn) {
  4423. this.data.sort(compareFn);
  4424. };
  4425. SmartArray.prototype.reset = function () {
  4426. this.length = 0;
  4427. this._duplicateId++;
  4428. };
  4429. SmartArray.prototype.concat = function (array) {
  4430. if (array.length === 0) {
  4431. return;
  4432. }
  4433. if (this.length + array.length > this.data.length) {
  4434. this.data.length = (this.length + array.length) * 2;
  4435. }
  4436. for (var index = 0; index < array.length; index++) {
  4437. this.data[this.length++] = (array.data || array)[index];
  4438. }
  4439. };
  4440. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4441. if (array.length === 0) {
  4442. return;
  4443. }
  4444. if (this.length + array.length > this.data.length) {
  4445. this.data.length = (this.length + array.length) * 2;
  4446. }
  4447. for (var index = 0; index < array.length; index++) {
  4448. var item = (array.data || array)[index];
  4449. this.pushNoDuplicate(item);
  4450. }
  4451. };
  4452. SmartArray.prototype.indexOf = function (value) {
  4453. var position = this.data.indexOf(value);
  4454. if (position >= this.length) {
  4455. return -1;
  4456. }
  4457. return position;
  4458. };
  4459. return SmartArray;
  4460. }());
  4461. // Statics
  4462. SmartArray._GlobalId = 0;
  4463. BABYLON.SmartArray = SmartArray;
  4464. })(BABYLON || (BABYLON = {}));
  4465. //# sourceMappingURL=babylon.smartArray.js.map
  4466. var BABYLON;
  4467. (function (BABYLON) {
  4468. /**
  4469. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4470. * The underlying implementation relies on an associative array to ensure the best performances.
  4471. * The value can be anything including 'null' but except 'undefined'
  4472. */
  4473. var StringDictionary = (function () {
  4474. function StringDictionary() {
  4475. this._count = 0;
  4476. this._data = {};
  4477. }
  4478. /**
  4479. * This will clear this dictionary and copy the content from the 'source' one.
  4480. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  4481. * @param source the dictionary to take the content from and copy to this dictionary
  4482. */
  4483. StringDictionary.prototype.copyFrom = function (source) {
  4484. var _this = this;
  4485. this.clear();
  4486. source.forEach(function (t, v) { return _this.add(t, v); });
  4487. };
  4488. /**
  4489. * Get a value based from its key
  4490. * @param key the given key to get the matching value from
  4491. * @return the value if found, otherwise undefined is returned
  4492. */
  4493. StringDictionary.prototype.get = function (key) {
  4494. var val = this._data[key];
  4495. if (val !== undefined) {
  4496. return val;
  4497. }
  4498. return undefined;
  4499. };
  4500. /**
  4501. * Get a value from its key or add it if it doesn't exist.
  4502. * This method will ensure you that a given key/data will be present in the dictionary.
  4503. * @param key the given key to get the matching value from
  4504. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4505. * The factory will only be invoked if there's no data for the given key.
  4506. * @return the value corresponding to the key.
  4507. */
  4508. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4509. var val = this.get(key);
  4510. if (val !== undefined) {
  4511. return val;
  4512. }
  4513. val = factory(key);
  4514. if (val) {
  4515. this.add(key, val);
  4516. }
  4517. return val;
  4518. };
  4519. /**
  4520. * Get a value from its key if present in the dictionary otherwise add it
  4521. * @param key the key to get the value from
  4522. * @param val if there's no such key/value pair in the dictionary add it with this value
  4523. * @return the value corresponding to the key
  4524. */
  4525. StringDictionary.prototype.getOrAdd = function (key, val) {
  4526. var curVal = this.get(key);
  4527. if (curVal !== undefined) {
  4528. return curVal;
  4529. }
  4530. this.add(key, val);
  4531. return val;
  4532. };
  4533. /**
  4534. * Check if there's a given key in the dictionary
  4535. * @param key the key to check for
  4536. * @return true if the key is present, false otherwise
  4537. */
  4538. StringDictionary.prototype.contains = function (key) {
  4539. return this._data[key] !== undefined;
  4540. };
  4541. /**
  4542. * Add a new key and its corresponding value
  4543. * @param key the key to add
  4544. * @param value the value corresponding to the key
  4545. * @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
  4546. */
  4547. StringDictionary.prototype.add = function (key, value) {
  4548. if (this._data[key] !== undefined) {
  4549. return false;
  4550. }
  4551. this._data[key] = value;
  4552. ++this._count;
  4553. return true;
  4554. };
  4555. StringDictionary.prototype.set = function (key, value) {
  4556. if (this._data[key] === undefined) {
  4557. return false;
  4558. }
  4559. this._data[key] = value;
  4560. return true;
  4561. };
  4562. /**
  4563. * Get the element of the given key and remove it from the dictionary
  4564. * @param key
  4565. */
  4566. StringDictionary.prototype.getAndRemove = function (key) {
  4567. var val = this.get(key);
  4568. if (val !== undefined) {
  4569. delete this._data[key];
  4570. --this._count;
  4571. return val;
  4572. }
  4573. return null;
  4574. };
  4575. /**
  4576. * Remove a key/value from the dictionary.
  4577. * @param key the key to remove
  4578. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4579. */
  4580. StringDictionary.prototype.remove = function (key) {
  4581. if (this.contains(key)) {
  4582. delete this._data[key];
  4583. --this._count;
  4584. return true;
  4585. }
  4586. return false;
  4587. };
  4588. /**
  4589. * Clear the whole content of the dictionary
  4590. */
  4591. StringDictionary.prototype.clear = function () {
  4592. this._data = {};
  4593. this._count = 0;
  4594. };
  4595. Object.defineProperty(StringDictionary.prototype, "count", {
  4596. get: function () {
  4597. return this._count;
  4598. },
  4599. enumerable: true,
  4600. configurable: true
  4601. });
  4602. /**
  4603. * Execute a callback on each key/val of the dictionary.
  4604. * Note that you can remove any element in this dictionary in the callback implementation
  4605. * @param callback the callback to execute on a given key/value pair
  4606. */
  4607. StringDictionary.prototype.forEach = function (callback) {
  4608. for (var cur in this._data) {
  4609. var val = this._data[cur];
  4610. callback(cur, val);
  4611. }
  4612. };
  4613. /**
  4614. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4615. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4616. * Note that you can remove any element in this dictionary in the callback implementation
  4617. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4618. */
  4619. StringDictionary.prototype.first = function (callback) {
  4620. for (var cur in this._data) {
  4621. var val = this._data[cur];
  4622. var res = callback(cur, val);
  4623. if (res) {
  4624. return res;
  4625. }
  4626. }
  4627. return null;
  4628. };
  4629. return StringDictionary;
  4630. }());
  4631. BABYLON.StringDictionary = StringDictionary;
  4632. })(BABYLON || (BABYLON = {}));
  4633. //# sourceMappingURL=babylon.stringDictionary.js.map
  4634. var BABYLON;
  4635. (function (BABYLON) {
  4636. // Screenshots
  4637. var screenshotCanvas;
  4638. var cloneValue = function (source, destinationObject) {
  4639. if (!source)
  4640. return null;
  4641. if (source instanceof BABYLON.Mesh) {
  4642. return null;
  4643. }
  4644. if (source instanceof BABYLON.SubMesh) {
  4645. return source.clone(destinationObject);
  4646. }
  4647. else if (source.clone) {
  4648. return source.clone();
  4649. }
  4650. return null;
  4651. };
  4652. var Tools = (function () {
  4653. function Tools() {
  4654. }
  4655. Tools.Instantiate = function (className) {
  4656. var arr = className.split(".");
  4657. var fn = (window || this);
  4658. for (var i = 0, len = arr.length; i < len; i++) {
  4659. fn = fn[arr[i]];
  4660. }
  4661. if (typeof fn !== "function") {
  4662. return null;
  4663. }
  4664. return fn;
  4665. };
  4666. Tools.SetImmediate = function (action) {
  4667. if (window.setImmediate) {
  4668. window.setImmediate(action);
  4669. }
  4670. else {
  4671. setTimeout(action, 1);
  4672. }
  4673. };
  4674. Tools.IsExponentOfTwo = function (value) {
  4675. var count = 1;
  4676. do {
  4677. count *= 2;
  4678. } while (count < value);
  4679. return count === value;
  4680. };
  4681. Tools.GetExponentOfTwo = function (value, max) {
  4682. var count = 1;
  4683. do {
  4684. count *= 2;
  4685. } while (count < value);
  4686. if (count > max)
  4687. count = max;
  4688. return count;
  4689. };
  4690. Tools.GetFilename = function (path) {
  4691. var index = path.lastIndexOf("/");
  4692. if (index < 0)
  4693. return path;
  4694. return path.substring(index + 1);
  4695. };
  4696. Tools.GetDOMTextContent = function (element) {
  4697. var result = "";
  4698. var child = element.firstChild;
  4699. while (child) {
  4700. if (child.nodeType === 3) {
  4701. result += child.textContent;
  4702. }
  4703. child = child.nextSibling;
  4704. }
  4705. return result;
  4706. };
  4707. Tools.ToDegrees = function (angle) {
  4708. return angle * 180 / Math.PI;
  4709. };
  4710. Tools.ToRadians = function (angle) {
  4711. return angle * Math.PI / 180;
  4712. };
  4713. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4714. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4715. var output = "";
  4716. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4717. var i = 0;
  4718. var bytes = new Uint8Array(buffer);
  4719. while (i < bytes.length) {
  4720. chr1 = bytes[i++];
  4721. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4722. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4723. enc1 = chr1 >> 2;
  4724. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4725. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4726. enc4 = chr3 & 63;
  4727. if (isNaN(chr2)) {
  4728. enc3 = enc4 = 64;
  4729. }
  4730. else if (isNaN(chr3)) {
  4731. enc4 = 64;
  4732. }
  4733. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4734. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4735. }
  4736. return "data:image/png;base64," + output;
  4737. };
  4738. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4739. if (bias === void 0) { bias = null; }
  4740. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4741. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4742. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4743. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4744. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4745. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4746. }
  4747. if (bias) {
  4748. minimum.x -= minimum.x * bias.x + bias.y;
  4749. minimum.y -= minimum.y * bias.x + bias.y;
  4750. minimum.z -= minimum.z * bias.x + bias.y;
  4751. maximum.x += maximum.x * bias.x + bias.y;
  4752. maximum.y += maximum.y * bias.x + bias.y;
  4753. maximum.z += maximum.z * bias.x + bias.y;
  4754. }
  4755. return {
  4756. minimum: minimum,
  4757. maximum: maximum
  4758. };
  4759. };
  4760. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4761. if (bias === void 0) { bias = null; }
  4762. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4763. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4764. if (!stride) {
  4765. stride = 3;
  4766. }
  4767. for (var index = start; index < start + count; index++) {
  4768. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4769. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4770. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4771. }
  4772. if (bias) {
  4773. minimum.x -= minimum.x * bias.x + bias.y;
  4774. minimum.y -= minimum.y * bias.x + bias.y;
  4775. minimum.z -= minimum.z * bias.x + bias.y;
  4776. maximum.x += maximum.x * bias.x + bias.y;
  4777. maximum.y += maximum.y * bias.x + bias.y;
  4778. maximum.z += maximum.z * bias.x + bias.y;
  4779. }
  4780. return {
  4781. minimum: minimum,
  4782. maximum: maximum
  4783. };
  4784. };
  4785. Tools.Vector2ArrayFeeder = function (array) {
  4786. return function (index) {
  4787. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4788. var length = isFloatArray ? array.length / 2 : array.length;
  4789. if (index >= length) {
  4790. return null;
  4791. }
  4792. if (isFloatArray) {
  4793. var fa = array;
  4794. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4795. }
  4796. var a = array;
  4797. return a[index];
  4798. };
  4799. };
  4800. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4801. if (bias === void 0) { bias = null; }
  4802. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4803. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4804. var i = 0;
  4805. var cur = feeder(i++);
  4806. while (cur) {
  4807. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4808. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4809. cur = feeder(i++);
  4810. }
  4811. if (bias) {
  4812. minimum.x -= minimum.x * bias.x + bias.y;
  4813. minimum.y -= minimum.y * bias.x + bias.y;
  4814. maximum.x += maximum.x * bias.x + bias.y;
  4815. maximum.y += maximum.y * bias.x + bias.y;
  4816. }
  4817. return {
  4818. minimum: minimum,
  4819. maximum: maximum
  4820. };
  4821. };
  4822. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4823. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4824. return undefined;
  4825. return Array.isArray(obj) ? obj : [obj];
  4826. };
  4827. // Misc.
  4828. Tools.GetPointerPrefix = function () {
  4829. var eventPrefix = "pointer";
  4830. // Check if pointer events are supported
  4831. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4832. eventPrefix = "mouse";
  4833. }
  4834. return eventPrefix;
  4835. };
  4836. /**
  4837. * @param func - the function to be called
  4838. * @param requester - the object that will request the next frame. Falls back to window.
  4839. */
  4840. Tools.QueueNewFrame = function (func, requester) {
  4841. if (requester === void 0) { requester = window; }
  4842. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  4843. /*if(requester.isPresenting) {
  4844. return;
  4845. } else*/ if (requester.requestAnimationFrame)
  4846. requester.requestAnimationFrame(func);
  4847. else if (requester.msRequestAnimationFrame)
  4848. requester.msRequestAnimationFrame(func);
  4849. else if (requester.webkitRequestAnimationFrame)
  4850. requester.webkitRequestAnimationFrame(func);
  4851. else if (requester.mozRequestAnimationFrame)
  4852. requester.mozRequestAnimationFrame(func);
  4853. else if (requester.oRequestAnimationFrame)
  4854. requester.oRequestAnimationFrame(func);
  4855. else {
  4856. window.setTimeout(func, 16);
  4857. }
  4858. };
  4859. Tools.RequestFullscreen = function (element) {
  4860. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4861. if (!requestFunction)
  4862. return;
  4863. requestFunction.call(element);
  4864. };
  4865. Tools.ExitFullscreen = function () {
  4866. if (document.exitFullscreen) {
  4867. document.exitFullscreen();
  4868. }
  4869. else if (document.mozCancelFullScreen) {
  4870. document.mozCancelFullScreen();
  4871. }
  4872. else if (document.webkitCancelFullScreen) {
  4873. document.webkitCancelFullScreen();
  4874. }
  4875. else if (document.msCancelFullScreen) {
  4876. document.msCancelFullScreen();
  4877. }
  4878. };
  4879. Tools.SetCorsBehavior = function (url, img) {
  4880. if (Tools.CorsBehavior) {
  4881. switch (typeof (Tools.CorsBehavior)) {
  4882. case "function":
  4883. var result = Tools.CorsBehavior(url);
  4884. if (result) {
  4885. return result;
  4886. }
  4887. break;
  4888. case "string":
  4889. default:
  4890. img.crossOrigin = Tools.CorsBehavior;
  4891. break;
  4892. }
  4893. }
  4894. };
  4895. // External files
  4896. Tools.CleanUrl = function (url) {
  4897. url = url.replace(/#/mg, "%23");
  4898. return url;
  4899. };
  4900. Tools.LoadImage = function (url, onload, onerror, database) {
  4901. if (url instanceof ArrayBuffer) {
  4902. url = Tools.EncodeArrayBufferTobase64(url);
  4903. }
  4904. url = Tools.CleanUrl(url);
  4905. var img = new Image();
  4906. if (url.substr(0, 5) !== "data:") {
  4907. Tools.SetCorsBehavior(url, img);
  4908. }
  4909. img.onload = function () {
  4910. onload(img);
  4911. };
  4912. img.onerror = function (err) {
  4913. Tools.Error("Error while trying to load texture: " + url);
  4914. if (Tools.UseFallbackTexture) {
  4915. img.src = "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";
  4916. onload(img);
  4917. }
  4918. else {
  4919. onerror();
  4920. }
  4921. };
  4922. var noIndexedDB = function () {
  4923. img.src = url;
  4924. };
  4925. var loadFromIndexedDB = function () {
  4926. database.loadImageFromDB(url, img);
  4927. };
  4928. //ANY database to do!
  4929. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4930. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4931. }
  4932. else {
  4933. if (url.indexOf("file:") === -1) {
  4934. noIndexedDB();
  4935. }
  4936. else {
  4937. try {
  4938. var textureName = url.substring(5).toLowerCase();
  4939. var blobURL;
  4940. try {
  4941. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4942. }
  4943. catch (ex) {
  4944. // Chrome doesn't support oneTimeOnly parameter
  4945. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4946. }
  4947. img.src = blobURL;
  4948. }
  4949. catch (e) {
  4950. img.src = null;
  4951. }
  4952. }
  4953. }
  4954. return img;
  4955. };
  4956. //ANY
  4957. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4958. url = Tools.CleanUrl(url);
  4959. var noIndexedDB = function () {
  4960. var request = new XMLHttpRequest();
  4961. var loadUrl = Tools.BaseUrl + url;
  4962. request.open('GET', loadUrl, true);
  4963. if (useArrayBuffer) {
  4964. request.responseType = "arraybuffer";
  4965. }
  4966. request.onprogress = progressCallBack;
  4967. request.onreadystatechange = function () {
  4968. if (request.readyState === 4) {
  4969. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  4970. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  4971. callback(!useArrayBuffer ? request.responseText : request.response);
  4972. }
  4973. else {
  4974. if (onError) {
  4975. onError();
  4976. }
  4977. else {
  4978. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4979. }
  4980. }
  4981. }
  4982. };
  4983. request.send(null);
  4984. };
  4985. var loadFromIndexedDB = function () {
  4986. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4987. };
  4988. if (url.indexOf("file:") !== -1) {
  4989. var fileName = url.substring(5).toLowerCase();
  4990. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4991. }
  4992. else {
  4993. // Caching all files
  4994. if (database && database.enableSceneOffline) {
  4995. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4996. }
  4997. else {
  4998. noIndexedDB();
  4999. }
  5000. }
  5001. };
  5002. /**
  5003. * Load a script (identified by an url). When the url returns, the
  5004. * content of this file is added into a new script element, attached to the DOM (body element)
  5005. */
  5006. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5007. var head = document.getElementsByTagName('head')[0];
  5008. var script = document.createElement('script');
  5009. script.type = 'text/javascript';
  5010. script.src = scriptUrl;
  5011. var self = this;
  5012. script.onload = function () {
  5013. if (onSuccess) {
  5014. onSuccess();
  5015. }
  5016. };
  5017. script.onerror = function () {
  5018. if (onError) {
  5019. onError();
  5020. }
  5021. };
  5022. head.appendChild(script);
  5023. };
  5024. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5025. var reader = new FileReader();
  5026. reader.onload = function (e) {
  5027. //target doesn't have result from ts 1.3
  5028. callback(e.target['result']);
  5029. };
  5030. reader.onprogress = progressCallback;
  5031. reader.readAsDataURL(fileToLoad);
  5032. };
  5033. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5034. var reader = new FileReader();
  5035. reader.onerror = function (e) {
  5036. Tools.Log("Error while reading file: " + fileToLoad.name);
  5037. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5038. };
  5039. reader.onload = function (e) {
  5040. //target doesn't have result from ts 1.3
  5041. callback(e.target['result']);
  5042. };
  5043. reader.onprogress = progressCallBack;
  5044. if (!useArrayBuffer) {
  5045. // Asynchronous read
  5046. reader.readAsText(fileToLoad);
  5047. }
  5048. else {
  5049. reader.readAsArrayBuffer(fileToLoad);
  5050. }
  5051. };
  5052. //returns a downloadable url to a file content.
  5053. Tools.FileAsURL = function (content) {
  5054. var fileBlob = new Blob([content]);
  5055. var url = window.URL || window.webkitURL;
  5056. var link = url.createObjectURL(fileBlob);
  5057. return link;
  5058. };
  5059. // Misc.
  5060. Tools.Format = function (value, decimals) {
  5061. if (decimals === void 0) { decimals = 2; }
  5062. return value.toFixed(decimals);
  5063. };
  5064. Tools.CheckExtends = function (v, min, max) {
  5065. if (v.x < min.x)
  5066. min.x = v.x;
  5067. if (v.y < min.y)
  5068. min.y = v.y;
  5069. if (v.z < min.z)
  5070. min.z = v.z;
  5071. if (v.x > max.x)
  5072. max.x = v.x;
  5073. if (v.y > max.y)
  5074. max.y = v.y;
  5075. if (v.z > max.z)
  5076. max.z = v.z;
  5077. };
  5078. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5079. for (var prop in source) {
  5080. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5081. continue;
  5082. }
  5083. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5084. continue;
  5085. }
  5086. var sourceValue = source[prop];
  5087. var typeOfSourceValue = typeof sourceValue;
  5088. if (typeOfSourceValue === "function") {
  5089. continue;
  5090. }
  5091. if (typeOfSourceValue === "object") {
  5092. if (sourceValue instanceof Array) {
  5093. destination[prop] = [];
  5094. if (sourceValue.length > 0) {
  5095. if (typeof sourceValue[0] == "object") {
  5096. for (var index = 0; index < sourceValue.length; index++) {
  5097. var clonedValue = cloneValue(sourceValue[index], destination);
  5098. if (destination[prop].indexOf(clonedValue) === -1) {
  5099. destination[prop].push(clonedValue);
  5100. }
  5101. }
  5102. }
  5103. else {
  5104. destination[prop] = sourceValue.slice(0);
  5105. }
  5106. }
  5107. }
  5108. else {
  5109. destination[prop] = cloneValue(sourceValue, destination);
  5110. }
  5111. }
  5112. else {
  5113. destination[prop] = sourceValue;
  5114. }
  5115. }
  5116. };
  5117. Tools.IsEmpty = function (obj) {
  5118. for (var i in obj) {
  5119. return false;
  5120. }
  5121. return true;
  5122. };
  5123. Tools.RegisterTopRootEvents = function (events) {
  5124. for (var index = 0; index < events.length; index++) {
  5125. var event = events[index];
  5126. window.addEventListener(event.name, event.handler, false);
  5127. try {
  5128. if (window.parent) {
  5129. window.parent.addEventListener(event.name, event.handler, false);
  5130. }
  5131. }
  5132. catch (e) {
  5133. }
  5134. }
  5135. };
  5136. Tools.UnregisterTopRootEvents = function (events) {
  5137. for (var index = 0; index < events.length; index++) {
  5138. var event = events[index];
  5139. window.removeEventListener(event.name, event.handler);
  5140. try {
  5141. if (window.parent) {
  5142. window.parent.removeEventListener(event.name, event.handler);
  5143. }
  5144. }
  5145. catch (e) {
  5146. }
  5147. }
  5148. };
  5149. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5150. if (mimeType === void 0) { mimeType = "image/png"; }
  5151. // Read the contents of the framebuffer
  5152. var numberOfChannelsByLine = width * 4;
  5153. var halfHeight = height / 2;
  5154. //Reading datas from WebGL
  5155. var data = engine.readPixels(0, 0, width, height);
  5156. //To flip image on Y axis.
  5157. for (var i = 0; i < halfHeight; i++) {
  5158. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5159. var currentCell = j + i * numberOfChannelsByLine;
  5160. var targetLine = height - i - 1;
  5161. var targetCell = j + targetLine * numberOfChannelsByLine;
  5162. var temp = data[currentCell];
  5163. data[currentCell] = data[targetCell];
  5164. data[targetCell] = temp;
  5165. }
  5166. }
  5167. // Create a 2D canvas to store the result
  5168. if (!screenshotCanvas) {
  5169. screenshotCanvas = document.createElement('canvas');
  5170. }
  5171. screenshotCanvas.width = width;
  5172. screenshotCanvas.height = height;
  5173. var context = screenshotCanvas.getContext('2d');
  5174. // Copy the pixels to a 2D canvas
  5175. var imageData = context.createImageData(width, height);
  5176. var castData = (imageData.data);
  5177. castData.set(data);
  5178. context.putImageData(imageData, 0, 0);
  5179. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5180. };
  5181. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5182. if (mimeType === void 0) { mimeType = "image/png"; }
  5183. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5184. if (successCallback) {
  5185. successCallback(base64Image);
  5186. }
  5187. else {
  5188. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5189. if (("download" in document.createElement("a"))) {
  5190. var a = window.document.createElement("a");
  5191. a.href = base64Image;
  5192. var date = new Date();
  5193. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5194. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5195. window.document.body.appendChild(a);
  5196. a.addEventListener("click", function () {
  5197. a.parentElement.removeChild(a);
  5198. });
  5199. a.click();
  5200. }
  5201. else {
  5202. var newWindow = window.open("");
  5203. var img = newWindow.document.createElement("img");
  5204. img.src = base64Image;
  5205. newWindow.document.body.appendChild(img);
  5206. }
  5207. }
  5208. };
  5209. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5210. if (mimeType === void 0) { mimeType = "image/png"; }
  5211. var width;
  5212. var height;
  5213. // If a precision value is specified
  5214. if (size.precision) {
  5215. width = Math.round(engine.getRenderWidth() * size.precision);
  5216. height = Math.round(width / engine.getAspectRatio(camera));
  5217. }
  5218. else if (size.width && size.height) {
  5219. width = size.width;
  5220. height = size.height;
  5221. }
  5222. else if (size.width && !size.height) {
  5223. width = size.width;
  5224. height = Math.round(width / engine.getAspectRatio(camera));
  5225. }
  5226. else if (size.height && !size.width) {
  5227. height = size.height;
  5228. width = Math.round(height * engine.getAspectRatio(camera));
  5229. }
  5230. else if (!isNaN(size)) {
  5231. height = size;
  5232. width = size;
  5233. }
  5234. else {
  5235. Tools.Error("Invalid 'size' parameter !");
  5236. return;
  5237. }
  5238. if (!screenshotCanvas) {
  5239. screenshotCanvas = document.createElement('canvas');
  5240. }
  5241. screenshotCanvas.width = width;
  5242. screenshotCanvas.height = height;
  5243. var renderContext = screenshotCanvas.getContext("2d");
  5244. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5245. var newWidth = width;
  5246. var newHeight = newWidth / ratio;
  5247. if (newHeight > height) {
  5248. newHeight = height;
  5249. newWidth = newHeight * ratio;
  5250. }
  5251. var offsetX = Math.max(0, width - newWidth) / 2;
  5252. var offsetY = Math.max(0, height - newHeight) / 2;
  5253. renderContext.fillStyle = camera.getScene().clearColor.toHexString();
  5254. renderContext.fillRect(0, 0, width, height);
  5255. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5256. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5257. };
  5258. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  5259. if (mimeType === void 0) { mimeType = "image/png"; }
  5260. var width;
  5261. var height;
  5262. //If a precision value is specified
  5263. if (size.precision) {
  5264. width = Math.round(engine.getRenderWidth() * size.precision);
  5265. height = Math.round(width / engine.getAspectRatio(camera));
  5266. size = { width: width, height: height };
  5267. }
  5268. else if (size.width && size.height) {
  5269. width = size.width;
  5270. height = size.height;
  5271. }
  5272. else if (size.width && !size.height) {
  5273. width = size.width;
  5274. height = Math.round(width / engine.getAspectRatio(camera));
  5275. size = { width: width, height: height };
  5276. }
  5277. else if (size.height && !size.width) {
  5278. height = size.height;
  5279. width = Math.round(height * engine.getAspectRatio(camera));
  5280. size = { width: width, height: height };
  5281. }
  5282. else if (!isNaN(size)) {
  5283. height = size;
  5284. width = size;
  5285. }
  5286. else {
  5287. Tools.Error("Invalid 'size' parameter !");
  5288. return;
  5289. }
  5290. var scene = camera.getScene();
  5291. var previousCamera = null;
  5292. if (scene.activeCamera !== camera) {
  5293. previousCamera = scene.activeCamera;
  5294. scene.activeCamera = camera;
  5295. }
  5296. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5297. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5298. texture.renderList = scene.meshes;
  5299. texture.onAfterRenderObservable.add(function () {
  5300. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5301. });
  5302. scene.incrementRenderId();
  5303. scene.resetCachedMaterial();
  5304. texture.render(true);
  5305. texture.dispose();
  5306. if (previousCamera) {
  5307. scene.activeCamera = previousCamera;
  5308. }
  5309. camera.getProjectionMatrix(true); // Force cache refresh;
  5310. };
  5311. // XHR response validator for local file scenario
  5312. Tools.ValidateXHRData = function (xhr, dataType) {
  5313. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5314. if (dataType === void 0) { dataType = 7; }
  5315. try {
  5316. if (dataType & 1) {
  5317. if (xhr.responseText && xhr.responseText.length > 0) {
  5318. return true;
  5319. }
  5320. else if (dataType === 1) {
  5321. return false;
  5322. }
  5323. }
  5324. if (dataType & 2) {
  5325. // Check header width and height since there is no "TGA" magic number
  5326. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5327. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5328. return true;
  5329. }
  5330. else if (dataType === 2) {
  5331. return false;
  5332. }
  5333. }
  5334. if (dataType & 4) {
  5335. // Check for the "DDS" magic number
  5336. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5337. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5338. return true;
  5339. }
  5340. else {
  5341. return false;
  5342. }
  5343. }
  5344. }
  5345. catch (e) {
  5346. }
  5347. return false;
  5348. };
  5349. /**
  5350. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5351. * Be aware Math.random() could cause collisions, but:
  5352. * "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"
  5353. */
  5354. Tools.RandomId = function () {
  5355. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5356. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5357. return v.toString(16);
  5358. });
  5359. };
  5360. Object.defineProperty(Tools, "NoneLogLevel", {
  5361. get: function () {
  5362. return Tools._NoneLogLevel;
  5363. },
  5364. enumerable: true,
  5365. configurable: true
  5366. });
  5367. Object.defineProperty(Tools, "MessageLogLevel", {
  5368. get: function () {
  5369. return Tools._MessageLogLevel;
  5370. },
  5371. enumerable: true,
  5372. configurable: true
  5373. });
  5374. Object.defineProperty(Tools, "WarningLogLevel", {
  5375. get: function () {
  5376. return Tools._WarningLogLevel;
  5377. },
  5378. enumerable: true,
  5379. configurable: true
  5380. });
  5381. Object.defineProperty(Tools, "ErrorLogLevel", {
  5382. get: function () {
  5383. return Tools._ErrorLogLevel;
  5384. },
  5385. enumerable: true,
  5386. configurable: true
  5387. });
  5388. Object.defineProperty(Tools, "AllLogLevel", {
  5389. get: function () {
  5390. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5391. },
  5392. enumerable: true,
  5393. configurable: true
  5394. });
  5395. Tools._AddLogEntry = function (entry) {
  5396. Tools._LogCache = entry + Tools._LogCache;
  5397. if (Tools.OnNewCacheEntry) {
  5398. Tools.OnNewCacheEntry(entry);
  5399. }
  5400. };
  5401. Tools._FormatMessage = function (message) {
  5402. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5403. var date = new Date();
  5404. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5405. };
  5406. Tools._LogDisabled = function (message) {
  5407. // nothing to do
  5408. };
  5409. Tools._LogEnabled = function (message) {
  5410. var formattedMessage = Tools._FormatMessage(message);
  5411. console.log("BJS - " + formattedMessage);
  5412. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5413. Tools._AddLogEntry(entry);
  5414. };
  5415. Tools._WarnDisabled = function (message) {
  5416. // nothing to do
  5417. };
  5418. Tools._WarnEnabled = function (message) {
  5419. var formattedMessage = Tools._FormatMessage(message);
  5420. console.warn("BJS - " + formattedMessage);
  5421. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5422. Tools._AddLogEntry(entry);
  5423. };
  5424. Tools._ErrorDisabled = function (message) {
  5425. // nothing to do
  5426. };
  5427. Tools._ErrorEnabled = function (message) {
  5428. Tools.errorsCount++;
  5429. var formattedMessage = Tools._FormatMessage(message);
  5430. console.error("BJS - " + formattedMessage);
  5431. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5432. Tools._AddLogEntry(entry);
  5433. };
  5434. Object.defineProperty(Tools, "LogCache", {
  5435. get: function () {
  5436. return Tools._LogCache;
  5437. },
  5438. enumerable: true,
  5439. configurable: true
  5440. });
  5441. Tools.ClearLogCache = function () {
  5442. Tools._LogCache = "";
  5443. Tools.errorsCount = 0;
  5444. };
  5445. Object.defineProperty(Tools, "LogLevels", {
  5446. set: function (level) {
  5447. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5448. Tools.Log = Tools._LogEnabled;
  5449. }
  5450. else {
  5451. Tools.Log = Tools._LogDisabled;
  5452. }
  5453. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5454. Tools.Warn = Tools._WarnEnabled;
  5455. }
  5456. else {
  5457. Tools.Warn = Tools._WarnDisabled;
  5458. }
  5459. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5460. Tools.Error = Tools._ErrorEnabled;
  5461. }
  5462. else {
  5463. Tools.Error = Tools._ErrorDisabled;
  5464. }
  5465. },
  5466. enumerable: true,
  5467. configurable: true
  5468. });
  5469. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5470. get: function () {
  5471. return Tools._PerformanceNoneLogLevel;
  5472. },
  5473. enumerable: true,
  5474. configurable: true
  5475. });
  5476. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5477. get: function () {
  5478. return Tools._PerformanceUserMarkLogLevel;
  5479. },
  5480. enumerable: true,
  5481. configurable: true
  5482. });
  5483. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5484. get: function () {
  5485. return Tools._PerformanceConsoleLogLevel;
  5486. },
  5487. enumerable: true,
  5488. configurable: true
  5489. });
  5490. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5491. set: function (level) {
  5492. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5493. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5494. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5495. return;
  5496. }
  5497. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5498. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5499. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5500. return;
  5501. }
  5502. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5503. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5504. },
  5505. enumerable: true,
  5506. configurable: true
  5507. });
  5508. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5509. };
  5510. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5511. };
  5512. Tools._StartUserMark = function (counterName, condition) {
  5513. if (condition === void 0) { condition = true; }
  5514. if (!condition || !Tools._performance.mark) {
  5515. return;
  5516. }
  5517. Tools._performance.mark(counterName + "-Begin");
  5518. };
  5519. Tools._EndUserMark = function (counterName, condition) {
  5520. if (condition === void 0) { condition = true; }
  5521. if (!condition || !Tools._performance.mark) {
  5522. return;
  5523. }
  5524. Tools._performance.mark(counterName + "-End");
  5525. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5526. };
  5527. Tools._StartPerformanceConsole = function (counterName, condition) {
  5528. if (condition === void 0) { condition = true; }
  5529. if (!condition) {
  5530. return;
  5531. }
  5532. Tools._StartUserMark(counterName, condition);
  5533. if (console.time) {
  5534. console.time(counterName);
  5535. }
  5536. };
  5537. Tools._EndPerformanceConsole = function (counterName, condition) {
  5538. if (condition === void 0) { condition = true; }
  5539. if (!condition) {
  5540. return;
  5541. }
  5542. Tools._EndUserMark(counterName, condition);
  5543. if (console.time) {
  5544. console.timeEnd(counterName);
  5545. }
  5546. };
  5547. Object.defineProperty(Tools, "Now", {
  5548. get: function () {
  5549. if (window.performance && window.performance.now) {
  5550. return window.performance.now();
  5551. }
  5552. return new Date().getTime();
  5553. },
  5554. enumerable: true,
  5555. configurable: true
  5556. });
  5557. /**
  5558. * This method will return the name of the class used to create the instance of the given object.
  5559. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5560. * @param object the object to get the class name from
  5561. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5562. */
  5563. Tools.getClassName = function (object, isType) {
  5564. if (isType === void 0) { isType = false; }
  5565. var name = null;
  5566. if (!isType && object.getClassName) {
  5567. name = object.getClassName();
  5568. }
  5569. else {
  5570. if (object instanceof Object) {
  5571. var classObj = isType ? object : Object.getPrototypeOf(object);
  5572. name = classObj.constructor["__bjsclassName__"];
  5573. }
  5574. if (!name) {
  5575. name = typeof object;
  5576. }
  5577. }
  5578. return name;
  5579. };
  5580. Tools.first = function (array, predicate) {
  5581. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  5582. var el = array_1[_i];
  5583. if (predicate(el)) {
  5584. return el;
  5585. }
  5586. }
  5587. };
  5588. /**
  5589. * This method will return the name of the full name of the class, including its owning module (if any).
  5590. * 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).
  5591. * @param object the object to get the class name from
  5592. * @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.
  5593. */
  5594. Tools.getFullClassName = function (object, isType) {
  5595. if (isType === void 0) { isType = false; }
  5596. var className = null;
  5597. var moduleName = null;
  5598. if (!isType && object.getClassName) {
  5599. className = object.getClassName();
  5600. }
  5601. else {
  5602. if (object instanceof Object) {
  5603. var classObj = isType ? object : Object.getPrototypeOf(object);
  5604. className = classObj.constructor["__bjsclassName__"];
  5605. moduleName = classObj.constructor["__bjsmoduleName__"];
  5606. }
  5607. if (!className) {
  5608. className = typeof object;
  5609. }
  5610. }
  5611. if (!className) {
  5612. return null;
  5613. }
  5614. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  5615. };
  5616. /**
  5617. * 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.
  5618. * @param array
  5619. */
  5620. Tools.arrayOrStringFeeder = function (array) {
  5621. return function (index) {
  5622. if (index >= array.length) {
  5623. return null;
  5624. }
  5625. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5626. if (val && val.getHashCode) {
  5627. val = val.getHashCode();
  5628. }
  5629. if (typeof val === "string") {
  5630. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5631. }
  5632. return val;
  5633. };
  5634. };
  5635. /**
  5636. * Compute the hashCode of a stream of number
  5637. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5638. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5639. * @return the hash code computed
  5640. */
  5641. Tools.hashCodeFromStream = function (feeder) {
  5642. // Based from here: http://stackoverflow.com/a/7616484/802124
  5643. var hash = 0;
  5644. var index = 0;
  5645. var chr = feeder(index++);
  5646. while (chr != null) {
  5647. hash = ((hash << 5) - hash) + chr;
  5648. hash |= 0; // Convert to 32bit integer
  5649. chr = feeder(index++);
  5650. }
  5651. return hash;
  5652. };
  5653. return Tools;
  5654. }());
  5655. Tools.BaseUrl = "";
  5656. Tools.CorsBehavior = "anonymous";
  5657. Tools.UseFallbackTexture = true;
  5658. // Logs
  5659. Tools._NoneLogLevel = 0;
  5660. Tools._MessageLogLevel = 1;
  5661. Tools._WarningLogLevel = 2;
  5662. Tools._ErrorLogLevel = 4;
  5663. Tools._LogCache = "";
  5664. Tools.errorsCount = 0;
  5665. Tools.Log = Tools._LogEnabled;
  5666. Tools.Warn = Tools._WarnEnabled;
  5667. Tools.Error = Tools._ErrorEnabled;
  5668. // Performances
  5669. Tools._PerformanceNoneLogLevel = 0;
  5670. Tools._PerformanceUserMarkLogLevel = 1;
  5671. Tools._PerformanceConsoleLogLevel = 2;
  5672. Tools._performance = window.performance;
  5673. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5674. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5675. BABYLON.Tools = Tools;
  5676. /**
  5677. * This class is used to track a performance counter which is number based.
  5678. * The user has access to many properties which give statistics of different nature
  5679. *
  5680. * The implementer can track two kinds of Performance Counter: time and count
  5681. * 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.
  5682. * 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.
  5683. */
  5684. var PerfCounter = (function () {
  5685. function PerfCounter() {
  5686. this._startMonitoringTime = 0;
  5687. this._min = 0;
  5688. this._max = 0;
  5689. this._average = 0;
  5690. this._lastSecAverage = 0;
  5691. this._current = 0;
  5692. this._totalValueCount = 0;
  5693. this._totalAccumulated = 0;
  5694. this._lastSecAccumulated = 0;
  5695. this._lastSecTime = 0;
  5696. this._lastSecValueCount = 0;
  5697. }
  5698. Object.defineProperty(PerfCounter.prototype, "min", {
  5699. /**
  5700. * Returns the smallest value ever
  5701. */
  5702. get: function () {
  5703. return this._min;
  5704. },
  5705. enumerable: true,
  5706. configurable: true
  5707. });
  5708. Object.defineProperty(PerfCounter.prototype, "max", {
  5709. /**
  5710. * Returns the biggest value ever
  5711. */
  5712. get: function () {
  5713. return this._max;
  5714. },
  5715. enumerable: true,
  5716. configurable: true
  5717. });
  5718. Object.defineProperty(PerfCounter.prototype, "average", {
  5719. /**
  5720. * Returns the average value since the performance counter is running
  5721. */
  5722. get: function () {
  5723. return this._average;
  5724. },
  5725. enumerable: true,
  5726. configurable: true
  5727. });
  5728. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5729. /**
  5730. * Returns the average value of the last second the counter was monitored
  5731. */
  5732. get: function () {
  5733. return this._lastSecAverage;
  5734. },
  5735. enumerable: true,
  5736. configurable: true
  5737. });
  5738. Object.defineProperty(PerfCounter.prototype, "current", {
  5739. /**
  5740. * Returns the current value
  5741. */
  5742. get: function () {
  5743. return this._current;
  5744. },
  5745. enumerable: true,
  5746. configurable: true
  5747. });
  5748. Object.defineProperty(PerfCounter.prototype, "total", {
  5749. get: function () {
  5750. return this._totalAccumulated;
  5751. },
  5752. enumerable: true,
  5753. configurable: true
  5754. });
  5755. /**
  5756. * Call this method to start monitoring a new frame.
  5757. * 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.
  5758. */
  5759. PerfCounter.prototype.fetchNewFrame = function () {
  5760. this._totalValueCount++;
  5761. this._current = 0;
  5762. this._lastSecValueCount++;
  5763. };
  5764. /**
  5765. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5766. * @param newCount the count value to add to the monitored count
  5767. * @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.
  5768. */
  5769. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5770. this._current += newCount;
  5771. if (fetchResult) {
  5772. this._fetchResult();
  5773. }
  5774. };
  5775. /**
  5776. * Start monitoring this performance counter
  5777. */
  5778. PerfCounter.prototype.beginMonitoring = function () {
  5779. this._startMonitoringTime = Tools.Now;
  5780. };
  5781. /**
  5782. * Compute the time lapsed since the previous beginMonitoring() call.
  5783. * @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
  5784. */
  5785. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5786. if (newFrame === void 0) { newFrame = true; }
  5787. if (newFrame) {
  5788. this.fetchNewFrame();
  5789. }
  5790. var currentTime = Tools.Now;
  5791. this._current = currentTime - this._startMonitoringTime;
  5792. if (newFrame) {
  5793. this._fetchResult();
  5794. }
  5795. };
  5796. PerfCounter.prototype._fetchResult = function () {
  5797. this._totalAccumulated += this._current;
  5798. this._lastSecAccumulated += this._current;
  5799. // Min/Max update
  5800. this._min = Math.min(this._min, this._current);
  5801. this._max = Math.max(this._max, this._current);
  5802. this._average = this._totalAccumulated / this._totalValueCount;
  5803. // Reset last sec?
  5804. var now = Tools.Now;
  5805. if ((now - this._lastSecTime) > 1000) {
  5806. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5807. this._lastSecTime = now;
  5808. this._lastSecAccumulated = 0;
  5809. this._lastSecValueCount = 0;
  5810. }
  5811. };
  5812. return PerfCounter;
  5813. }());
  5814. BABYLON.PerfCounter = PerfCounter;
  5815. /**
  5816. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  5817. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5818. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5819. * @param name The name of the class, case should be preserved
  5820. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  5821. */
  5822. function className(name, module) {
  5823. return function (target) {
  5824. target["__bjsclassName__"] = name;
  5825. target["__bjsmoduleName__"] = (module != null) ? module : null;
  5826. };
  5827. }
  5828. BABYLON.className = className;
  5829. /**
  5830. * An implementation of a loop for asynchronous functions.
  5831. */
  5832. var AsyncLoop = (function () {
  5833. /**
  5834. * Constroctor.
  5835. * @param iterations the number of iterations.
  5836. * @param _fn the function to run each iteration
  5837. * @param _successCallback the callback that will be called upon succesful execution
  5838. * @param offset starting offset.
  5839. */
  5840. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5841. if (offset === void 0) { offset = 0; }
  5842. this.iterations = iterations;
  5843. this._fn = _fn;
  5844. this._successCallback = _successCallback;
  5845. this.index = offset - 1;
  5846. this._done = false;
  5847. }
  5848. /**
  5849. * Execute the next iteration. Must be called after the last iteration was finished.
  5850. */
  5851. AsyncLoop.prototype.executeNext = function () {
  5852. if (!this._done) {
  5853. if (this.index + 1 < this.iterations) {
  5854. ++this.index;
  5855. this._fn(this);
  5856. }
  5857. else {
  5858. this.breakLoop();
  5859. }
  5860. }
  5861. };
  5862. /**
  5863. * Break the loop and run the success callback.
  5864. */
  5865. AsyncLoop.prototype.breakLoop = function () {
  5866. this._done = true;
  5867. this._successCallback();
  5868. };
  5869. /**
  5870. * Helper function
  5871. */
  5872. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5873. if (offset === void 0) { offset = 0; }
  5874. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5875. loop.executeNext();
  5876. return loop;
  5877. };
  5878. /**
  5879. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5880. * @param iterations total number of iterations
  5881. * @param syncedIterations number of synchronous iterations in each async iteration.
  5882. * @param fn the function to call each iteration.
  5883. * @param callback a success call back that will be called when iterating stops.
  5884. * @param breakFunction a break condition (optional)
  5885. * @param timeout timeout settings for the setTimeout function. default - 0.
  5886. * @constructor
  5887. */
  5888. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5889. if (timeout === void 0) { timeout = 0; }
  5890. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5891. if (breakFunction && breakFunction())
  5892. loop.breakLoop();
  5893. else {
  5894. setTimeout(function () {
  5895. for (var i = 0; i < syncedIterations; ++i) {
  5896. var iteration = (loop.index * syncedIterations) + i;
  5897. if (iteration >= iterations)
  5898. break;
  5899. fn(iteration);
  5900. if (breakFunction && breakFunction()) {
  5901. loop.breakLoop();
  5902. break;
  5903. }
  5904. }
  5905. loop.executeNext();
  5906. }, timeout);
  5907. }
  5908. }, callback);
  5909. };
  5910. return AsyncLoop;
  5911. }());
  5912. BABYLON.AsyncLoop = AsyncLoop;
  5913. })(BABYLON || (BABYLON = {}));
  5914. //# sourceMappingURL=babylon.tools.js.map
  5915. var BABYLON;
  5916. (function (BABYLON) {
  5917. var Internals;
  5918. (function (Internals) {
  5919. var _AlphaState = (function () {
  5920. /**
  5921. * Initializes the state.
  5922. */
  5923. function _AlphaState() {
  5924. this._isAlphaBlendDirty = false;
  5925. this._isBlendFunctionParametersDirty = false;
  5926. this._alphaBlend = false;
  5927. this._blendFunctionParameters = new Array(4);
  5928. this.reset();
  5929. }
  5930. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5931. get: function () {
  5932. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5933. },
  5934. enumerable: true,
  5935. configurable: true
  5936. });
  5937. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5938. get: function () {
  5939. return this._alphaBlend;
  5940. },
  5941. set: function (value) {
  5942. if (this._alphaBlend === value) {
  5943. return;
  5944. }
  5945. this._alphaBlend = value;
  5946. this._isAlphaBlendDirty = true;
  5947. },
  5948. enumerable: true,
  5949. configurable: true
  5950. });
  5951. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5952. if (this._blendFunctionParameters[0] === value0 &&
  5953. this._blendFunctionParameters[1] === value1 &&
  5954. this._blendFunctionParameters[2] === value2 &&
  5955. this._blendFunctionParameters[3] === value3) {
  5956. return;
  5957. }
  5958. this._blendFunctionParameters[0] = value0;
  5959. this._blendFunctionParameters[1] = value1;
  5960. this._blendFunctionParameters[2] = value2;
  5961. this._blendFunctionParameters[3] = value3;
  5962. this._isBlendFunctionParametersDirty = true;
  5963. };
  5964. _AlphaState.prototype.reset = function () {
  5965. this._alphaBlend = false;
  5966. this._blendFunctionParameters[0] = null;
  5967. this._blendFunctionParameters[1] = null;
  5968. this._blendFunctionParameters[2] = null;
  5969. this._blendFunctionParameters[3] = null;
  5970. this._isAlphaBlendDirty = true;
  5971. this._isBlendFunctionParametersDirty = false;
  5972. };
  5973. _AlphaState.prototype.apply = function (gl) {
  5974. if (!this.isDirty) {
  5975. return;
  5976. }
  5977. // Alpha blend
  5978. if (this._isAlphaBlendDirty) {
  5979. if (this._alphaBlend) {
  5980. gl.enable(gl.BLEND);
  5981. }
  5982. else {
  5983. gl.disable(gl.BLEND);
  5984. }
  5985. this._isAlphaBlendDirty = false;
  5986. }
  5987. // Alpha function
  5988. if (this._isBlendFunctionParametersDirty) {
  5989. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5990. this._isBlendFunctionParametersDirty = false;
  5991. }
  5992. };
  5993. return _AlphaState;
  5994. }());
  5995. Internals._AlphaState = _AlphaState;
  5996. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5997. })(BABYLON || (BABYLON = {}));
  5998. //# sourceMappingURL=babylon.alphaCullingState.js.map
  5999. var BABYLON;
  6000. (function (BABYLON) {
  6001. var Internals;
  6002. (function (Internals) {
  6003. var _DepthCullingState = (function () {
  6004. /**
  6005. * Initializes the state.
  6006. */
  6007. function _DepthCullingState() {
  6008. this._isDepthTestDirty = false;
  6009. this._isDepthMaskDirty = false;
  6010. this._isDepthFuncDirty = false;
  6011. this._isCullFaceDirty = false;
  6012. this._isCullDirty = false;
  6013. this._isZOffsetDirty = false;
  6014. this.reset();
  6015. }
  6016. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6017. get: function () {
  6018. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6019. },
  6020. enumerable: true,
  6021. configurable: true
  6022. });
  6023. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6024. get: function () {
  6025. return this._zOffset;
  6026. },
  6027. set: function (value) {
  6028. if (this._zOffset === value) {
  6029. return;
  6030. }
  6031. this._zOffset = value;
  6032. this._isZOffsetDirty = true;
  6033. },
  6034. enumerable: true,
  6035. configurable: true
  6036. });
  6037. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6038. get: function () {
  6039. return this._cullFace;
  6040. },
  6041. set: function (value) {
  6042. if (this._cullFace === value) {
  6043. return;
  6044. }
  6045. this._cullFace = value;
  6046. this._isCullFaceDirty = true;
  6047. },
  6048. enumerable: true,
  6049. configurable: true
  6050. });
  6051. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6052. get: function () {
  6053. return this._cull;
  6054. },
  6055. set: function (value) {
  6056. if (this._cull === value) {
  6057. return;
  6058. }
  6059. this._cull = value;
  6060. this._isCullDirty = true;
  6061. },
  6062. enumerable: true,
  6063. configurable: true
  6064. });
  6065. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6066. get: function () {
  6067. return this._depthFunc;
  6068. },
  6069. set: function (value) {
  6070. if (this._depthFunc === value) {
  6071. return;
  6072. }
  6073. this._depthFunc = value;
  6074. this._isDepthFuncDirty = true;
  6075. },
  6076. enumerable: true,
  6077. configurable: true
  6078. });
  6079. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6080. get: function () {
  6081. return this._depthMask;
  6082. },
  6083. set: function (value) {
  6084. if (this._depthMask === value) {
  6085. return;
  6086. }
  6087. this._depthMask = value;
  6088. this._isDepthMaskDirty = true;
  6089. },
  6090. enumerable: true,
  6091. configurable: true
  6092. });
  6093. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6094. get: function () {
  6095. return this._depthTest;
  6096. },
  6097. set: function (value) {
  6098. if (this._depthTest === value) {
  6099. return;
  6100. }
  6101. this._depthTest = value;
  6102. this._isDepthTestDirty = true;
  6103. },
  6104. enumerable: true,
  6105. configurable: true
  6106. });
  6107. _DepthCullingState.prototype.reset = function () {
  6108. this._depthMask = true;
  6109. this._depthTest = true;
  6110. this._depthFunc = null;
  6111. this._cullFace = null;
  6112. this._cull = null;
  6113. this._zOffset = 0;
  6114. this._isDepthTestDirty = true;
  6115. this._isDepthMaskDirty = true;
  6116. this._isDepthFuncDirty = false;
  6117. this._isCullFaceDirty = false;
  6118. this._isCullDirty = false;
  6119. this._isZOffsetDirty = false;
  6120. };
  6121. _DepthCullingState.prototype.apply = function (gl) {
  6122. if (!this.isDirty) {
  6123. return;
  6124. }
  6125. // Cull
  6126. if (this._isCullDirty) {
  6127. if (this.cull) {
  6128. gl.enable(gl.CULL_FACE);
  6129. }
  6130. else {
  6131. gl.disable(gl.CULL_FACE);
  6132. }
  6133. this._isCullDirty = false;
  6134. }
  6135. // Cull face
  6136. if (this._isCullFaceDirty) {
  6137. gl.cullFace(this.cullFace);
  6138. this._isCullFaceDirty = false;
  6139. }
  6140. // Depth mask
  6141. if (this._isDepthMaskDirty) {
  6142. gl.depthMask(this.depthMask);
  6143. this._isDepthMaskDirty = false;
  6144. }
  6145. // Depth test
  6146. if (this._isDepthTestDirty) {
  6147. if (this.depthTest) {
  6148. gl.enable(gl.DEPTH_TEST);
  6149. }
  6150. else {
  6151. gl.disable(gl.DEPTH_TEST);
  6152. }
  6153. this._isDepthTestDirty = false;
  6154. }
  6155. // Depth func
  6156. if (this._isDepthFuncDirty) {
  6157. gl.depthFunc(this.depthFunc);
  6158. this._isDepthFuncDirty = false;
  6159. }
  6160. // zOffset
  6161. if (this._isZOffsetDirty) {
  6162. if (this.zOffset) {
  6163. gl.enable(gl.POLYGON_OFFSET_FILL);
  6164. gl.polygonOffset(this.zOffset, 0);
  6165. }
  6166. else {
  6167. gl.disable(gl.POLYGON_OFFSET_FILL);
  6168. }
  6169. this._isZOffsetDirty = false;
  6170. }
  6171. };
  6172. return _DepthCullingState;
  6173. }());
  6174. Internals._DepthCullingState = _DepthCullingState;
  6175. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6176. })(BABYLON || (BABYLON = {}));
  6177. //# sourceMappingURL=babylon.depthCullingState.js.map
  6178. var BABYLON;
  6179. (function (BABYLON) {
  6180. var Internals;
  6181. (function (Internals) {
  6182. var _StencilState = (function () {
  6183. function _StencilState() {
  6184. this._isStencilTestDirty = false;
  6185. this._isStencilMaskDirty = false;
  6186. this._isStencilFuncDirty = false;
  6187. this._isStencilOpDirty = false;
  6188. this.reset();
  6189. }
  6190. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6191. get: function () {
  6192. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6193. },
  6194. enumerable: true,
  6195. configurable: true
  6196. });
  6197. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6198. get: function () {
  6199. return this._stencilFunc;
  6200. },
  6201. set: function (value) {
  6202. if (this._stencilFunc === value) {
  6203. return;
  6204. }
  6205. this._stencilFunc = value;
  6206. this._isStencilFuncDirty = true;
  6207. },
  6208. enumerable: true,
  6209. configurable: true
  6210. });
  6211. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6212. get: function () {
  6213. return this._stencilFuncRef;
  6214. },
  6215. set: function (value) {
  6216. if (this._stencilFuncRef === value) {
  6217. return;
  6218. }
  6219. this._stencilFuncRef = value;
  6220. this._isStencilFuncDirty = true;
  6221. },
  6222. enumerable: true,
  6223. configurable: true
  6224. });
  6225. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6226. get: function () {
  6227. return this._stencilFuncMask;
  6228. },
  6229. set: function (value) {
  6230. if (this._stencilFuncMask === value) {
  6231. return;
  6232. }
  6233. this._stencilFuncMask = value;
  6234. this._isStencilFuncDirty = true;
  6235. },
  6236. enumerable: true,
  6237. configurable: true
  6238. });
  6239. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6240. get: function () {
  6241. return this._stencilOpStencilFail;
  6242. },
  6243. set: function (value) {
  6244. if (this._stencilOpStencilFail === value) {
  6245. return;
  6246. }
  6247. this._stencilOpStencilFail = value;
  6248. this._isStencilOpDirty = true;
  6249. },
  6250. enumerable: true,
  6251. configurable: true
  6252. });
  6253. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6254. get: function () {
  6255. return this._stencilOpDepthFail;
  6256. },
  6257. set: function (value) {
  6258. if (this._stencilOpDepthFail === value) {
  6259. return;
  6260. }
  6261. this._stencilOpDepthFail = value;
  6262. this._isStencilOpDirty = true;
  6263. },
  6264. enumerable: true,
  6265. configurable: true
  6266. });
  6267. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6268. get: function () {
  6269. return this._stencilOpStencilDepthPass;
  6270. },
  6271. set: function (value) {
  6272. if (this._stencilOpStencilDepthPass === value) {
  6273. return;
  6274. }
  6275. this._stencilOpStencilDepthPass = value;
  6276. this._isStencilOpDirty = true;
  6277. },
  6278. enumerable: true,
  6279. configurable: true
  6280. });
  6281. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6282. get: function () {
  6283. return this._stencilMask;
  6284. },
  6285. set: function (value) {
  6286. if (this._stencilMask === value) {
  6287. return;
  6288. }
  6289. this._stencilMask = value;
  6290. this._isStencilMaskDirty = true;
  6291. },
  6292. enumerable: true,
  6293. configurable: true
  6294. });
  6295. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6296. get: function () {
  6297. return this._stencilTest;
  6298. },
  6299. set: function (value) {
  6300. if (this._stencilTest === value) {
  6301. return;
  6302. }
  6303. this._stencilTest = value;
  6304. this._isStencilTestDirty = true;
  6305. },
  6306. enumerable: true,
  6307. configurable: true
  6308. });
  6309. _StencilState.prototype.reset = function () {
  6310. this._stencilTest = false;
  6311. this._stencilMask = 0xFF;
  6312. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6313. this._stencilFuncRef = 1;
  6314. this._stencilFuncMask = 0xFF;
  6315. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6316. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6317. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6318. this._isStencilTestDirty = true;
  6319. this._isStencilMaskDirty = true;
  6320. this._isStencilFuncDirty = true;
  6321. this._isStencilOpDirty = true;
  6322. };
  6323. _StencilState.prototype.apply = function (gl) {
  6324. if (!this.isDirty) {
  6325. return;
  6326. }
  6327. // Stencil test
  6328. if (this._isStencilTestDirty) {
  6329. if (this.stencilTest) {
  6330. gl.enable(gl.STENCIL_TEST);
  6331. }
  6332. else {
  6333. gl.disable(gl.STENCIL_TEST);
  6334. }
  6335. this._isStencilTestDirty = false;
  6336. }
  6337. // Stencil mask
  6338. if (this._isStencilMaskDirty) {
  6339. gl.stencilMask(this.stencilMask);
  6340. this._isStencilMaskDirty = false;
  6341. }
  6342. // Stencil func
  6343. if (this._isStencilFuncDirty) {
  6344. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6345. this._isStencilFuncDirty = false;
  6346. }
  6347. // Stencil op
  6348. if (this._isStencilOpDirty) {
  6349. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6350. this._isStencilOpDirty = false;
  6351. }
  6352. };
  6353. return _StencilState;
  6354. }());
  6355. Internals._StencilState = _StencilState;
  6356. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6357. })(BABYLON || (BABYLON = {}));
  6358. //# sourceMappingURL=babylon.stencilState.js.map
  6359. var BABYLON;
  6360. (function (BABYLON) {
  6361. var compileShader = function (gl, source, type, defines, shaderVersion) {
  6362. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6363. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  6364. gl.compileShader(shader);
  6365. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6366. throw new Error(gl.getShaderInfoLog(shader));
  6367. }
  6368. return shader;
  6369. };
  6370. var HALF_FLOAT_OES = 0x8D61;
  6371. var getWebGLTextureType = function (gl, type) {
  6372. if (type === Engine.TEXTURETYPE_FLOAT) {
  6373. return gl.FLOAT;
  6374. }
  6375. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6376. // Add Half Float Constant.
  6377. return HALF_FLOAT_OES;
  6378. }
  6379. return gl.UNSIGNED_BYTE;
  6380. };
  6381. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6382. var magFilter = gl.NEAREST;
  6383. var minFilter = gl.NEAREST;
  6384. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6385. magFilter = gl.LINEAR;
  6386. if (generateMipMaps) {
  6387. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6388. }
  6389. else {
  6390. minFilter = gl.LINEAR;
  6391. }
  6392. }
  6393. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6394. magFilter = gl.LINEAR;
  6395. if (generateMipMaps) {
  6396. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6397. }
  6398. else {
  6399. minFilter = gl.LINEAR;
  6400. }
  6401. }
  6402. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6403. magFilter = gl.NEAREST;
  6404. if (generateMipMaps) {
  6405. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6406. }
  6407. else {
  6408. minFilter = gl.NEAREST;
  6409. }
  6410. }
  6411. return {
  6412. min: minFilter,
  6413. mag: magFilter
  6414. };
  6415. };
  6416. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6417. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6418. var engine = scene.getEngine();
  6419. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6420. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6421. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6422. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6423. texture._baseWidth = width;
  6424. texture._baseHeight = height;
  6425. texture._width = potWidth;
  6426. texture._height = potHeight;
  6427. texture.isReady = true;
  6428. processFunction(potWidth, potHeight);
  6429. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6430. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6431. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6432. if (!noMipmap && !isCompressed) {
  6433. gl.generateMipmap(gl.TEXTURE_2D);
  6434. }
  6435. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6436. engine.resetTextureCache();
  6437. scene._removePendingData(texture);
  6438. texture.onLoadedCallbacks.forEach(function (callback) {
  6439. callback();
  6440. });
  6441. texture.onLoadedCallbacks = [];
  6442. };
  6443. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6444. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6445. var img;
  6446. var onload = function () {
  6447. loadedImages[index] = img;
  6448. loadedImages._internalCount++;
  6449. scene._removePendingData(img);
  6450. if (loadedImages._internalCount === 6) {
  6451. onfinish(loadedImages);
  6452. }
  6453. };
  6454. var onerror = function () {
  6455. scene._removePendingData(img);
  6456. if (onErrorCallBack) {
  6457. onErrorCallBack();
  6458. }
  6459. };
  6460. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6461. scene._addPendingData(img);
  6462. };
  6463. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  6464. if (onError === void 0) { onError = null; }
  6465. var loadedImages = [];
  6466. loadedImages._internalCount = 0;
  6467. for (var index = 0; index < 6; index++) {
  6468. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  6469. }
  6470. };
  6471. var InstancingAttributeInfo = (function () {
  6472. function InstancingAttributeInfo() {
  6473. }
  6474. return InstancingAttributeInfo;
  6475. }());
  6476. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6477. var EngineCapabilities = (function () {
  6478. function EngineCapabilities() {
  6479. }
  6480. return EngineCapabilities;
  6481. }());
  6482. BABYLON.EngineCapabilities = EngineCapabilities;
  6483. /**
  6484. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6485. */
  6486. var Engine = (function () {
  6487. /**
  6488. * @constructor
  6489. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6490. * @param {boolean} [antialias] - enable antialias
  6491. * @param options - further options to be sent to the getContext function
  6492. */
  6493. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6494. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  6495. var _this = this;
  6496. // Public members
  6497. this.isFullscreen = false;
  6498. this.isPointerLock = false;
  6499. this.cullBackFaces = true;
  6500. this.renderEvenInBackground = true;
  6501. // To enable/disable IDB support and avoid XHR on .manifest
  6502. this.enableOfflineSupport = true;
  6503. this.scenes = new Array();
  6504. this._windowIsBackground = false;
  6505. this._webGLVersion = 1.0;
  6506. this._badOS = false;
  6507. this._drawCalls = new BABYLON.PerfCounter();
  6508. this._renderingQueueLaunched = false;
  6509. this._activeRenderLoops = [];
  6510. // FPS
  6511. this.fpsRange = 60;
  6512. this.previousFramesDuration = [];
  6513. this.fps = 60;
  6514. this.deltaTime = 0;
  6515. // States
  6516. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6517. this._stencilState = new BABYLON.Internals._StencilState();
  6518. this._alphaState = new BABYLON.Internals._AlphaState();
  6519. this._alphaMode = Engine.ALPHA_DISABLE;
  6520. // Cache
  6521. this._loadedTexturesCache = new Array();
  6522. this._maxTextureChannels = 16;
  6523. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6524. this._compiledEffects = {};
  6525. this._vertexAttribArraysEnabled = [];
  6526. this._uintIndicesCurrentlySet = false;
  6527. this._currentBoundBuffer = new Array();
  6528. this._currentBufferPointers = [];
  6529. this._currentInstanceLocations = new Array();
  6530. this._currentInstanceBuffers = new Array();
  6531. // Hardware supported Compressed Textures
  6532. this._texturesSupported = new Array();
  6533. this._onVRFullScreenTriggered = function () {
  6534. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  6535. //get the old size before we change
  6536. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  6537. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  6538. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  6539. //But actually, no browser follow the specs...
  6540. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  6541. //get the width and height, change the render size
  6542. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  6543. var width, height;
  6544. _this.setHardwareScalingLevel(1);
  6545. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  6546. }
  6547. else {
  6548. //When the specs are implemented, need to uncomment this.
  6549. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  6550. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  6551. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  6552. _this._vrDisplayEnabled = undefined;
  6553. }
  6554. };
  6555. this._renderingCanvas = canvas;
  6556. this._externalData = new BABYLON.StringDictionary();
  6557. options = options || {};
  6558. if (antialias != null) {
  6559. options.antialias = antialias;
  6560. }
  6561. if (options.preserveDrawingBuffer === undefined) {
  6562. options.preserveDrawingBuffer = false;
  6563. }
  6564. // Checks if some of the format renders first to allow the use of webgl inspector.
  6565. var renderToFullFloat = this._canRenderToFloatTexture();
  6566. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  6567. // GL
  6568. if (!options.disableWebGL2Support) {
  6569. try {
  6570. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6571. if (this._gl) {
  6572. this._webGLVersion = 2.0;
  6573. }
  6574. }
  6575. catch (e) {
  6576. }
  6577. }
  6578. if (!this._gl) {
  6579. if (!canvas) {
  6580. throw new Error("The provided canvas is null or undefined.");
  6581. }
  6582. try {
  6583. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6584. }
  6585. catch (e) {
  6586. throw new Error("WebGL not supported");
  6587. }
  6588. }
  6589. if (!this._gl) {
  6590. throw new Error("WebGL not supported");
  6591. }
  6592. this._onBlur = function () {
  6593. _this._windowIsBackground = true;
  6594. };
  6595. this._onFocus = function () {
  6596. _this._windowIsBackground = false;
  6597. };
  6598. window.addEventListener("blur", this._onBlur);
  6599. window.addEventListener("focus", this._onFocus);
  6600. // Viewport
  6601. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6602. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6603. this.resize();
  6604. // Caps
  6605. this._isStencilEnable = options.stencil;
  6606. this._caps = new EngineCapabilities();
  6607. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6608. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6609. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6610. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6611. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6612. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  6613. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  6614. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  6615. // Infos
  6616. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6617. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6618. if (rendererInfo != null) {
  6619. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6620. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6621. }
  6622. if (!this._glVendor) {
  6623. this._glVendor = "Unknown vendor";
  6624. }
  6625. if (!this._glRenderer) {
  6626. this._glRenderer = "Unknown renderer";
  6627. }
  6628. // Extensions
  6629. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  6630. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  6631. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  6632. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  6633. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  6634. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  6635. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  6636. this._caps.atc = this._gl.getExtension('WEBGL_compressed_texture_atc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_atc');
  6637. this._caps.textureFloat = this._webGLVersion > 1 || (this._gl.getExtension('OES_texture_float') !== null);
  6638. 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');
  6639. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6640. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  6641. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  6642. this._caps.highPrecisionShaderSupported = true;
  6643. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  6644. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6645. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  6646. this._caps.textureFloatRender = renderToFullFloat;
  6647. this._caps.textureHalfFloat = this._webGLVersion > 1 || (this._gl.getExtension('OES_texture_half_float') !== null);
  6648. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float_linear');
  6649. this._caps.textureHalfFloatRender = renderToHalfFloat;
  6650. // instancesCount
  6651. if (this._webGLVersion > 1) {
  6652. this._caps.instancedArrays = true;
  6653. }
  6654. else {
  6655. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  6656. if (instanceExtension != null) {
  6657. this._caps.instancedArrays = true;
  6658. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE;
  6659. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE;
  6660. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE;
  6661. }
  6662. else {
  6663. this._caps.instancedArrays = false;
  6664. }
  6665. }
  6666. // Intelligently add supported compressed formats in order to check for.
  6667. // Check for ASTC support first as it is most powerful and to be very cross platform.
  6668. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  6669. // Likely no hardware which supports both PVR & DXT, so order matters little.
  6670. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  6671. // ATC before ETC1, since both old (widely supported), but ATC supports alpha, but ETC1 does not
  6672. if (this._caps.astc)
  6673. this.texturesSupported.push('-astc.ktx');
  6674. if (this._caps.s3tc)
  6675. this.texturesSupported.push('-dxt.ktx');
  6676. if (this._caps.pvrtc)
  6677. this.texturesSupported.push('-pvrtc.ktx');
  6678. if (this._caps.etc2)
  6679. this.texturesSupported.push('-etc2.ktx');
  6680. if (this._caps.atc)
  6681. this.texturesSupported.push('-atc.ktx');
  6682. if (this._caps.etc1)
  6683. this.texturesSupported.push('-etc1.ktx');
  6684. if (this._gl.getShaderPrecisionFormat) {
  6685. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6686. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6687. }
  6688. // Depth buffer
  6689. this.setDepthBuffer(true);
  6690. this.setDepthFunctionToLessOrEqual();
  6691. this.setDepthWrite(true);
  6692. // Fullscreen
  6693. this._onFullscreenChange = function () {
  6694. if (document.fullscreen !== undefined) {
  6695. _this.isFullscreen = document.fullscreen;
  6696. }
  6697. else if (document.mozFullScreen !== undefined) {
  6698. _this.isFullscreen = document.mozFullScreen;
  6699. }
  6700. else if (document.webkitIsFullScreen !== undefined) {
  6701. _this.isFullscreen = document.webkitIsFullScreen;
  6702. }
  6703. else if (document.msIsFullScreen !== undefined) {
  6704. _this.isFullscreen = document.msIsFullScreen;
  6705. }
  6706. // Pointer lock
  6707. if (_this.isFullscreen && _this._pointerLockRequested) {
  6708. canvas.requestPointerLock = canvas.requestPointerLock ||
  6709. canvas.msRequestPointerLock ||
  6710. canvas.mozRequestPointerLock ||
  6711. canvas.webkitRequestPointerLock;
  6712. if (canvas.requestPointerLock) {
  6713. canvas.requestPointerLock();
  6714. }
  6715. }
  6716. };
  6717. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6718. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6719. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6720. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6721. // Pointer lock
  6722. this._onPointerLockChange = function () {
  6723. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6724. document.webkitPointerLockElement === canvas ||
  6725. document.msPointerLockElement === canvas ||
  6726. document.pointerLockElement === canvas);
  6727. };
  6728. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6729. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6730. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6731. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6732. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6733. Engine.audioEngine = new BABYLON.AudioEngine();
  6734. }
  6735. //default loading screen
  6736. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6737. //Load WebVR Devices
  6738. if (options.autoEnableWebVR) {
  6739. this.initWebVR();
  6740. }
  6741. //Detect if we are running on a faulty buggy OS.
  6742. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  6743. //ua sniffing is the tool of the devil.
  6744. this._badOS = regexp.test(navigator.userAgent);
  6745. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6746. }
  6747. Object.defineProperty(Engine, "NEVER", {
  6748. get: function () {
  6749. return Engine._NEVER;
  6750. },
  6751. enumerable: true,
  6752. configurable: true
  6753. });
  6754. Object.defineProperty(Engine, "ALWAYS", {
  6755. get: function () {
  6756. return Engine._ALWAYS;
  6757. },
  6758. enumerable: true,
  6759. configurable: true
  6760. });
  6761. Object.defineProperty(Engine, "LESS", {
  6762. get: function () {
  6763. return Engine._LESS;
  6764. },
  6765. enumerable: true,
  6766. configurable: true
  6767. });
  6768. Object.defineProperty(Engine, "EQUAL", {
  6769. get: function () {
  6770. return Engine._EQUAL;
  6771. },
  6772. enumerable: true,
  6773. configurable: true
  6774. });
  6775. Object.defineProperty(Engine, "LEQUAL", {
  6776. get: function () {
  6777. return Engine._LEQUAL;
  6778. },
  6779. enumerable: true,
  6780. configurable: true
  6781. });
  6782. Object.defineProperty(Engine, "GREATER", {
  6783. get: function () {
  6784. return Engine._GREATER;
  6785. },
  6786. enumerable: true,
  6787. configurable: true
  6788. });
  6789. Object.defineProperty(Engine, "GEQUAL", {
  6790. get: function () {
  6791. return Engine._GEQUAL;
  6792. },
  6793. enumerable: true,
  6794. configurable: true
  6795. });
  6796. Object.defineProperty(Engine, "NOTEQUAL", {
  6797. get: function () {
  6798. return Engine._NOTEQUAL;
  6799. },
  6800. enumerable: true,
  6801. configurable: true
  6802. });
  6803. Object.defineProperty(Engine, "KEEP", {
  6804. get: function () {
  6805. return Engine._KEEP;
  6806. },
  6807. enumerable: true,
  6808. configurable: true
  6809. });
  6810. Object.defineProperty(Engine, "REPLACE", {
  6811. get: function () {
  6812. return Engine._REPLACE;
  6813. },
  6814. enumerable: true,
  6815. configurable: true
  6816. });
  6817. Object.defineProperty(Engine, "INCR", {
  6818. get: function () {
  6819. return Engine._INCR;
  6820. },
  6821. enumerable: true,
  6822. configurable: true
  6823. });
  6824. Object.defineProperty(Engine, "DECR", {
  6825. get: function () {
  6826. return Engine._DECR;
  6827. },
  6828. enumerable: true,
  6829. configurable: true
  6830. });
  6831. Object.defineProperty(Engine, "INVERT", {
  6832. get: function () {
  6833. return Engine._INVERT;
  6834. },
  6835. enumerable: true,
  6836. configurable: true
  6837. });
  6838. Object.defineProperty(Engine, "INCR_WRAP", {
  6839. get: function () {
  6840. return Engine._INCR_WRAP;
  6841. },
  6842. enumerable: true,
  6843. configurable: true
  6844. });
  6845. Object.defineProperty(Engine, "DECR_WRAP", {
  6846. get: function () {
  6847. return Engine._DECR_WRAP;
  6848. },
  6849. enumerable: true,
  6850. configurable: true
  6851. });
  6852. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6853. get: function () {
  6854. return Engine._ALPHA_DISABLE;
  6855. },
  6856. enumerable: true,
  6857. configurable: true
  6858. });
  6859. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6860. get: function () {
  6861. return Engine._ALPHA_ONEONE;
  6862. },
  6863. enumerable: true,
  6864. configurable: true
  6865. });
  6866. Object.defineProperty(Engine, "ALPHA_ADD", {
  6867. get: function () {
  6868. return Engine._ALPHA_ADD;
  6869. },
  6870. enumerable: true,
  6871. configurable: true
  6872. });
  6873. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6874. get: function () {
  6875. return Engine._ALPHA_COMBINE;
  6876. },
  6877. enumerable: true,
  6878. configurable: true
  6879. });
  6880. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6881. get: function () {
  6882. return Engine._ALPHA_SUBTRACT;
  6883. },
  6884. enumerable: true,
  6885. configurable: true
  6886. });
  6887. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6888. get: function () {
  6889. return Engine._ALPHA_MULTIPLY;
  6890. },
  6891. enumerable: true,
  6892. configurable: true
  6893. });
  6894. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6895. get: function () {
  6896. return Engine._ALPHA_MAXIMIZED;
  6897. },
  6898. enumerable: true,
  6899. configurable: true
  6900. });
  6901. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  6902. get: function () {
  6903. return Engine._ALPHA_PREMULTIPLIED;
  6904. },
  6905. enumerable: true,
  6906. configurable: true
  6907. });
  6908. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6909. get: function () {
  6910. return Engine._DELAYLOADSTATE_NONE;
  6911. },
  6912. enumerable: true,
  6913. configurable: true
  6914. });
  6915. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6916. get: function () {
  6917. return Engine._DELAYLOADSTATE_LOADED;
  6918. },
  6919. enumerable: true,
  6920. configurable: true
  6921. });
  6922. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6923. get: function () {
  6924. return Engine._DELAYLOADSTATE_LOADING;
  6925. },
  6926. enumerable: true,
  6927. configurable: true
  6928. });
  6929. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6930. get: function () {
  6931. return Engine._DELAYLOADSTATE_NOTLOADED;
  6932. },
  6933. enumerable: true,
  6934. configurable: true
  6935. });
  6936. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6937. get: function () {
  6938. return Engine._TEXTUREFORMAT_ALPHA;
  6939. },
  6940. enumerable: true,
  6941. configurable: true
  6942. });
  6943. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6944. get: function () {
  6945. return Engine._TEXTUREFORMAT_LUMINANCE;
  6946. },
  6947. enumerable: true,
  6948. configurable: true
  6949. });
  6950. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6951. get: function () {
  6952. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6953. },
  6954. enumerable: true,
  6955. configurable: true
  6956. });
  6957. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6958. get: function () {
  6959. return Engine._TEXTUREFORMAT_RGB;
  6960. },
  6961. enumerable: true,
  6962. configurable: true
  6963. });
  6964. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6965. get: function () {
  6966. return Engine._TEXTUREFORMAT_RGBA;
  6967. },
  6968. enumerable: true,
  6969. configurable: true
  6970. });
  6971. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6972. get: function () {
  6973. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6974. },
  6975. enumerable: true,
  6976. configurable: true
  6977. });
  6978. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6979. get: function () {
  6980. return Engine._TEXTURETYPE_FLOAT;
  6981. },
  6982. enumerable: true,
  6983. configurable: true
  6984. });
  6985. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6986. get: function () {
  6987. return Engine._TEXTURETYPE_HALF_FLOAT;
  6988. },
  6989. enumerable: true,
  6990. configurable: true
  6991. });
  6992. Object.defineProperty(Engine, "Version", {
  6993. get: function () {
  6994. return "2.6-alpha";
  6995. },
  6996. enumerable: true,
  6997. configurable: true
  6998. });
  6999. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7000. get: function () {
  7001. return this._texturesSupported;
  7002. },
  7003. enumerable: true,
  7004. configurable: true
  7005. });
  7006. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7007. get: function () {
  7008. return this._textureFormatInUse;
  7009. },
  7010. enumerable: true,
  7011. configurable: true
  7012. });
  7013. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7014. get: function () {
  7015. return this._webGLVersion;
  7016. },
  7017. enumerable: true,
  7018. configurable: true
  7019. });
  7020. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7021. /**
  7022. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7023. */
  7024. get: function () {
  7025. return this._isStencilEnable;
  7026. },
  7027. enumerable: true,
  7028. configurable: true
  7029. });
  7030. Engine.prototype._prepareWorkingCanvas = function () {
  7031. if (this._workingCanvas) {
  7032. return;
  7033. }
  7034. this._workingCanvas = document.createElement("canvas");
  7035. this._workingContext = this._workingCanvas.getContext("2d");
  7036. };
  7037. Engine.prototype.resetTextureCache = function () {
  7038. for (var index = 0; index < this._maxTextureChannels; index++) {
  7039. this._activeTexturesCache[index] = null;
  7040. }
  7041. };
  7042. Engine.prototype.getGlInfo = function () {
  7043. return {
  7044. vendor: this._glVendor,
  7045. renderer: this._glRenderer,
  7046. version: this._glVersion
  7047. };
  7048. };
  7049. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7050. if (useScreen === void 0) { useScreen = false; }
  7051. var viewport = camera.viewport;
  7052. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7053. };
  7054. Engine.prototype.getRenderWidth = function (useScreen) {
  7055. if (useScreen === void 0) { useScreen = false; }
  7056. if (!useScreen && this._currentRenderTarget) {
  7057. return this._currentRenderTarget._width;
  7058. }
  7059. return this._renderingCanvas.width;
  7060. };
  7061. Engine.prototype.getRenderHeight = function (useScreen) {
  7062. if (useScreen === void 0) { useScreen = false; }
  7063. if (!useScreen && this._currentRenderTarget) {
  7064. return this._currentRenderTarget._height;
  7065. }
  7066. return this._renderingCanvas.height;
  7067. };
  7068. Engine.prototype.getRenderingCanvas = function () {
  7069. return this._renderingCanvas;
  7070. };
  7071. Engine.prototype.getRenderingCanvasClientRect = function () {
  7072. return this._renderingCanvas.getBoundingClientRect();
  7073. };
  7074. Engine.prototype.setHardwareScalingLevel = function (level) {
  7075. this._hardwareScalingLevel = level;
  7076. this.resize();
  7077. };
  7078. Engine.prototype.getHardwareScalingLevel = function () {
  7079. return this._hardwareScalingLevel;
  7080. };
  7081. Engine.prototype.getLoadedTexturesCache = function () {
  7082. return this._loadedTexturesCache;
  7083. };
  7084. Engine.prototype.getCaps = function () {
  7085. return this._caps;
  7086. };
  7087. Object.defineProperty(Engine.prototype, "drawCalls", {
  7088. get: function () {
  7089. return this._drawCalls.current;
  7090. },
  7091. enumerable: true,
  7092. configurable: true
  7093. });
  7094. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7095. get: function () {
  7096. return this._drawCalls;
  7097. },
  7098. enumerable: true,
  7099. configurable: true
  7100. });
  7101. Engine.prototype.getDepthFunction = function () {
  7102. return this._depthCullingState.depthFunc;
  7103. };
  7104. Engine.prototype.setDepthFunction = function (depthFunc) {
  7105. this._depthCullingState.depthFunc = depthFunc;
  7106. };
  7107. Engine.prototype.setDepthFunctionToGreater = function () {
  7108. this._depthCullingState.depthFunc = this._gl.GREATER;
  7109. };
  7110. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7111. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7112. };
  7113. Engine.prototype.setDepthFunctionToLess = function () {
  7114. this._depthCullingState.depthFunc = this._gl.LESS;
  7115. };
  7116. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7117. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7118. };
  7119. Engine.prototype.getStencilBuffer = function () {
  7120. return this._stencilState.stencilTest;
  7121. };
  7122. Engine.prototype.setStencilBuffer = function (enable) {
  7123. this._stencilState.stencilTest = enable;
  7124. };
  7125. Engine.prototype.getStencilMask = function () {
  7126. return this._stencilState.stencilMask;
  7127. };
  7128. Engine.prototype.setStencilMask = function (mask) {
  7129. this._stencilState.stencilMask = mask;
  7130. };
  7131. Engine.prototype.getStencilFunction = function () {
  7132. return this._stencilState.stencilFunc;
  7133. };
  7134. Engine.prototype.getStencilFunctionReference = function () {
  7135. return this._stencilState.stencilFuncRef;
  7136. };
  7137. Engine.prototype.getStencilFunctionMask = function () {
  7138. return this._stencilState.stencilFuncMask;
  7139. };
  7140. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7141. this._stencilState.stencilFunc = stencilFunc;
  7142. };
  7143. Engine.prototype.setStencilFunctionReference = function (reference) {
  7144. this._stencilState.stencilFuncRef = reference;
  7145. };
  7146. Engine.prototype.setStencilFunctionMask = function (mask) {
  7147. this._stencilState.stencilFuncMask = mask;
  7148. };
  7149. Engine.prototype.getStencilOperationFail = function () {
  7150. return this._stencilState.stencilOpStencilFail;
  7151. };
  7152. Engine.prototype.getStencilOperationDepthFail = function () {
  7153. return this._stencilState.stencilOpDepthFail;
  7154. };
  7155. Engine.prototype.getStencilOperationPass = function () {
  7156. return this._stencilState.stencilOpStencilDepthPass;
  7157. };
  7158. Engine.prototype.setStencilOperationFail = function (operation) {
  7159. this._stencilState.stencilOpStencilFail = operation;
  7160. };
  7161. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7162. this._stencilState.stencilOpDepthFail = operation;
  7163. };
  7164. Engine.prototype.setStencilOperationPass = function (operation) {
  7165. this._stencilState.stencilOpStencilDepthPass = operation;
  7166. };
  7167. /**
  7168. * stop executing a render loop function and remove it from the execution array
  7169. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7170. */
  7171. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7172. if (!renderFunction) {
  7173. this._activeRenderLoops = [];
  7174. return;
  7175. }
  7176. var index = this._activeRenderLoops.indexOf(renderFunction);
  7177. if (index >= 0) {
  7178. this._activeRenderLoops.splice(index, 1);
  7179. }
  7180. };
  7181. Engine.prototype._renderLoop = function () {
  7182. var shouldRender = true;
  7183. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7184. shouldRender = false;
  7185. }
  7186. if (shouldRender) {
  7187. // Start new frame
  7188. this.beginFrame();
  7189. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7190. var renderFunction = this._activeRenderLoops[index];
  7191. renderFunction();
  7192. }
  7193. // Present
  7194. this.endFrame();
  7195. }
  7196. if (this._activeRenderLoops.length > 0) {
  7197. // Register new frame
  7198. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7199. }
  7200. else {
  7201. this._renderingQueueLaunched = false;
  7202. }
  7203. };
  7204. /**
  7205. * Register and execute a render loop. The engine can have more than one render function.
  7206. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7207. * @example
  7208. * engine.runRenderLoop(function () {
  7209. * scene.render()
  7210. * })
  7211. */
  7212. Engine.prototype.runRenderLoop = function (renderFunction) {
  7213. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7214. return;
  7215. }
  7216. this._activeRenderLoops.push(renderFunction);
  7217. if (!this._renderingQueueLaunched) {
  7218. this._renderingQueueLaunched = true;
  7219. this._bindedRenderFunction = this._renderLoop.bind(this);
  7220. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7221. }
  7222. };
  7223. /**
  7224. * Toggle full screen mode.
  7225. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7226. * @param {any} options - an options object to be sent to the requestFullscreen function
  7227. */
  7228. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7229. if (this.isFullscreen) {
  7230. BABYLON.Tools.ExitFullscreen();
  7231. }
  7232. else {
  7233. this._pointerLockRequested = requestPointerLock;
  7234. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7235. }
  7236. };
  7237. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7238. if (stencil === void 0) { stencil = false; }
  7239. this.applyStates();
  7240. var mode = 0;
  7241. if (backBuffer && color) {
  7242. this._gl.clearColor(color.r, color.g, color.b, color.a);
  7243. mode |= this._gl.COLOR_BUFFER_BIT;
  7244. }
  7245. if (depth) {
  7246. this._gl.clearDepth(1.0);
  7247. mode |= this._gl.DEPTH_BUFFER_BIT;
  7248. }
  7249. if (stencil) {
  7250. this._gl.clearStencil(0);
  7251. mode |= this._gl.STENCIL_BUFFER_BIT;
  7252. }
  7253. this._gl.clear(mode);
  7254. };
  7255. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7256. var gl = this._gl;
  7257. // Save state
  7258. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7259. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7260. // Change state
  7261. gl.enable(gl.SCISSOR_TEST);
  7262. gl.scissor(x, y, width, height);
  7263. // Clear
  7264. this.clear(clearColor, true, true, true);
  7265. // Restore state
  7266. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7267. if (curScissor === true) {
  7268. gl.enable(gl.SCISSOR_TEST);
  7269. }
  7270. else {
  7271. gl.disable(gl.SCISSOR_TEST);
  7272. }
  7273. };
  7274. /**
  7275. * Set the WebGL's viewport
  7276. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7277. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7278. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7279. */
  7280. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7281. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  7282. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  7283. var x = viewport.x || 0;
  7284. var y = viewport.y || 0;
  7285. this._cachedViewport = viewport;
  7286. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7287. };
  7288. /**
  7289. * Directly set the WebGL Viewport
  7290. * The x, y, width & height are directly passed to the WebGL call
  7291. * @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.
  7292. */
  7293. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7294. var currentViewport = this._cachedViewport;
  7295. this._cachedViewport = null;
  7296. this._gl.viewport(x, y, width, height);
  7297. return currentViewport;
  7298. };
  7299. Engine.prototype.beginFrame = function () {
  7300. this._measureFps();
  7301. };
  7302. Engine.prototype.endFrame = function () {
  7303. //force a flush in case we are using a bad OS.
  7304. if (this._badOS) {
  7305. this.flushFramebuffer();
  7306. }
  7307. //submit frame to the vr device, if enabled
  7308. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7309. this._vrDisplayEnabled.submitFrame();
  7310. }
  7311. };
  7312. /**
  7313. * resize the view according to the canvas' size.
  7314. * @example
  7315. * window.addEventListener("resize", function () {
  7316. * engine.resize();
  7317. * });
  7318. */
  7319. Engine.prototype.resize = function () {
  7320. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7321. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7322. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7323. };
  7324. /**
  7325. * force a specific size of the canvas
  7326. * @param {number} width - the new canvas' width
  7327. * @param {number} height - the new canvas' height
  7328. */
  7329. Engine.prototype.setSize = function (width, height) {
  7330. this._renderingCanvas.width = width;
  7331. this._renderingCanvas.height = height;
  7332. for (var index = 0; index < this.scenes.length; index++) {
  7333. var scene = this.scenes[index];
  7334. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7335. var cam = scene.cameras[camIndex];
  7336. cam._currentRenderId = 0;
  7337. }
  7338. }
  7339. };
  7340. //WebVR functions
  7341. Engine.prototype.initWebVR = function () {
  7342. if (!this.vrDisplaysPromise) {
  7343. this._getVRDisplays();
  7344. }
  7345. };
  7346. Engine.prototype.enableVR = function (vrDevice) {
  7347. this._vrDisplayEnabled = vrDevice;
  7348. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7349. };
  7350. Engine.prototype.disableVR = function () {
  7351. if (this._vrDisplayEnabled) {
  7352. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7353. }
  7354. };
  7355. Engine.prototype._getVRDisplays = function () {
  7356. var _this = this;
  7357. var getWebVRDevices = function (devices) {
  7358. var size = devices.length;
  7359. var i = 0;
  7360. _this._vrDisplays = devices.filter(function (device) {
  7361. return devices[i] instanceof VRDisplay;
  7362. });
  7363. return _this._vrDisplays;
  7364. };
  7365. //using a key due to typescript
  7366. if (navigator.getVRDisplays) {
  7367. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7368. }
  7369. };
  7370. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7371. this._currentRenderTarget = texture;
  7372. this.bindUnboundFramebuffer(texture._framebuffer);
  7373. var gl = this._gl;
  7374. if (texture.isCube) {
  7375. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7376. }
  7377. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7378. this.wipeCaches();
  7379. };
  7380. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7381. if (this._currentFramebuffer !== framebuffer) {
  7382. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7383. this._currentFramebuffer = framebuffer;
  7384. }
  7385. };
  7386. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  7387. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7388. this._currentRenderTarget = null;
  7389. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7390. var gl = this._gl;
  7391. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7392. gl.generateMipmap(gl.TEXTURE_2D);
  7393. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7394. }
  7395. this.bindUnboundFramebuffer(null);
  7396. };
  7397. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7398. if (texture.generateMipMaps) {
  7399. var gl = this._gl;
  7400. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7401. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7402. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7403. }
  7404. };
  7405. Engine.prototype.flushFramebuffer = function () {
  7406. this._gl.flush();
  7407. };
  7408. Engine.prototype.restoreDefaultFramebuffer = function () {
  7409. this._currentRenderTarget = null;
  7410. this.bindUnboundFramebuffer(null);
  7411. this.setViewport(this._cachedViewport);
  7412. this.wipeCaches();
  7413. };
  7414. // VBOs
  7415. Engine.prototype._resetVertexBufferBinding = function () {
  7416. this.bindArrayBuffer(null);
  7417. this._cachedVertexBuffers = null;
  7418. };
  7419. Engine.prototype.createVertexBuffer = function (vertices) {
  7420. var vbo = this._gl.createBuffer();
  7421. this.bindArrayBuffer(vbo);
  7422. if (vertices instanceof Float32Array) {
  7423. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  7424. }
  7425. else {
  7426. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  7427. }
  7428. this._resetVertexBufferBinding();
  7429. vbo.references = 1;
  7430. return vbo;
  7431. };
  7432. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  7433. var vbo = this._gl.createBuffer();
  7434. this.bindArrayBuffer(vbo);
  7435. if (vertices instanceof Float32Array) {
  7436. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  7437. }
  7438. else {
  7439. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  7440. }
  7441. this._resetVertexBufferBinding();
  7442. vbo.references = 1;
  7443. return vbo;
  7444. };
  7445. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  7446. this.bindArrayBuffer(vertexBuffer);
  7447. if (offset === undefined) {
  7448. offset = 0;
  7449. }
  7450. if (count === undefined) {
  7451. if (vertices instanceof Float32Array) {
  7452. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  7453. }
  7454. else {
  7455. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  7456. }
  7457. }
  7458. else {
  7459. if (vertices instanceof Float32Array) {
  7460. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  7461. }
  7462. else {
  7463. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  7464. }
  7465. }
  7466. this._resetVertexBufferBinding();
  7467. };
  7468. Engine.prototype._resetIndexBufferBinding = function () {
  7469. this.bindIndexBuffer(null);
  7470. this._cachedIndexBuffer = null;
  7471. };
  7472. Engine.prototype.createIndexBuffer = function (indices) {
  7473. var vbo = this._gl.createBuffer();
  7474. this.bindIndexBuffer(vbo);
  7475. // Check for 32 bits indices
  7476. var arrayBuffer;
  7477. var need32Bits = false;
  7478. if (this._caps.uintIndices) {
  7479. for (var index = 0; index < indices.length; index++) {
  7480. if (indices[index] > 65535) {
  7481. need32Bits = true;
  7482. break;
  7483. }
  7484. }
  7485. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  7486. }
  7487. else {
  7488. arrayBuffer = new Uint16Array(indices);
  7489. }
  7490. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  7491. this._resetIndexBufferBinding();
  7492. vbo.references = 1;
  7493. vbo.is32Bits = need32Bits;
  7494. return vbo;
  7495. };
  7496. Engine.prototype.bindArrayBuffer = function (buffer) {
  7497. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  7498. };
  7499. Engine.prototype.bindIndexBuffer = function (buffer) {
  7500. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  7501. };
  7502. Engine.prototype.bindBuffer = function (buffer, target) {
  7503. if (this._currentBoundBuffer[target] !== buffer) {
  7504. this._gl.bindBuffer(target, buffer);
  7505. this._currentBoundBuffer[target] = buffer;
  7506. }
  7507. };
  7508. Engine.prototype.updateArrayBuffer = function (data) {
  7509. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7510. };
  7511. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  7512. var pointer = this._currentBufferPointers[indx];
  7513. var changed = false;
  7514. if (!pointer) {
  7515. changed = true;
  7516. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  7517. }
  7518. else {
  7519. if (pointer.buffer !== buffer) {
  7520. pointer.buffer = buffer;
  7521. changed = true;
  7522. }
  7523. if (pointer.size !== size) {
  7524. pointer.size = size;
  7525. changed = true;
  7526. }
  7527. if (pointer.type !== type) {
  7528. pointer.type = type;
  7529. changed = true;
  7530. }
  7531. if (pointer.normalized !== normalized) {
  7532. pointer.normalized = normalized;
  7533. changed = true;
  7534. }
  7535. if (pointer.stride !== stride) {
  7536. pointer.stride = stride;
  7537. changed = true;
  7538. }
  7539. if (pointer.offset !== offset) {
  7540. pointer.offset = offset;
  7541. changed = true;
  7542. }
  7543. }
  7544. if (changed) {
  7545. this.bindArrayBuffer(buffer);
  7546. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  7547. }
  7548. };
  7549. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  7550. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  7551. this._cachedVertexBuffers = vertexBuffer;
  7552. this._cachedEffectForVertexBuffers = effect;
  7553. var attributesCount = effect.getAttributesCount();
  7554. this.unbindAllAttributes();
  7555. var offset = 0;
  7556. for (var index = 0; index < attributesCount; index++) {
  7557. if (index < vertexDeclaration.length) {
  7558. var order = effect.getAttributeLocation(index);
  7559. if (order >= 0) {
  7560. this._gl.enableVertexAttribArray(order);
  7561. this._vertexAttribArraysEnabled[order] = true;
  7562. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7563. }
  7564. offset += vertexDeclaration[index] * 4;
  7565. }
  7566. }
  7567. }
  7568. if (this._cachedIndexBuffer !== indexBuffer) {
  7569. this._cachedIndexBuffer = indexBuffer;
  7570. this.bindIndexBuffer(indexBuffer);
  7571. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7572. }
  7573. };
  7574. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7575. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7576. this._cachedVertexBuffers = vertexBuffers;
  7577. this._cachedEffectForVertexBuffers = effect;
  7578. var attributes = effect.getAttributesNames();
  7579. this.unbindAllAttributes();
  7580. for (var index = 0; index < attributes.length; index++) {
  7581. var order = effect.getAttributeLocation(index);
  7582. if (order >= 0) {
  7583. var vertexBuffer = vertexBuffers[attributes[index]];
  7584. if (!vertexBuffer) {
  7585. continue;
  7586. }
  7587. this._gl.enableVertexAttribArray(order);
  7588. this._vertexAttribArraysEnabled[order] = true;
  7589. var buffer = vertexBuffer.getBuffer();
  7590. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7591. if (vertexBuffer.getIsInstanced()) {
  7592. this._gl.vertexAttribDivisor(order, 1);
  7593. this._currentInstanceLocations.push(order);
  7594. this._currentInstanceBuffers.push(buffer);
  7595. }
  7596. }
  7597. }
  7598. }
  7599. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  7600. this._cachedIndexBuffer = indexBuffer;
  7601. this.bindIndexBuffer(indexBuffer);
  7602. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7603. }
  7604. };
  7605. Engine.prototype.unbindInstanceAttributes = function () {
  7606. var boundBuffer;
  7607. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7608. var instancesBuffer = this._currentInstanceBuffers[i];
  7609. if (boundBuffer != instancesBuffer) {
  7610. boundBuffer = instancesBuffer;
  7611. this.bindArrayBuffer(instancesBuffer);
  7612. }
  7613. var offsetLocation = this._currentInstanceLocations[i];
  7614. this._gl.vertexAttribDivisor(offsetLocation, 0);
  7615. }
  7616. this._currentInstanceBuffers.length = 0;
  7617. this._currentInstanceLocations.length = 0;
  7618. };
  7619. Engine.prototype._releaseBuffer = function (buffer) {
  7620. buffer.references--;
  7621. if (buffer.references === 0) {
  7622. this._gl.deleteBuffer(buffer);
  7623. return true;
  7624. }
  7625. return false;
  7626. };
  7627. Engine.prototype.createInstancesBuffer = function (capacity) {
  7628. var buffer = this._gl.createBuffer();
  7629. buffer.capacity = capacity;
  7630. this.bindArrayBuffer(buffer);
  7631. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7632. return buffer;
  7633. };
  7634. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7635. this._gl.deleteBuffer(buffer);
  7636. };
  7637. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7638. this.bindArrayBuffer(instancesBuffer);
  7639. if (data) {
  7640. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7641. }
  7642. if (offsetLocations[0].index !== undefined) {
  7643. var stride = 0;
  7644. for (var i = 0; i < offsetLocations.length; i++) {
  7645. var ai = offsetLocations[i];
  7646. stride += ai.attributeSize * 4;
  7647. }
  7648. for (var i = 0; i < offsetLocations.length; i++) {
  7649. var ai = offsetLocations[i];
  7650. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7651. this._gl.enableVertexAttribArray(ai.index);
  7652. this._vertexAttribArraysEnabled[ai.index] = true;
  7653. }
  7654. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7655. this._gl.vertexAttribDivisor(ai.index, 1);
  7656. this._currentInstanceLocations.push(ai.index);
  7657. this._currentInstanceBuffers.push(instancesBuffer);
  7658. }
  7659. }
  7660. else {
  7661. for (var index = 0; index < 4; index++) {
  7662. var offsetLocation = offsetLocations[index];
  7663. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7664. this._gl.enableVertexAttribArray(offsetLocation);
  7665. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7666. }
  7667. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7668. this._gl.vertexAttribDivisor(offsetLocation, 1);
  7669. this._currentInstanceLocations.push(offsetLocation);
  7670. this._currentInstanceBuffers.push(instancesBuffer);
  7671. }
  7672. }
  7673. };
  7674. Engine.prototype.applyStates = function () {
  7675. this._depthCullingState.apply(this._gl);
  7676. this._stencilState.apply(this._gl);
  7677. this._alphaState.apply(this._gl);
  7678. };
  7679. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7680. // Apply states
  7681. this.applyStates();
  7682. this._drawCalls.addCount(1, false);
  7683. // Render
  7684. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7685. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7686. if (instancesCount) {
  7687. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7688. return;
  7689. }
  7690. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7691. };
  7692. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7693. // Apply states
  7694. this.applyStates();
  7695. this._drawCalls.addCount(1, false);
  7696. if (instancesCount) {
  7697. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7698. return;
  7699. }
  7700. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7701. };
  7702. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7703. // Apply states
  7704. this.applyStates();
  7705. this._drawCalls.addCount(1, false);
  7706. if (instancesCount) {
  7707. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7708. return;
  7709. }
  7710. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7711. };
  7712. // Shaders
  7713. Engine.prototype._releaseEffect = function (effect) {
  7714. if (this._compiledEffects[effect._key]) {
  7715. delete this._compiledEffects[effect._key];
  7716. if (effect.getProgram()) {
  7717. this._gl.deleteProgram(effect.getProgram());
  7718. }
  7719. }
  7720. };
  7721. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7722. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7723. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7724. var name = vertex + "+" + fragment + "@" + defines;
  7725. if (this._compiledEffects[name]) {
  7726. return this._compiledEffects[name];
  7727. }
  7728. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7729. effect._key = name;
  7730. this._compiledEffects[name] = effect;
  7731. return effect;
  7732. };
  7733. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7734. if (uniformsNames === void 0) { uniformsNames = []; }
  7735. if (samplers === void 0) { samplers = []; }
  7736. if (defines === void 0) { defines = ""; }
  7737. return this.createEffect({
  7738. vertex: "particles",
  7739. fragmentElement: fragmentName
  7740. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7741. };
  7742. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7743. context = context || this._gl;
  7744. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  7745. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  7746. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  7747. var shaderProgram = context.createProgram();
  7748. context.attachShader(shaderProgram, vertexShader);
  7749. context.attachShader(shaderProgram, fragmentShader);
  7750. context.linkProgram(shaderProgram);
  7751. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7752. if (!linked) {
  7753. var error = context.getProgramInfoLog(shaderProgram);
  7754. if (error) {
  7755. throw new Error(error);
  7756. }
  7757. }
  7758. context.deleteShader(vertexShader);
  7759. context.deleteShader(fragmentShader);
  7760. return shaderProgram;
  7761. };
  7762. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7763. var results = [];
  7764. for (var index = 0; index < uniformsNames.length; index++) {
  7765. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7766. }
  7767. return results;
  7768. };
  7769. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7770. var results = [];
  7771. for (var index = 0; index < attributesNames.length; index++) {
  7772. try {
  7773. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7774. }
  7775. catch (e) {
  7776. results.push(-1);
  7777. }
  7778. }
  7779. return results;
  7780. };
  7781. Engine.prototype.enableEffect = function (effect) {
  7782. //if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  7783. // if (effect && effect.onBind) {
  7784. // effect.onBind(effect);
  7785. // }
  7786. // return;
  7787. //}
  7788. // Use program
  7789. this.setProgram(effect.getProgram());
  7790. this._currentEffect = effect;
  7791. if (effect.onBind) {
  7792. effect.onBind(effect);
  7793. }
  7794. };
  7795. Engine.prototype.setIntArray = function (uniform, array) {
  7796. if (!uniform)
  7797. return;
  7798. this._gl.uniform1iv(uniform, array);
  7799. };
  7800. Engine.prototype.setIntArray2 = function (uniform, array) {
  7801. if (!uniform || array.length % 2 !== 0)
  7802. return;
  7803. this._gl.uniform2iv(uniform, array);
  7804. };
  7805. Engine.prototype.setIntArray3 = function (uniform, array) {
  7806. if (!uniform || array.length % 3 !== 0)
  7807. return;
  7808. this._gl.uniform3iv(uniform, array);
  7809. };
  7810. Engine.prototype.setIntArray4 = function (uniform, array) {
  7811. if (!uniform || array.length % 4 !== 0)
  7812. return;
  7813. this._gl.uniform4iv(uniform, array);
  7814. };
  7815. Engine.prototype.setFloatArray = function (uniform, array) {
  7816. if (!uniform)
  7817. return;
  7818. this._gl.uniform1fv(uniform, array);
  7819. };
  7820. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7821. if (!uniform || array.length % 2 !== 0)
  7822. return;
  7823. this._gl.uniform2fv(uniform, array);
  7824. };
  7825. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7826. if (!uniform || array.length % 3 !== 0)
  7827. return;
  7828. this._gl.uniform3fv(uniform, array);
  7829. };
  7830. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7831. if (!uniform || array.length % 4 !== 0)
  7832. return;
  7833. this._gl.uniform4fv(uniform, array);
  7834. };
  7835. Engine.prototype.setArray = function (uniform, array) {
  7836. if (!uniform)
  7837. return;
  7838. this._gl.uniform1fv(uniform, array);
  7839. };
  7840. Engine.prototype.setArray2 = function (uniform, array) {
  7841. if (!uniform || array.length % 2 !== 0)
  7842. return;
  7843. this._gl.uniform2fv(uniform, array);
  7844. };
  7845. Engine.prototype.setArray3 = function (uniform, array) {
  7846. if (!uniform || array.length % 3 !== 0)
  7847. return;
  7848. this._gl.uniform3fv(uniform, array);
  7849. };
  7850. Engine.prototype.setArray4 = function (uniform, array) {
  7851. if (!uniform || array.length % 4 !== 0)
  7852. return;
  7853. this._gl.uniform4fv(uniform, array);
  7854. };
  7855. Engine.prototype.setMatrices = function (uniform, matrices) {
  7856. if (!uniform)
  7857. return;
  7858. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7859. };
  7860. Engine.prototype.setMatrix = function (uniform, matrix) {
  7861. if (!uniform)
  7862. return;
  7863. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7864. };
  7865. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7866. if (!uniform)
  7867. return;
  7868. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7869. };
  7870. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7871. if (!uniform)
  7872. return;
  7873. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7874. };
  7875. Engine.prototype.setFloat = function (uniform, value) {
  7876. if (!uniform)
  7877. return;
  7878. this._gl.uniform1f(uniform, value);
  7879. };
  7880. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7881. if (!uniform)
  7882. return;
  7883. this._gl.uniform2f(uniform, x, y);
  7884. };
  7885. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7886. if (!uniform)
  7887. return;
  7888. this._gl.uniform3f(uniform, x, y, z);
  7889. };
  7890. Engine.prototype.setBool = function (uniform, bool) {
  7891. if (!uniform)
  7892. return;
  7893. this._gl.uniform1i(uniform, bool);
  7894. };
  7895. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7896. if (!uniform)
  7897. return;
  7898. this._gl.uniform4f(uniform, x, y, z, w);
  7899. };
  7900. Engine.prototype.setColor3 = function (uniform, color3) {
  7901. if (!uniform)
  7902. return;
  7903. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7904. };
  7905. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7906. if (!uniform)
  7907. return;
  7908. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7909. };
  7910. // States
  7911. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7912. if (zOffset === void 0) { zOffset = 0; }
  7913. if (reverseSide === void 0) { reverseSide = false; }
  7914. // Culling
  7915. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7916. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7917. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7918. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7919. if (culling) {
  7920. this._depthCullingState.cullFace = cullFace;
  7921. this._depthCullingState.cull = true;
  7922. }
  7923. else {
  7924. this._depthCullingState.cull = false;
  7925. }
  7926. }
  7927. // Z offset
  7928. this._depthCullingState.zOffset = zOffset;
  7929. };
  7930. Engine.prototype.setDepthBuffer = function (enable) {
  7931. this._depthCullingState.depthTest = enable;
  7932. };
  7933. Engine.prototype.getDepthWrite = function () {
  7934. return this._depthCullingState.depthMask;
  7935. };
  7936. Engine.prototype.setDepthWrite = function (enable) {
  7937. this._depthCullingState.depthMask = enable;
  7938. };
  7939. Engine.prototype.setColorWrite = function (enable) {
  7940. this._gl.colorMask(enable, enable, enable, enable);
  7941. };
  7942. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7943. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7944. if (this._alphaMode === mode) {
  7945. return;
  7946. }
  7947. switch (mode) {
  7948. case Engine.ALPHA_DISABLE:
  7949. this._alphaState.alphaBlend = false;
  7950. break;
  7951. case Engine.ALPHA_PREMULTIPLIED:
  7952. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  7953. this._alphaState.alphaBlend = true;
  7954. break;
  7955. case Engine.ALPHA_COMBINE:
  7956. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7957. this._alphaState.alphaBlend = true;
  7958. break;
  7959. case Engine.ALPHA_ONEONE:
  7960. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7961. this._alphaState.alphaBlend = true;
  7962. break;
  7963. case Engine.ALPHA_ADD:
  7964. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7965. this._alphaState.alphaBlend = true;
  7966. break;
  7967. case Engine.ALPHA_SUBTRACT:
  7968. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7969. this._alphaState.alphaBlend = true;
  7970. break;
  7971. case Engine.ALPHA_MULTIPLY:
  7972. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7973. this._alphaState.alphaBlend = true;
  7974. break;
  7975. case Engine.ALPHA_MAXIMIZED:
  7976. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7977. this._alphaState.alphaBlend = true;
  7978. break;
  7979. }
  7980. if (!noDepthWriteChange) {
  7981. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7982. }
  7983. this._alphaMode = mode;
  7984. };
  7985. Engine.prototype.getAlphaMode = function () {
  7986. return this._alphaMode;
  7987. };
  7988. Engine.prototype.setAlphaTesting = function (enable) {
  7989. this._alphaTest = enable;
  7990. };
  7991. Engine.prototype.getAlphaTesting = function () {
  7992. return this._alphaTest;
  7993. };
  7994. // Textures
  7995. Engine.prototype.wipeCaches = function () {
  7996. this.resetTextureCache();
  7997. this._currentEffect = null;
  7998. this._stencilState.reset();
  7999. this._depthCullingState.reset();
  8000. this.setDepthFunctionToLessOrEqual();
  8001. this._alphaState.reset();
  8002. this._cachedVertexBuffers = null;
  8003. this._cachedIndexBuffer = null;
  8004. this._cachedEffectForVertexBuffers = null;
  8005. };
  8006. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  8007. var gl = this._gl;
  8008. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8009. var magFilter = gl.NEAREST;
  8010. var minFilter = gl.NEAREST;
  8011. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  8012. magFilter = gl.LINEAR;
  8013. minFilter = gl.LINEAR;
  8014. }
  8015. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  8016. magFilter = gl.LINEAR;
  8017. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8018. }
  8019. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  8020. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  8021. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8022. texture.samplingMode = samplingMode;
  8023. };
  8024. /**
  8025. * Set the compressed texture format to use, based on the formats you have, and the formats
  8026. * supported by the hardware / browser.
  8027. *
  8028. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  8029. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  8030. * to API arguments needed to compressed textures. This puts the burden on the container
  8031. * generator to house the arcane code for determining these for current & future formats.
  8032. *
  8033. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  8034. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  8035. *
  8036. * Note: The result of this call is not taken into account when a texture is base64 or when
  8037. * using a database / manifest.
  8038. *
  8039. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  8040. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  8041. *
  8042. * Current families are astc, dxt, pvrtc, etc2, atc, & etc1.
  8043. * @returns The extension selected.
  8044. */
  8045. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  8046. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  8047. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  8048. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  8049. return this._textureFormatInUse = this._texturesSupported[i];
  8050. }
  8051. }
  8052. }
  8053. // actively set format to nothing, to allow this to be called more than once
  8054. // and possibly fail the 2nd time
  8055. return this._textureFormatInUse = null;
  8056. };
  8057. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  8058. var _this = this;
  8059. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  8060. if (onLoad === void 0) { onLoad = null; }
  8061. if (onError === void 0) { onError = null; }
  8062. if (buffer === void 0) { buffer = null; }
  8063. var texture = this._gl.createTexture();
  8064. var extension;
  8065. var isKTX = false;
  8066. var fromData = false;
  8067. if (url.substr(0, 5) === "data:") {
  8068. fromData = true;
  8069. }
  8070. if (!fromData) {
  8071. var lastDot = url.lastIndexOf('.');
  8072. extension = url.substring(lastDot).toLowerCase();
  8073. if (this._textureFormatInUse && !fromData && !scene.database) {
  8074. extension = this._textureFormatInUse;
  8075. url = url.substring(0, lastDot) + this._textureFormatInUse;
  8076. isKTX = true;
  8077. }
  8078. }
  8079. else {
  8080. var oldUrl = url;
  8081. fromData = oldUrl.split(':');
  8082. url = oldUrl;
  8083. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  8084. }
  8085. var isDDS = (extension === ".dds");
  8086. var isTGA = (extension === ".tga");
  8087. scene._addPendingData(texture);
  8088. texture.url = url;
  8089. texture.noMipmap = noMipmap;
  8090. texture.references = 1;
  8091. texture.samplingMode = samplingMode;
  8092. texture.onLoadedCallbacks = [onLoad];
  8093. this._loadedTexturesCache.push(texture);
  8094. var onerror = function () {
  8095. scene._removePendingData(texture);
  8096. if (onError) {
  8097. onError();
  8098. }
  8099. };
  8100. var callback;
  8101. if (isKTX || isTGA || isDDS) {
  8102. if (isKTX) {
  8103. callback = function (data) {
  8104. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  8105. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  8106. ktx.uploadLevels(_this._gl, !noMipmap);
  8107. }, samplingMode);
  8108. };
  8109. }
  8110. else if (isTGA) {
  8111. callback = function (arrayBuffer) {
  8112. var data = new Uint8Array(arrayBuffer);
  8113. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  8114. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  8115. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  8116. }, samplingMode);
  8117. };
  8118. }
  8119. else if (isDDS) {
  8120. callback = function (data) {
  8121. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8122. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  8123. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  8124. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  8125. }, samplingMode);
  8126. };
  8127. }
  8128. if (!(fromData instanceof Array))
  8129. BABYLON.Tools.LoadFile(url, function (data) {
  8130. callback(data);
  8131. }, null, scene.database, true, onerror);
  8132. else
  8133. callback(buffer);
  8134. }
  8135. else {
  8136. var onload = function (img) {
  8137. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  8138. var isPot = (img.width === potWidth && img.height === potHeight);
  8139. if (!isPot) {
  8140. _this._prepareWorkingCanvas();
  8141. _this._workingCanvas.width = potWidth;
  8142. _this._workingCanvas.height = potHeight;
  8143. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8144. _this._workingContext.imageSmoothingEnabled = false;
  8145. _this._workingContext.mozImageSmoothingEnabled = false;
  8146. _this._workingContext.oImageSmoothingEnabled = false;
  8147. _this._workingContext.webkitImageSmoothingEnabled = false;
  8148. _this._workingContext.msImageSmoothingEnabled = false;
  8149. }
  8150. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  8151. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8152. _this._workingContext.imageSmoothingEnabled = true;
  8153. _this._workingContext.mozImageSmoothingEnabled = true;
  8154. _this._workingContext.oImageSmoothingEnabled = true;
  8155. _this._workingContext.webkitImageSmoothingEnabled = true;
  8156. _this._workingContext.msImageSmoothingEnabled = true;
  8157. }
  8158. }
  8159. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  8160. }, samplingMode);
  8161. };
  8162. if (!(fromData instanceof Array))
  8163. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  8164. else
  8165. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  8166. }
  8167. return texture;
  8168. };
  8169. Engine.prototype._getInternalFormat = function (format) {
  8170. var internalFormat = this._gl.RGBA;
  8171. switch (format) {
  8172. case Engine.TEXTUREFORMAT_ALPHA:
  8173. internalFormat = this._gl.ALPHA;
  8174. break;
  8175. case Engine.TEXTUREFORMAT_LUMINANCE:
  8176. internalFormat = this._gl.LUMINANCE;
  8177. break;
  8178. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  8179. internalFormat = this._gl.LUMINANCE_ALPHA;
  8180. break;
  8181. case Engine.TEXTUREFORMAT_RGB:
  8182. internalFormat = this._gl.RGB;
  8183. break;
  8184. case Engine.TEXTUREFORMAT_RGBA:
  8185. internalFormat = this._gl.RGBA;
  8186. break;
  8187. }
  8188. return internalFormat;
  8189. };
  8190. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  8191. if (compression === void 0) { compression = null; }
  8192. var internalFormat = this._getInternalFormat(format);
  8193. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8194. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  8195. if (texture._width % 4 !== 0) {
  8196. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  8197. }
  8198. if (compression) {
  8199. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  8200. }
  8201. else {
  8202. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  8203. }
  8204. if (texture.generateMipMaps) {
  8205. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8206. }
  8207. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8208. this.resetTextureCache();
  8209. texture.isReady = true;
  8210. };
  8211. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  8212. if (compression === void 0) { compression = null; }
  8213. var texture = this._gl.createTexture();
  8214. texture._baseWidth = width;
  8215. texture._baseHeight = height;
  8216. texture._width = width;
  8217. texture._height = height;
  8218. texture.references = 1;
  8219. this.updateRawTexture(texture, data, format, invertY, compression);
  8220. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8221. // Filters
  8222. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  8223. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8224. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8225. if (generateMipMaps) {
  8226. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8227. }
  8228. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8229. texture.samplingMode = samplingMode;
  8230. this._loadedTexturesCache.push(texture);
  8231. return texture;
  8232. };
  8233. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  8234. var texture = this._gl.createTexture();
  8235. texture._baseWidth = width;
  8236. texture._baseHeight = height;
  8237. if (generateMipMaps) {
  8238. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  8239. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  8240. }
  8241. this.resetTextureCache();
  8242. texture._width = width;
  8243. texture._height = height;
  8244. texture.isReady = false;
  8245. texture.generateMipMaps = generateMipMaps;
  8246. texture.references = 1;
  8247. texture.samplingMode = samplingMode;
  8248. this.updateTextureSamplingMode(samplingMode, texture);
  8249. this._loadedTexturesCache.push(texture);
  8250. return texture;
  8251. };
  8252. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  8253. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  8254. if (texture.isCube) {
  8255. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  8256. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8257. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8258. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8259. }
  8260. else {
  8261. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8262. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8263. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8264. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8265. }
  8266. };
  8267. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  8268. if (premulAlpha === void 0) { premulAlpha = false; }
  8269. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8270. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  8271. if (premulAlpha) {
  8272. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  8273. }
  8274. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  8275. if (texture.generateMipMaps) {
  8276. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8277. }
  8278. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8279. if (premulAlpha) {
  8280. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  8281. }
  8282. this.resetTextureCache();
  8283. texture.isReady = true;
  8284. };
  8285. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8286. if (texture._isDisabled) {
  8287. return;
  8288. }
  8289. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8290. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  8291. try {
  8292. // Testing video texture support
  8293. if (this._videoTextureSupported === undefined) {
  8294. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8295. if (this._gl.getError() !== 0) {
  8296. this._videoTextureSupported = false;
  8297. }
  8298. else {
  8299. this._videoTextureSupported = true;
  8300. }
  8301. }
  8302. // Copy video through the current working canvas if video texture is not supported
  8303. if (!this._videoTextureSupported) {
  8304. if (!texture._workingCanvas) {
  8305. texture._workingCanvas = document.createElement("canvas");
  8306. texture._workingContext = texture._workingCanvas.getContext("2d");
  8307. texture._workingCanvas.width = texture._width;
  8308. texture._workingCanvas.height = texture._height;
  8309. }
  8310. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  8311. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  8312. }
  8313. else {
  8314. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8315. }
  8316. if (texture.generateMipMaps) {
  8317. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8318. }
  8319. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8320. this.resetTextureCache();
  8321. texture.isReady = true;
  8322. }
  8323. catch (ex) {
  8324. // Something unexpected
  8325. // Let's disable the texture
  8326. texture._isDisabled = true;
  8327. }
  8328. };
  8329. Engine.prototype.createRenderTargetTexture = function (size, options) {
  8330. // old version had a "generateMipMaps" arg instead of options.
  8331. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  8332. // in the same way, generateDepthBuffer is defaulted to true
  8333. var generateMipMaps = false;
  8334. var generateDepthBuffer = true;
  8335. var generateStencilBuffer = false;
  8336. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8337. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8338. if (options !== undefined) {
  8339. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8340. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8341. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8342. type = options.type === undefined ? type : options.type;
  8343. if (options.samplingMode !== undefined) {
  8344. samplingMode = options.samplingMode;
  8345. }
  8346. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  8347. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  8348. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8349. }
  8350. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  8351. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  8352. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8353. }
  8354. }
  8355. var gl = this._gl;
  8356. var texture = gl.createTexture();
  8357. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8358. var width = size.width || size;
  8359. var height = size.height || size;
  8360. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8361. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  8362. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8363. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  8364. }
  8365. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  8366. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  8367. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8368. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8369. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  8370. var depthStencilBuffer;
  8371. // Create the depth/stencil buffer
  8372. if (generateStencilBuffer) {
  8373. depthStencilBuffer = gl.createRenderbuffer();
  8374. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8375. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  8376. }
  8377. else if (generateDepthBuffer) {
  8378. depthStencilBuffer = gl.createRenderbuffer();
  8379. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8380. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  8381. }
  8382. // Create the framebuffer
  8383. var framebuffer = gl.createFramebuffer();
  8384. this.bindUnboundFramebuffer(framebuffer);
  8385. // Manage attachments
  8386. if (generateStencilBuffer) {
  8387. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8388. }
  8389. else if (generateDepthBuffer) {
  8390. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8391. }
  8392. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  8393. if (generateMipMaps) {
  8394. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8395. }
  8396. // Unbind
  8397. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8398. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8399. this.bindUnboundFramebuffer(null);
  8400. texture._framebuffer = framebuffer;
  8401. if (generateDepthBuffer) {
  8402. texture._depthBuffer = depthStencilBuffer;
  8403. }
  8404. texture._baseWidth = width;
  8405. texture._baseHeight = height;
  8406. texture._width = width;
  8407. texture._height = height;
  8408. texture.isReady = true;
  8409. texture.generateMipMaps = generateMipMaps;
  8410. texture.references = 1;
  8411. texture.samplingMode = samplingMode;
  8412. texture.type = type;
  8413. this.resetTextureCache();
  8414. this._loadedTexturesCache.push(texture);
  8415. return texture;
  8416. };
  8417. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  8418. var gl = this._gl;
  8419. var texture = gl.createTexture();
  8420. var generateMipMaps = true;
  8421. var generateDepthBuffer = true;
  8422. var generateStencilBuffer = false;
  8423. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8424. if (options !== undefined) {
  8425. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8426. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8427. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8428. if (options.samplingMode !== undefined) {
  8429. samplingMode = options.samplingMode;
  8430. }
  8431. }
  8432. texture.isCube = true;
  8433. texture.references = 1;
  8434. texture.generateMipMaps = generateMipMaps;
  8435. texture.references = 1;
  8436. texture.samplingMode = samplingMode;
  8437. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8438. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8439. for (var face = 0; face < 6; face++) {
  8440. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  8441. }
  8442. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  8443. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  8444. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8445. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8446. // Create the depth buffer
  8447. var depthStencilBuffer;
  8448. // Create the depth/stencil buffer
  8449. if (generateStencilBuffer) {
  8450. depthStencilBuffer = gl.createRenderbuffer();
  8451. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8452. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  8453. }
  8454. else if (generateDepthBuffer) {
  8455. depthStencilBuffer = gl.createRenderbuffer();
  8456. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8457. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  8458. }
  8459. // Create the framebuffer
  8460. var framebuffer = gl.createFramebuffer();
  8461. this.bindUnboundFramebuffer(framebuffer);
  8462. // Manage attachments
  8463. if (generateStencilBuffer) {
  8464. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8465. }
  8466. else if (generateDepthBuffer) {
  8467. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8468. }
  8469. // Mipmaps
  8470. if (texture.generateMipMaps) {
  8471. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8472. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8473. }
  8474. // Unbind
  8475. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8476. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8477. this.bindUnboundFramebuffer(null);
  8478. texture._framebuffer = framebuffer;
  8479. if (generateDepthBuffer) {
  8480. texture._depthBuffer = depthStencilBuffer;
  8481. }
  8482. texture._width = size;
  8483. texture._height = size;
  8484. texture.isReady = true;
  8485. this.resetTextureCache();
  8486. this._loadedTexturesCache.push(texture);
  8487. return texture;
  8488. };
  8489. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError) {
  8490. var _this = this;
  8491. if (onLoad === void 0) { onLoad = null; }
  8492. if (onError === void 0) { onError = null; }
  8493. var gl = this._gl;
  8494. var texture = gl.createTexture();
  8495. texture.isCube = true;
  8496. texture.url = rootUrl;
  8497. texture.references = 1;
  8498. texture.onLoadedCallbacks = [];
  8499. var isKTX = false;
  8500. var lastDot = rootUrl.lastIndexOf('.');
  8501. var extension = rootUrl.substring(lastDot).toLowerCase();
  8502. if (this._textureFormatInUse && !scene.database) {
  8503. extension = this._textureFormatInUse;
  8504. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  8505. isKTX = true;
  8506. }
  8507. var isDDS = (extension === ".dds");
  8508. if (isKTX) {
  8509. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8510. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  8511. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  8512. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8513. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8514. ktx.uploadLevels(_this._gl, !noMipmap);
  8515. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8516. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8517. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8518. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8519. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8520. _this.resetTextureCache();
  8521. texture._width = ktx.pixelWidth;
  8522. texture._height = ktx.pixelHeight;
  8523. texture.isReady = true;
  8524. }, null, null, true, onError);
  8525. }
  8526. else if (isDDS) {
  8527. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8528. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8529. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  8530. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8531. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8532. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  8533. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  8534. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8535. }
  8536. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8537. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8538. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8539. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8540. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8541. _this.resetTextureCache();
  8542. texture._width = info.width;
  8543. texture._height = info.height;
  8544. texture.isReady = true;
  8545. }, null, null, true, onError);
  8546. }
  8547. else {
  8548. cascadeLoad(rootUrl, scene, function (imgs) {
  8549. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8550. var height = width;
  8551. _this._prepareWorkingCanvas();
  8552. _this._workingCanvas.width = width;
  8553. _this._workingCanvas.height = height;
  8554. var faces = [
  8555. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8556. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8557. ];
  8558. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8559. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8560. for (var index = 0; index < faces.length; index++) {
  8561. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8562. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8563. }
  8564. if (!noMipmap) {
  8565. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8566. }
  8567. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8568. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8569. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8570. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8571. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8572. _this.resetTextureCache();
  8573. texture._width = width;
  8574. texture._height = height;
  8575. texture.isReady = true;
  8576. texture.onLoadedCallbacks.forEach(function (callback) {
  8577. callback();
  8578. });
  8579. if (onLoad) {
  8580. onLoad();
  8581. }
  8582. }, files, onError);
  8583. }
  8584. this._loadedTexturesCache.push(texture);
  8585. return texture;
  8586. };
  8587. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8588. texture._width = width;
  8589. texture._height = height;
  8590. texture._size = width * height;
  8591. texture._baseWidth = width;
  8592. texture._baseHeight = height;
  8593. };
  8594. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  8595. var _this = this;
  8596. var gl = this._gl;
  8597. var texture = gl.createTexture();
  8598. scene._addPendingData(texture);
  8599. texture.isCube = true;
  8600. texture.references = 1;
  8601. texture.url = url;
  8602. var internalFormat = this._getInternalFormat(format);
  8603. var textureType = gl.UNSIGNED_BYTE;
  8604. if (type === Engine.TEXTURETYPE_FLOAT) {
  8605. textureType = gl.FLOAT;
  8606. }
  8607. var width = size;
  8608. var height = width;
  8609. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8610. texture._width = width;
  8611. texture._height = height;
  8612. var onerror = function () {
  8613. scene._removePendingData(texture);
  8614. };
  8615. var internalCallback = function (data) {
  8616. var rgbeDataArrays = callback(data);
  8617. var facesIndex = [
  8618. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8619. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8620. ];
  8621. width = texture._width;
  8622. height = texture._height;
  8623. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8624. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8625. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8626. if (!noMipmap && isPot) {
  8627. if (mipmmapGenerator) {
  8628. var arrayTemp = [];
  8629. // Data are known to be in +X +Y +Z -X -Y -Z
  8630. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8631. arrayTemp.push(rgbeDataArrays[0]); // +X
  8632. arrayTemp.push(rgbeDataArrays[3]); // -X
  8633. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8634. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8635. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8636. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8637. var mipData = mipmmapGenerator(arrayTemp);
  8638. for (var level = 0; level < mipData.length; level++) {
  8639. var mipSize = width >> level;
  8640. // mipData is order in +X -X +Y -Y +Z -Z
  8641. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  8642. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  8643. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  8644. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  8645. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  8646. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  8647. }
  8648. }
  8649. else {
  8650. // Data are known to be in +X +Y +Z -X -Y -Z
  8651. for (var index = 0; index < facesIndex.length; index++) {
  8652. var faceData = rgbeDataArrays[index];
  8653. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  8654. }
  8655. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8656. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  8657. // By following the webgl standard changes from Revision 7, 2014/11/24
  8658. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  8659. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  8660. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  8661. // Data are known to be in +X +Y +Z -X -Y -Z
  8662. for (var index = 0; index < facesIndex.length; index++) {
  8663. var faceData = rgbeDataArrays[index];
  8664. // Create a new RGBA Face.
  8665. var newFaceData = new Float32Array(width * height * 4);
  8666. for (var x = 0; x < width; x++) {
  8667. for (var y = 0; y < height; y++) {
  8668. var index_1 = (y * width + x) * 3;
  8669. var newIndex = (y * width + x) * 4;
  8670. // Map Old Value to new value.
  8671. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  8672. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  8673. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  8674. // Add fully opaque alpha channel.
  8675. newFaceData[newIndex + 3] = 1;
  8676. }
  8677. }
  8678. // Reupload the face.
  8679. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  8680. }
  8681. // Try to generate mipmap again.
  8682. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8683. }
  8684. }
  8685. }
  8686. else {
  8687. noMipmap = true;
  8688. }
  8689. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8690. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8691. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8692. }
  8693. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8694. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8695. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8696. }
  8697. else {
  8698. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8699. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8700. }
  8701. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8702. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8703. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8704. texture.isReady = true;
  8705. _this.resetTextureCache();
  8706. scene._removePendingData(texture);
  8707. };
  8708. BABYLON.Tools.LoadFile(url, function (data) {
  8709. internalCallback(data);
  8710. }, onerror, scene.database, true);
  8711. return texture;
  8712. };
  8713. ;
  8714. Engine.prototype._releaseTexture = function (texture) {
  8715. var gl = this._gl;
  8716. if (texture._framebuffer) {
  8717. gl.deleteFramebuffer(texture._framebuffer);
  8718. }
  8719. if (texture._depthBuffer) {
  8720. gl.deleteRenderbuffer(texture._depthBuffer);
  8721. }
  8722. gl.deleteTexture(texture);
  8723. // Unbind channels
  8724. this.unbindAllTextures();
  8725. var index = this._loadedTexturesCache.indexOf(texture);
  8726. if (index !== -1) {
  8727. this._loadedTexturesCache.splice(index, 1);
  8728. }
  8729. };
  8730. Engine.prototype.setProgram = function (program) {
  8731. if (this._currentProgram !== program) {
  8732. this._gl.useProgram(program);
  8733. this._currentProgram = program;
  8734. }
  8735. };
  8736. Engine.prototype.bindSamplers = function (effect) {
  8737. this.setProgram(effect.getProgram());
  8738. var samplers = effect.getSamplers();
  8739. for (var index = 0; index < samplers.length; index++) {
  8740. var uniform = effect.getUniform(samplers[index]);
  8741. this._gl.uniform1i(uniform, index);
  8742. }
  8743. this._currentEffect = null;
  8744. };
  8745. Engine.prototype.activateTexture = function (texture) {
  8746. if (this._activeTexture !== texture) {
  8747. this._gl.activeTexture(texture);
  8748. this._activeTexture = texture;
  8749. }
  8750. };
  8751. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8752. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8753. this._gl.bindTexture(target, texture);
  8754. this._activeTexturesCache[this._activeTexture] = texture;
  8755. }
  8756. };
  8757. Engine.prototype._bindTexture = function (channel, texture) {
  8758. if (channel < 0) {
  8759. return;
  8760. }
  8761. this.activateTexture(this._gl.TEXTURE0 + channel);
  8762. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8763. };
  8764. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8765. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8766. };
  8767. Engine.prototype.unbindAllTextures = function () {
  8768. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8769. this.activateTexture(this._gl["TEXTURE" + channel]);
  8770. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8771. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8772. }
  8773. };
  8774. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8775. if (channel < 0) {
  8776. return;
  8777. }
  8778. this._gl.uniform1i(uniform, channel);
  8779. this._setTexture(channel, texture);
  8780. };
  8781. Engine.prototype._setTexture = function (channel, texture) {
  8782. // Not ready?
  8783. if (!texture || !texture.isReady()) {
  8784. if (this._activeTexturesCache[channel] != null) {
  8785. this.activateTexture(this._gl["TEXTURE" + channel]);
  8786. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8787. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8788. }
  8789. return;
  8790. }
  8791. // Video
  8792. var alreadyActivated = false;
  8793. if (texture instanceof BABYLON.VideoTexture) {
  8794. this.activateTexture(this._gl["TEXTURE" + channel]);
  8795. alreadyActivated = true;
  8796. texture.update();
  8797. }
  8798. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8799. texture.delayLoad();
  8800. return;
  8801. }
  8802. var internalTexture = texture.getInternalTexture();
  8803. if (this._activeTexturesCache[channel] === internalTexture) {
  8804. return;
  8805. }
  8806. if (!alreadyActivated) {
  8807. this.activateTexture(this._gl["TEXTURE" + channel]);
  8808. }
  8809. if (internalTexture.isCube) {
  8810. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8811. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8812. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8813. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8814. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8815. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8816. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8817. }
  8818. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8819. }
  8820. else {
  8821. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8822. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8823. internalTexture._cachedWrapU = texture.wrapU;
  8824. switch (texture.wrapU) {
  8825. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8826. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8827. break;
  8828. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8829. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8830. break;
  8831. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8832. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8833. break;
  8834. }
  8835. }
  8836. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8837. internalTexture._cachedWrapV = texture.wrapV;
  8838. switch (texture.wrapV) {
  8839. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8840. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8841. break;
  8842. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8843. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8844. break;
  8845. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8846. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8847. break;
  8848. }
  8849. }
  8850. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8851. }
  8852. };
  8853. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8854. if (channel < 0) {
  8855. return;
  8856. }
  8857. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8858. this._textureUnits = new Int32Array(textures.length);
  8859. }
  8860. for (var i = 0; i < textures.length; i++) {
  8861. this._textureUnits[i] = channel + i;
  8862. }
  8863. this._gl.uniform1iv(uniform, this._textureUnits);
  8864. for (var index = 0; index < textures.length; index++) {
  8865. this._setTexture(channel + index, textures[index]);
  8866. }
  8867. };
  8868. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8869. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8870. var value = texture.anisotropicFilteringLevel;
  8871. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8872. value = 1;
  8873. }
  8874. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8875. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8876. texture._cachedAnisotropicFilteringLevel = value;
  8877. }
  8878. };
  8879. Engine.prototype.readPixels = function (x, y, width, height) {
  8880. var data = new Uint8Array(height * width * 4);
  8881. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8882. return data;
  8883. };
  8884. /**
  8885. * Add an externaly attached data from its key.
  8886. * This method call will fail and return false, if such key already exists.
  8887. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8888. * @param key the unique key that identifies the data
  8889. * @param data the data object to associate to the key for this Engine instance
  8890. * @return true if no such key were already present and the data was added successfully, false otherwise
  8891. */
  8892. Engine.prototype.addExternalData = function (key, data) {
  8893. return this._externalData.add(key, data);
  8894. };
  8895. /**
  8896. * Get an externaly attached data from its key
  8897. * @param key the unique key that identifies the data
  8898. * @return the associated data, if present (can be null), or undefined if not present
  8899. */
  8900. Engine.prototype.getExternalData = function (key) {
  8901. return this._externalData.get(key);
  8902. };
  8903. /**
  8904. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8905. * @param key the unique key that identifies the data
  8906. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8907. * @return the associated data, can be null if the factory returned null.
  8908. */
  8909. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8910. return this._externalData.getOrAddWithFactory(key, factory);
  8911. };
  8912. /**
  8913. * Remove an externaly attached data from the Engine instance
  8914. * @param key the unique key that identifies the data
  8915. * @return true if the data was successfully removed, false if it doesn't exist
  8916. */
  8917. Engine.prototype.removeExternalData = function (key) {
  8918. return this._externalData.remove(key);
  8919. };
  8920. Engine.prototype.releaseInternalTexture = function (texture) {
  8921. if (!texture) {
  8922. return;
  8923. }
  8924. texture.references--;
  8925. // Final reference ?
  8926. if (texture.references === 0) {
  8927. var texturesCache = this.getLoadedTexturesCache();
  8928. var index = texturesCache.indexOf(texture);
  8929. if (index > -1) {
  8930. texturesCache.splice(index, 1);
  8931. }
  8932. this._releaseTexture(texture);
  8933. }
  8934. };
  8935. Engine.prototype.unbindAllAttributes = function () {
  8936. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8937. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  8938. continue;
  8939. }
  8940. if (this._vertexAttribArraysEnabled[i]) {
  8941. this._gl.disableVertexAttribArray(i);
  8942. this._vertexAttribArraysEnabled[i] = false;
  8943. }
  8944. }
  8945. };
  8946. // Dispose
  8947. Engine.prototype.dispose = function () {
  8948. this.hideLoadingUI();
  8949. this.stopRenderLoop();
  8950. // Release scenes
  8951. while (this.scenes.length) {
  8952. this.scenes[0].dispose();
  8953. }
  8954. // Release audio engine
  8955. Engine.audioEngine.dispose();
  8956. // Release effects
  8957. for (var name in this._compiledEffects) {
  8958. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8959. }
  8960. // Unbind
  8961. this.unbindAllAttributes();
  8962. this._gl = null;
  8963. //WebVR
  8964. this.disableVR();
  8965. // Events
  8966. window.removeEventListener("blur", this._onBlur);
  8967. window.removeEventListener("focus", this._onFocus);
  8968. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8969. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8970. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8971. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8972. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8973. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8974. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8975. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8976. };
  8977. // Loading screen
  8978. Engine.prototype.displayLoadingUI = function () {
  8979. this._loadingScreen.displayLoadingUI();
  8980. };
  8981. Engine.prototype.hideLoadingUI = function () {
  8982. this._loadingScreen.hideLoadingUI();
  8983. };
  8984. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8985. get: function () {
  8986. return this._loadingScreen;
  8987. },
  8988. set: function (loadingScreen) {
  8989. this._loadingScreen = loadingScreen;
  8990. },
  8991. enumerable: true,
  8992. configurable: true
  8993. });
  8994. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8995. set: function (text) {
  8996. this._loadingScreen.loadingUIText = text;
  8997. },
  8998. enumerable: true,
  8999. configurable: true
  9000. });
  9001. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  9002. set: function (color) {
  9003. this._loadingScreen.loadingUIBackgroundColor = color;
  9004. },
  9005. enumerable: true,
  9006. configurable: true
  9007. });
  9008. Engine.prototype.attachContextLostEvent = function (callback) {
  9009. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  9010. };
  9011. Engine.prototype.attachContextRestoredEvent = function (callback) {
  9012. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  9013. };
  9014. Engine.prototype.getVertexShaderSource = function (program) {
  9015. var shaders = this._gl.getAttachedShaders(program);
  9016. return this._gl.getShaderSource(shaders[0]);
  9017. };
  9018. Engine.prototype.getFragmentShaderSource = function (program) {
  9019. var shaders = this._gl.getAttachedShaders(program);
  9020. return this._gl.getShaderSource(shaders[1]);
  9021. };
  9022. // FPS
  9023. Engine.prototype.getFps = function () {
  9024. return this.fps;
  9025. };
  9026. Engine.prototype.getDeltaTime = function () {
  9027. return this.deltaTime;
  9028. };
  9029. Engine.prototype._measureFps = function () {
  9030. this.previousFramesDuration.push(BABYLON.Tools.Now);
  9031. var length = this.previousFramesDuration.length;
  9032. if (length >= 2) {
  9033. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  9034. }
  9035. if (length >= this.fpsRange) {
  9036. if (length > this.fpsRange) {
  9037. this.previousFramesDuration.splice(0, 1);
  9038. length = this.previousFramesDuration.length;
  9039. }
  9040. var sum = 0;
  9041. for (var id = 0; id < length - 1; id++) {
  9042. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  9043. }
  9044. this.fps = 1000.0 / (sum / (length - 1));
  9045. }
  9046. };
  9047. Engine.prototype._canRenderToFloatTexture = function () {
  9048. if (this._webGLVersion > 1) {
  9049. return true;
  9050. }
  9051. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  9052. };
  9053. Engine.prototype._canRenderToHalfFloatTexture = function () {
  9054. if (this._webGLVersion > 1) {
  9055. return true;
  9056. }
  9057. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  9058. };
  9059. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  9060. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  9061. try {
  9062. var tempcanvas = document.createElement("canvas");
  9063. tempcanvas.height = 16;
  9064. tempcanvas.width = 16;
  9065. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  9066. // extension.
  9067. var ext = gl.getExtension(extension);
  9068. if (!ext) {
  9069. return false;
  9070. }
  9071. // setup GLSL program
  9072. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  9073. var fragmentCode = "precision mediump float;\n uniform vec4 u_color;\n uniform sampler2D u_texture;\n\n void main() {\n gl_FragColor = texture2D(u_texture, vec2(0.5, 0.5)) * u_color;\n }";
  9074. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  9075. gl.useProgram(program);
  9076. // look up where the vertex data needs to go.
  9077. var positionLocation = gl.getAttribLocation(program, "a_position");
  9078. var colorLoc = gl.getUniformLocation(program, "u_color");
  9079. // provide texture coordinates for the rectangle.
  9080. var positionBuffer = gl.createBuffer();
  9081. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  9082. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  9083. -1.0, -1.0,
  9084. 1.0, -1.0,
  9085. -1.0, 1.0,
  9086. -1.0, 1.0,
  9087. 1.0, -1.0,
  9088. 1.0, 1.0
  9089. ]), gl.STATIC_DRAW);
  9090. gl.enableVertexAttribArray(positionLocation);
  9091. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  9092. var whiteTex = gl.createTexture();
  9093. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  9094. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  9095. var tex = gl.createTexture();
  9096. gl.bindTexture(gl.TEXTURE_2D, tex);
  9097. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  9098. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9099. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9100. var fb = gl.createFramebuffer();
  9101. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  9102. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  9103. gl.viewport(0, 0, 1, 1);
  9104. var cleanup = function () {
  9105. gl.deleteProgram(program);
  9106. gl.disableVertexAttribArray(positionLocation);
  9107. gl.deleteBuffer(positionBuffer);
  9108. gl.deleteFramebuffer(fb);
  9109. gl.deleteTexture(whiteTex);
  9110. gl.deleteTexture(tex);
  9111. };
  9112. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  9113. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  9114. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  9115. cleanup();
  9116. return false;
  9117. }
  9118. // Draw the rectangle.
  9119. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  9120. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  9121. gl.drawArrays(gl.TRIANGLES, 0, 6);
  9122. gl.bindTexture(gl.TEXTURE_2D, tex);
  9123. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9124. gl.clearColor(1, 0, 0, 1);
  9125. gl.clear(gl.COLOR_BUFFER_BIT);
  9126. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  9127. gl.drawArrays(gl.TRIANGLES, 0, 6);
  9128. var pixel = new Uint8Array(4);
  9129. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  9130. if (pixel[0] !== 0 ||
  9131. pixel[1] < 248 ||
  9132. pixel[2] < 248 ||
  9133. pixel[3] < 254) {
  9134. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  9135. cleanup();
  9136. return false;
  9137. }
  9138. // Succesfully rendered to "format" texture.
  9139. cleanup();
  9140. return true;
  9141. }
  9142. catch (e) {
  9143. return false;
  9144. }
  9145. };
  9146. // Statics
  9147. Engine.isSupported = function () {
  9148. try {
  9149. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  9150. if (navigator.isCocoonJS) {
  9151. return true;
  9152. }
  9153. var tempcanvas = document.createElement("canvas");
  9154. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  9155. return gl != null && !!window.WebGLRenderingContext;
  9156. }
  9157. catch (e) {
  9158. return false;
  9159. }
  9160. };
  9161. return Engine;
  9162. }());
  9163. // Const statics
  9164. Engine._ALPHA_DISABLE = 0;
  9165. Engine._ALPHA_ADD = 1;
  9166. Engine._ALPHA_COMBINE = 2;
  9167. Engine._ALPHA_SUBTRACT = 3;
  9168. Engine._ALPHA_MULTIPLY = 4;
  9169. Engine._ALPHA_MAXIMIZED = 5;
  9170. Engine._ALPHA_ONEONE = 6;
  9171. Engine._ALPHA_PREMULTIPLIED = 7;
  9172. Engine._DELAYLOADSTATE_NONE = 0;
  9173. Engine._DELAYLOADSTATE_LOADED = 1;
  9174. Engine._DELAYLOADSTATE_LOADING = 2;
  9175. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  9176. Engine._TEXTUREFORMAT_ALPHA = 0;
  9177. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  9178. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  9179. Engine._TEXTUREFORMAT_RGB = 4;
  9180. Engine._TEXTUREFORMAT_RGBA = 5;
  9181. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  9182. Engine._TEXTURETYPE_FLOAT = 1;
  9183. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  9184. // Depht or Stencil test Constants.
  9185. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  9186. 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.
  9187. 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.
  9188. 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.
  9189. 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.
  9190. 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.
  9191. 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.
  9192. 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.
  9193. // Stencil Actions Constants.
  9194. Engine._KEEP = 0x1E00;
  9195. Engine._REPLACE = 0x1E01;
  9196. Engine._INCR = 0x1E02;
  9197. Engine._DECR = 0x1E03;
  9198. Engine._INVERT = 0x150A;
  9199. Engine._INCR_WRAP = 0x8507;
  9200. Engine._DECR_WRAP = 0x8508;
  9201. // Updatable statics so stick with vars here
  9202. Engine.CollisionsEpsilon = 0.001;
  9203. Engine.CodeRepository = "src/";
  9204. Engine.ShadersRepository = "src/Shaders/";
  9205. BABYLON.Engine = Engine;
  9206. })(BABYLON || (BABYLON = {}));
  9207. //# sourceMappingURL=babylon.engine.js.map
  9208. var BABYLON;
  9209. (function (BABYLON) {
  9210. /**
  9211. * Node is the basic class for all scene objects (Mesh, Light Camera).
  9212. */
  9213. var Node = (function () {
  9214. /**
  9215. * @constructor
  9216. * @param {string} name - the name and id to be given to this node
  9217. * @param {BABYLON.Scene} the scene this node will be added to
  9218. */
  9219. function Node(name, scene) {
  9220. this.state = "";
  9221. this.metadata = null;
  9222. this.doNotSerialize = false;
  9223. this.animations = new Array();
  9224. this._ranges = {};
  9225. this._childrenFlag = -1;
  9226. this._isEnabled = true;
  9227. this._isReady = true;
  9228. this._currentRenderId = -1;
  9229. this._parentRenderId = -1;
  9230. /**
  9231. * An event triggered when the mesh is disposed.
  9232. * @type {BABYLON.Observable}
  9233. */
  9234. this.onDisposeObservable = new BABYLON.Observable();
  9235. this.name = name;
  9236. this.id = name;
  9237. this._scene = scene;
  9238. this._initCache();
  9239. }
  9240. Object.defineProperty(Node.prototype, "parent", {
  9241. get: function () {
  9242. return this._parentNode;
  9243. },
  9244. set: function (parent) {
  9245. if (this._parentNode === parent) {
  9246. return;
  9247. }
  9248. if (this._parentNode) {
  9249. var index = this._parentNode._children.indexOf(this);
  9250. if (index !== -1) {
  9251. this._parentNode._children.splice(index, 1);
  9252. }
  9253. }
  9254. this._parentNode = parent;
  9255. if (this._parentNode) {
  9256. if (!this._parentNode._children) {
  9257. this._parentNode._children = new Array();
  9258. }
  9259. this._parentNode._children.push(this);
  9260. }
  9261. },
  9262. enumerable: true,
  9263. configurable: true
  9264. });
  9265. Node.prototype.getClassName = function () {
  9266. return "Node";
  9267. };
  9268. Object.defineProperty(Node.prototype, "onDispose", {
  9269. set: function (callback) {
  9270. if (this._onDisposeObserver) {
  9271. this.onDisposeObservable.remove(this._onDisposeObserver);
  9272. }
  9273. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9274. },
  9275. enumerable: true,
  9276. configurable: true
  9277. });
  9278. Node.prototype.getScene = function () {
  9279. return this._scene;
  9280. };
  9281. Node.prototype.getEngine = function () {
  9282. return this._scene.getEngine();
  9283. };
  9284. // override it in derived class
  9285. Node.prototype.getWorldMatrix = function () {
  9286. return BABYLON.Matrix.Identity();
  9287. };
  9288. // override it in derived class if you add new variables to the cache
  9289. // and call the parent class method
  9290. Node.prototype._initCache = function () {
  9291. this._cache = {};
  9292. this._cache.parent = undefined;
  9293. };
  9294. Node.prototype.updateCache = function (force) {
  9295. if (!force && this.isSynchronized())
  9296. return;
  9297. this._cache.parent = this.parent;
  9298. this._updateCache();
  9299. };
  9300. // override it in derived class if you add new variables to the cache
  9301. // and call the parent class method if !ignoreParentClass
  9302. Node.prototype._updateCache = function (ignoreParentClass) {
  9303. };
  9304. // override it in derived class if you add new variables to the cache
  9305. Node.prototype._isSynchronized = function () {
  9306. return true;
  9307. };
  9308. Node.prototype._markSyncedWithParent = function () {
  9309. this._parentRenderId = this.parent._currentRenderId;
  9310. };
  9311. Node.prototype.isSynchronizedWithParent = function () {
  9312. if (!this.parent) {
  9313. return true;
  9314. }
  9315. if (this._parentRenderId !== this.parent._currentRenderId) {
  9316. return false;
  9317. }
  9318. return this.parent.isSynchronized();
  9319. };
  9320. Node.prototype.isSynchronized = function (updateCache) {
  9321. var check = this.hasNewParent();
  9322. check = check || !this.isSynchronizedWithParent();
  9323. check = check || !this._isSynchronized();
  9324. if (updateCache)
  9325. this.updateCache(true);
  9326. return !check;
  9327. };
  9328. Node.prototype.hasNewParent = function (update) {
  9329. if (this._cache.parent === this.parent)
  9330. return false;
  9331. if (update)
  9332. this._cache.parent = this.parent;
  9333. return true;
  9334. };
  9335. /**
  9336. * Is this node ready to be used/rendered
  9337. * @return {boolean} is it ready
  9338. */
  9339. Node.prototype.isReady = function () {
  9340. return this._isReady;
  9341. };
  9342. /**
  9343. * Is this node enabled.
  9344. * If the node has a parent and is enabled, the parent will be inspected as well.
  9345. * @return {boolean} whether this node (and its parent) is enabled.
  9346. * @see setEnabled
  9347. */
  9348. Node.prototype.isEnabled = function () {
  9349. if (!this._isEnabled) {
  9350. return false;
  9351. }
  9352. if (this.parent) {
  9353. return this.parent.isEnabled();
  9354. }
  9355. return true;
  9356. };
  9357. /**
  9358. * Set the enabled state of this node.
  9359. * @param {boolean} value - the new enabled state
  9360. * @see isEnabled
  9361. */
  9362. Node.prototype.setEnabled = function (value) {
  9363. this._isEnabled = value;
  9364. };
  9365. /**
  9366. * Is this node a descendant of the given node.
  9367. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  9368. * @param {BABYLON.Node} ancestor - The parent node to inspect
  9369. * @see parent
  9370. */
  9371. Node.prototype.isDescendantOf = function (ancestor) {
  9372. if (this.parent) {
  9373. if (this.parent === ancestor) {
  9374. return true;
  9375. }
  9376. return this.parent.isDescendantOf(ancestor);
  9377. }
  9378. return false;
  9379. };
  9380. /**
  9381. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  9382. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  9383. * @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.
  9384. * @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.
  9385. */
  9386. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  9387. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  9388. if (!this._children) {
  9389. return;
  9390. }
  9391. for (var index = 0; index < this._children.length; index++) {
  9392. var item = this._children[index];
  9393. if (!predicate || predicate(item)) {
  9394. results.push(item);
  9395. }
  9396. if (!directDescendantsOnly) {
  9397. item._getDescendants(results, false, predicate);
  9398. }
  9399. }
  9400. };
  9401. /**
  9402. * Will return all nodes that have this node as ascendant.
  9403. * @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.
  9404. * @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.
  9405. * @return {BABYLON.Node[]} all children nodes of all types.
  9406. */
  9407. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  9408. var results = [];
  9409. this._getDescendants(results, directDescendantsOnly, predicate);
  9410. return results;
  9411. };
  9412. /**
  9413. * @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.
  9414. * @Deprecated, legacy support.
  9415. * use getDecendants instead.
  9416. */
  9417. Node.prototype.getChildren = function (predicate) {
  9418. return this.getDescendants(true, predicate);
  9419. };
  9420. /**
  9421. * Get all child-meshes of this node.
  9422. */
  9423. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  9424. var results = [];
  9425. this._getDescendants(results, directDecendantsOnly, function (node) {
  9426. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  9427. });
  9428. return results;
  9429. };
  9430. Node.prototype._setReady = function (state) {
  9431. if (state === this._isReady) {
  9432. return;
  9433. }
  9434. if (!state) {
  9435. this._isReady = false;
  9436. return;
  9437. }
  9438. this._isReady = true;
  9439. if (this.onReady) {
  9440. this.onReady(this);
  9441. }
  9442. };
  9443. Node.prototype.getAnimationByName = function (name) {
  9444. for (var i = 0; i < this.animations.length; i++) {
  9445. var animation = this.animations[i];
  9446. if (animation.name === name) {
  9447. return animation;
  9448. }
  9449. }
  9450. return null;
  9451. };
  9452. Node.prototype.createAnimationRange = function (name, from, to) {
  9453. // check name not already in use
  9454. if (!this._ranges[name]) {
  9455. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  9456. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9457. if (this.animations[i]) {
  9458. this.animations[i].createRange(name, from, to);
  9459. }
  9460. }
  9461. }
  9462. };
  9463. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  9464. if (deleteFrames === void 0) { deleteFrames = true; }
  9465. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9466. if (this.animations[i]) {
  9467. this.animations[i].deleteRange(name, deleteFrames);
  9468. }
  9469. }
  9470. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  9471. };
  9472. Node.prototype.getAnimationRange = function (name) {
  9473. return this._ranges[name];
  9474. };
  9475. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  9476. var range = this.getAnimationRange(name);
  9477. if (!range) {
  9478. return null;
  9479. }
  9480. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  9481. };
  9482. Node.prototype.serializeAnimationRanges = function () {
  9483. var serializationRanges = [];
  9484. for (var name in this._ranges) {
  9485. var range = {};
  9486. range.name = name;
  9487. range.from = this._ranges[name].from;
  9488. range.to = this._ranges[name].to;
  9489. serializationRanges.push(range);
  9490. }
  9491. return serializationRanges;
  9492. };
  9493. Node.prototype.dispose = function () {
  9494. this.parent = null;
  9495. // Callback
  9496. this.onDisposeObservable.notifyObservers(this);
  9497. this.onDisposeObservable.clear();
  9498. };
  9499. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  9500. if (parsedNode.ranges) {
  9501. for (var index = 0; index < parsedNode.ranges.length; index++) {
  9502. var data = parsedNode.ranges[index];
  9503. node.createAnimationRange(data.name, data.from, data.to);
  9504. }
  9505. }
  9506. };
  9507. return Node;
  9508. }());
  9509. __decorate([
  9510. BABYLON.serialize()
  9511. ], Node.prototype, "name", void 0);
  9512. __decorate([
  9513. BABYLON.serialize()
  9514. ], Node.prototype, "id", void 0);
  9515. __decorate([
  9516. BABYLON.serialize()
  9517. ], Node.prototype, "uniqueId", void 0);
  9518. __decorate([
  9519. BABYLON.serialize()
  9520. ], Node.prototype, "state", void 0);
  9521. __decorate([
  9522. BABYLON.serialize()
  9523. ], Node.prototype, "metadata", void 0);
  9524. BABYLON.Node = Node;
  9525. })(BABYLON || (BABYLON = {}));
  9526. //# sourceMappingURL=babylon.node.js.map
  9527. var BABYLON;
  9528. (function (BABYLON) {
  9529. var FilesInput = (function () {
  9530. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  9531. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  9532. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  9533. this._engine = p_engine;
  9534. this._canvas = p_canvas;
  9535. this._currentScene = p_scene;
  9536. this._sceneLoadedCallback = p_sceneLoadedCallback;
  9537. this._progressCallback = p_progressCallback;
  9538. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  9539. this._textureLoadingCallback = p_textureLoadingCallback;
  9540. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  9541. }
  9542. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  9543. var _this = this;
  9544. if (p_elementToMonitor) {
  9545. this._elementToMonitor = p_elementToMonitor;
  9546. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  9547. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  9548. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  9549. }
  9550. };
  9551. FilesInput.prototype.renderFunction = function () {
  9552. if (this._additionnalRenderLoopLogicCallback) {
  9553. this._additionnalRenderLoopLogicCallback();
  9554. }
  9555. if (this._currentScene) {
  9556. if (this._textureLoadingCallback) {
  9557. var remaining = this._currentScene.getWaitingItemsCount();
  9558. if (remaining > 0) {
  9559. this._textureLoadingCallback(remaining);
  9560. }
  9561. }
  9562. this._currentScene.render();
  9563. }
  9564. };
  9565. FilesInput.prototype.drag = function (e) {
  9566. e.stopPropagation();
  9567. e.preventDefault();
  9568. };
  9569. FilesInput.prototype.drop = function (eventDrop) {
  9570. eventDrop.stopPropagation();
  9571. eventDrop.preventDefault();
  9572. this.loadFiles(eventDrop);
  9573. };
  9574. FilesInput.prototype.loadFiles = function (event) {
  9575. if (this._startingProcessingFilesCallback)
  9576. this._startingProcessingFilesCallback();
  9577. // Handling data transfer via drag'n'drop
  9578. if (event && event.dataTransfer && event.dataTransfer.files) {
  9579. this._filesToLoad = event.dataTransfer.files;
  9580. }
  9581. // Handling files from input files
  9582. if (event && event.target && event.target.files) {
  9583. this._filesToLoad = event.target.files;
  9584. }
  9585. if (this._filesToLoad && this._filesToLoad.length > 0) {
  9586. for (var i = 0; i < this._filesToLoad.length; i++) {
  9587. switch (this._filesToLoad[i].type) {
  9588. case "image/jpeg":
  9589. case "image/png":
  9590. case "image/bmp":
  9591. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9592. break;
  9593. case "image/targa":
  9594. case "image/vnd.ms-dds":
  9595. case "audio/wav":
  9596. case "audio/x-wav":
  9597. case "audio/mp3":
  9598. case "audio/mpeg":
  9599. case "audio/mpeg3":
  9600. case "audio/x-mpeg-3":
  9601. case "audio/ogg":
  9602. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9603. break;
  9604. default:
  9605. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  9606. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9607. }
  9608. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  9609. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  9610. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  9611. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  9612. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  9613. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  9614. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  9615. this._sceneFileToLoad = this._filesToLoad[i];
  9616. }
  9617. break;
  9618. }
  9619. }
  9620. this.reload();
  9621. }
  9622. };
  9623. FilesInput.prototype.reload = function () {
  9624. var _this = this;
  9625. var that = this;
  9626. // If a ".babylon" file has been provided
  9627. if (this._sceneFileToLoad) {
  9628. if (this._currentScene) {
  9629. if (BABYLON.Tools.errorsCount > 0) {
  9630. BABYLON.Tools.ClearLogCache();
  9631. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9632. }
  9633. this._engine.stopRenderLoop();
  9634. this._currentScene.dispose();
  9635. }
  9636. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9637. that._currentScene = newScene;
  9638. // Wait for textures and shaders to be ready
  9639. that._currentScene.executeWhenReady(function () {
  9640. // Attach camera to canvas inputs
  9641. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9642. that._currentScene.createDefaultCameraOrLight();
  9643. }
  9644. that._currentScene.activeCamera.attachControl(that._canvas);
  9645. if (that._sceneLoadedCallback) {
  9646. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9647. }
  9648. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9649. });
  9650. }, function (progress) {
  9651. if (_this._progressCallback) {
  9652. _this._progressCallback(progress);
  9653. }
  9654. });
  9655. }
  9656. else {
  9657. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9658. }
  9659. };
  9660. return FilesInput;
  9661. }());
  9662. FilesInput.FilesTextures = new Array();
  9663. FilesInput.FilesToLoad = new Array();
  9664. BABYLON.FilesInput = FilesInput;
  9665. })(BABYLON || (BABYLON = {}));
  9666. //# sourceMappingURL=babylon.filesInput.js.map
  9667. var BABYLON;
  9668. (function (BABYLON) {
  9669. var IntersectionInfo = (function () {
  9670. function IntersectionInfo(bu, bv, distance) {
  9671. this.bu = bu;
  9672. this.bv = bv;
  9673. this.distance = distance;
  9674. this.faceId = 0;
  9675. this.subMeshId = 0;
  9676. }
  9677. return IntersectionInfo;
  9678. }());
  9679. BABYLON.IntersectionInfo = IntersectionInfo;
  9680. var PickingInfo = (function () {
  9681. function PickingInfo() {
  9682. this.hit = false;
  9683. this.distance = 0;
  9684. this.pickedPoint = null;
  9685. this.pickedMesh = null;
  9686. this.bu = 0;
  9687. this.bv = 0;
  9688. this.faceId = -1;
  9689. this.subMeshId = 0;
  9690. this.pickedSprite = null;
  9691. }
  9692. // Methods
  9693. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9694. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9695. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9696. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9697. return null;
  9698. }
  9699. var indices = this.pickedMesh.getIndices();
  9700. var result;
  9701. if (useVerticesNormals) {
  9702. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9703. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9704. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9705. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9706. normal0 = normal0.scale(this.bu);
  9707. normal1 = normal1.scale(this.bv);
  9708. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9709. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9710. }
  9711. else {
  9712. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9713. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9714. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9715. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9716. var p1p2 = vertex1.subtract(vertex2);
  9717. var p3p2 = vertex3.subtract(vertex2);
  9718. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9719. }
  9720. if (useWorldCoordinates) {
  9721. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9722. }
  9723. return BABYLON.Vector3.Normalize(result);
  9724. };
  9725. PickingInfo.prototype.getTextureCoordinates = function () {
  9726. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9727. return null;
  9728. }
  9729. var indices = this.pickedMesh.getIndices();
  9730. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9731. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9732. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9733. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9734. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9735. uv1 = uv1.scale(this.bu);
  9736. uv2 = uv2.scale(this.bv);
  9737. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9738. };
  9739. return PickingInfo;
  9740. }());
  9741. BABYLON.PickingInfo = PickingInfo;
  9742. })(BABYLON || (BABYLON = {}));
  9743. //# sourceMappingURL=babylon.pickingInfo.js.map
  9744. var BABYLON;
  9745. (function (BABYLON) {
  9746. var BoundingSphere = (function () {
  9747. function BoundingSphere(minimum, maximum) {
  9748. this.minimum = minimum;
  9749. this.maximum = maximum;
  9750. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9751. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9752. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9753. this.radius = distance * 0.5;
  9754. this.centerWorld = BABYLON.Vector3.Zero();
  9755. this._update(BABYLON.Matrix.Identity());
  9756. }
  9757. // Methods
  9758. BoundingSphere.prototype._update = function (world) {
  9759. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9760. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9761. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9762. };
  9763. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9764. for (var i = 0; i < 6; i++) {
  9765. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9766. return false;
  9767. }
  9768. return true;
  9769. };
  9770. BoundingSphere.prototype.intersectsPoint = function (point) {
  9771. var x = this.centerWorld.x - point.x;
  9772. var y = this.centerWorld.y - point.y;
  9773. var z = this.centerWorld.z - point.z;
  9774. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9775. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9776. return false;
  9777. return true;
  9778. };
  9779. // Statics
  9780. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9781. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9782. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9783. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9784. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9785. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9786. return false;
  9787. return true;
  9788. };
  9789. return BoundingSphere;
  9790. }());
  9791. BABYLON.BoundingSphere = BoundingSphere;
  9792. })(BABYLON || (BABYLON = {}));
  9793. //# sourceMappingURL=babylon.boundingSphere.js.map
  9794. var BABYLON;
  9795. (function (BABYLON) {
  9796. var BoundingBox = (function () {
  9797. function BoundingBox(minimum, maximum) {
  9798. this.minimum = minimum;
  9799. this.maximum = maximum;
  9800. this.vectors = new Array();
  9801. this.vectorsWorld = new Array();
  9802. // Bounding vectors
  9803. this.vectors.push(this.minimum.clone());
  9804. this.vectors.push(this.maximum.clone());
  9805. this.vectors.push(this.minimum.clone());
  9806. this.vectors[2].x = this.maximum.x;
  9807. this.vectors.push(this.minimum.clone());
  9808. this.vectors[3].y = this.maximum.y;
  9809. this.vectors.push(this.minimum.clone());
  9810. this.vectors[4].z = this.maximum.z;
  9811. this.vectors.push(this.maximum.clone());
  9812. this.vectors[5].z = this.minimum.z;
  9813. this.vectors.push(this.maximum.clone());
  9814. this.vectors[6].x = this.minimum.x;
  9815. this.vectors.push(this.maximum.clone());
  9816. this.vectors[7].y = this.minimum.y;
  9817. // OBB
  9818. this.center = this.maximum.add(this.minimum).scale(0.5);
  9819. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9820. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9821. // World
  9822. for (var index = 0; index < this.vectors.length; index++) {
  9823. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9824. }
  9825. this.minimumWorld = BABYLON.Vector3.Zero();
  9826. this.maximumWorld = BABYLON.Vector3.Zero();
  9827. this._update(BABYLON.Matrix.Identity());
  9828. }
  9829. // Methods
  9830. BoundingBox.prototype.getWorldMatrix = function () {
  9831. return this._worldMatrix;
  9832. };
  9833. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9834. this._worldMatrix.copyFrom(matrix);
  9835. return this;
  9836. };
  9837. BoundingBox.prototype._update = function (world) {
  9838. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9839. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9840. for (var index = 0; index < this.vectors.length; index++) {
  9841. var v = this.vectorsWorld[index];
  9842. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9843. if (v.x < this.minimumWorld.x)
  9844. this.minimumWorld.x = v.x;
  9845. if (v.y < this.minimumWorld.y)
  9846. this.minimumWorld.y = v.y;
  9847. if (v.z < this.minimumWorld.z)
  9848. this.minimumWorld.z = v.z;
  9849. if (v.x > this.maximumWorld.x)
  9850. this.maximumWorld.x = v.x;
  9851. if (v.y > this.maximumWorld.y)
  9852. this.maximumWorld.y = v.y;
  9853. if (v.z > this.maximumWorld.z)
  9854. this.maximumWorld.z = v.z;
  9855. }
  9856. // OBB
  9857. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9858. this.center.scaleInPlace(0.5);
  9859. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9860. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9861. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9862. this._worldMatrix = world;
  9863. };
  9864. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9865. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9866. };
  9867. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9868. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9869. };
  9870. BoundingBox.prototype.intersectsPoint = function (point) {
  9871. var delta = -BABYLON.Epsilon;
  9872. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9873. return false;
  9874. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9875. return false;
  9876. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9877. return false;
  9878. return true;
  9879. };
  9880. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9881. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9882. };
  9883. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9884. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9885. return false;
  9886. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9887. return false;
  9888. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9889. return false;
  9890. return true;
  9891. };
  9892. // Statics
  9893. BoundingBox.Intersects = function (box0, box1) {
  9894. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9895. return false;
  9896. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9897. return false;
  9898. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9899. return false;
  9900. return true;
  9901. };
  9902. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9903. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9904. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9905. return (num <= (sphereRadius * sphereRadius));
  9906. };
  9907. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9908. for (var p = 0; p < 6; p++) {
  9909. for (var i = 0; i < 8; i++) {
  9910. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9911. return false;
  9912. }
  9913. }
  9914. }
  9915. return true;
  9916. };
  9917. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9918. for (var p = 0; p < 6; p++) {
  9919. var inCount = 8;
  9920. for (var i = 0; i < 8; i++) {
  9921. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9922. --inCount;
  9923. }
  9924. else {
  9925. break;
  9926. }
  9927. }
  9928. if (inCount === 0)
  9929. return false;
  9930. }
  9931. return true;
  9932. };
  9933. return BoundingBox;
  9934. }());
  9935. BABYLON.BoundingBox = BoundingBox;
  9936. })(BABYLON || (BABYLON = {}));
  9937. //# sourceMappingURL=babylon.boundingBox.js.map
  9938. var BABYLON;
  9939. (function (BABYLON) {
  9940. var computeBoxExtents = function (axis, box) {
  9941. var p = BABYLON.Vector3.Dot(box.center, axis);
  9942. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9943. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9944. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9945. var r = r0 + r1 + r2;
  9946. return {
  9947. min: p - r,
  9948. max: p + r
  9949. };
  9950. };
  9951. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  9952. var axisOverlap = function (axis, box0, box1) {
  9953. var result0 = computeBoxExtents(axis, box0);
  9954. var result1 = computeBoxExtents(axis, box1);
  9955. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  9956. };
  9957. var BoundingInfo = (function () {
  9958. function BoundingInfo(minimum, maximum) {
  9959. this.minimum = minimum;
  9960. this.maximum = maximum;
  9961. this._isLocked = false;
  9962. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  9963. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  9964. }
  9965. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  9966. get: function () {
  9967. return this._isLocked;
  9968. },
  9969. set: function (value) {
  9970. this._isLocked = value;
  9971. },
  9972. enumerable: true,
  9973. configurable: true
  9974. });
  9975. // Methods
  9976. BoundingInfo.prototype.update = function (world) {
  9977. if (this._isLocked) {
  9978. return;
  9979. }
  9980. this.boundingBox._update(world);
  9981. this.boundingSphere._update(world);
  9982. };
  9983. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  9984. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  9985. return false;
  9986. return this.boundingBox.isInFrustum(frustumPlanes);
  9987. };
  9988. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9989. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  9990. };
  9991. BoundingInfo.prototype._checkCollision = function (collider) {
  9992. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  9993. };
  9994. BoundingInfo.prototype.intersectsPoint = function (point) {
  9995. if (!this.boundingSphere.centerWorld) {
  9996. return false;
  9997. }
  9998. if (!this.boundingSphere.intersectsPoint(point)) {
  9999. return false;
  10000. }
  10001. if (!this.boundingBox.intersectsPoint(point)) {
  10002. return false;
  10003. }
  10004. return true;
  10005. };
  10006. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  10007. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  10008. return false;
  10009. }
  10010. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  10011. return false;
  10012. }
  10013. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  10014. return false;
  10015. }
  10016. if (!precise) {
  10017. return true;
  10018. }
  10019. var box0 = this.boundingBox;
  10020. var box1 = boundingInfo.boundingBox;
  10021. if (!axisOverlap(box0.directions[0], box0, box1))
  10022. return false;
  10023. if (!axisOverlap(box0.directions[1], box0, box1))
  10024. return false;
  10025. if (!axisOverlap(box0.directions[2], box0, box1))
  10026. return false;
  10027. if (!axisOverlap(box1.directions[0], box0, box1))
  10028. return false;
  10029. if (!axisOverlap(box1.directions[1], box0, box1))
  10030. return false;
  10031. if (!axisOverlap(box1.directions[2], box0, box1))
  10032. return false;
  10033. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  10034. return false;
  10035. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  10036. return false;
  10037. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  10038. return false;
  10039. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  10040. return false;
  10041. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  10042. return false;
  10043. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  10044. return false;
  10045. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  10046. return false;
  10047. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  10048. return false;
  10049. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  10050. return false;
  10051. return true;
  10052. };
  10053. return BoundingInfo;
  10054. }());
  10055. BABYLON.BoundingInfo = BoundingInfo;
  10056. })(BABYLON || (BABYLON = {}));
  10057. //# sourceMappingURL=babylon.boundingInfo.js.map
  10058. var BABYLON;
  10059. (function (BABYLON) {
  10060. var Ray = (function () {
  10061. function Ray(origin, direction, length) {
  10062. if (length === void 0) { length = Number.MAX_VALUE; }
  10063. this.origin = origin;
  10064. this.direction = direction;
  10065. this.length = length;
  10066. this._show = false;
  10067. }
  10068. // Methods
  10069. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  10070. var d = 0.0;
  10071. var maxValue = Number.MAX_VALUE;
  10072. var inv;
  10073. var min;
  10074. var max;
  10075. var temp;
  10076. if (Math.abs(this.direction.x) < 0.0000001) {
  10077. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  10078. return false;
  10079. }
  10080. }
  10081. else {
  10082. inv = 1.0 / this.direction.x;
  10083. min = (minimum.x - this.origin.x) * inv;
  10084. max = (maximum.x - this.origin.x) * inv;
  10085. if (max === -Infinity) {
  10086. max = Infinity;
  10087. }
  10088. if (min > max) {
  10089. temp = min;
  10090. min = max;
  10091. max = temp;
  10092. }
  10093. d = Math.max(min, d);
  10094. maxValue = Math.min(max, maxValue);
  10095. if (d > maxValue) {
  10096. return false;
  10097. }
  10098. }
  10099. if (Math.abs(this.direction.y) < 0.0000001) {
  10100. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  10101. return false;
  10102. }
  10103. }
  10104. else {
  10105. inv = 1.0 / this.direction.y;
  10106. min = (minimum.y - this.origin.y) * inv;
  10107. max = (maximum.y - this.origin.y) * inv;
  10108. if (max === -Infinity) {
  10109. max = Infinity;
  10110. }
  10111. if (min > max) {
  10112. temp = min;
  10113. min = max;
  10114. max = temp;
  10115. }
  10116. d = Math.max(min, d);
  10117. maxValue = Math.min(max, maxValue);
  10118. if (d > maxValue) {
  10119. return false;
  10120. }
  10121. }
  10122. if (Math.abs(this.direction.z) < 0.0000001) {
  10123. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  10124. return false;
  10125. }
  10126. }
  10127. else {
  10128. inv = 1.0 / this.direction.z;
  10129. min = (minimum.z - this.origin.z) * inv;
  10130. max = (maximum.z - this.origin.z) * inv;
  10131. if (max === -Infinity) {
  10132. max = Infinity;
  10133. }
  10134. if (min > max) {
  10135. temp = min;
  10136. min = max;
  10137. max = temp;
  10138. }
  10139. d = Math.max(min, d);
  10140. maxValue = Math.min(max, maxValue);
  10141. if (d > maxValue) {
  10142. return false;
  10143. }
  10144. }
  10145. return true;
  10146. };
  10147. Ray.prototype.intersectsBox = function (box) {
  10148. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  10149. };
  10150. Ray.prototype.intersectsSphere = function (sphere) {
  10151. var x = sphere.center.x - this.origin.x;
  10152. var y = sphere.center.y - this.origin.y;
  10153. var z = sphere.center.z - this.origin.z;
  10154. var pyth = (x * x) + (y * y) + (z * z);
  10155. var rr = sphere.radius * sphere.radius;
  10156. if (pyth <= rr) {
  10157. return true;
  10158. }
  10159. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  10160. if (dot < 0.0) {
  10161. return false;
  10162. }
  10163. var temp = pyth - (dot * dot);
  10164. return temp <= rr;
  10165. };
  10166. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  10167. if (!this._edge1) {
  10168. this._edge1 = BABYLON.Vector3.Zero();
  10169. this._edge2 = BABYLON.Vector3.Zero();
  10170. this._pvec = BABYLON.Vector3.Zero();
  10171. this._tvec = BABYLON.Vector3.Zero();
  10172. this._qvec = BABYLON.Vector3.Zero();
  10173. }
  10174. vertex1.subtractToRef(vertex0, this._edge1);
  10175. vertex2.subtractToRef(vertex0, this._edge2);
  10176. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  10177. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  10178. if (det === 0) {
  10179. return null;
  10180. }
  10181. var invdet = 1 / det;
  10182. this.origin.subtractToRef(vertex0, this._tvec);
  10183. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  10184. if (bu < 0 || bu > 1.0) {
  10185. return null;
  10186. }
  10187. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  10188. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  10189. if (bv < 0 || bu + bv > 1.0) {
  10190. return null;
  10191. }
  10192. //check if the distance is longer than the predefined length.
  10193. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  10194. if (distance > this.length) {
  10195. return null;
  10196. }
  10197. return new BABYLON.IntersectionInfo(bu, bv, distance);
  10198. };
  10199. Ray.prototype.intersectsPlane = function (plane) {
  10200. var distance;
  10201. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  10202. if (Math.abs(result1) < 9.99999997475243E-07) {
  10203. return null;
  10204. }
  10205. else {
  10206. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  10207. distance = (-plane.d - result2) / result1;
  10208. if (distance < 0.0) {
  10209. if (distance < -9.99999997475243E-07) {
  10210. return null;
  10211. }
  10212. else {
  10213. return 0;
  10214. }
  10215. }
  10216. return distance;
  10217. }
  10218. };
  10219. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  10220. var tm = BABYLON.Tmp.Matrix[0];
  10221. mesh.getWorldMatrix().invertToRef(tm);
  10222. if (this._tmpRay) {
  10223. Ray.TransformToRef(this, tm, this._tmpRay);
  10224. }
  10225. else {
  10226. this._tmpRay = Ray.Transform(this, tm);
  10227. }
  10228. return mesh.intersects(this._tmpRay, fastCheck);
  10229. };
  10230. Ray.prototype.show = function (scene, color) {
  10231. if (!this._show) {
  10232. this._renderFunction = this._render.bind(this);
  10233. this._show = true;
  10234. this._scene = scene;
  10235. this._renderPoints = [this.origin, this.origin.add(this.direction.scale(this.length))];
  10236. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  10237. this._scene.registerBeforeRender(this._renderFunction);
  10238. }
  10239. if (color) {
  10240. this._renderLine.color.copyFrom(color);
  10241. }
  10242. };
  10243. Ray.prototype.hide = function () {
  10244. if (this._show) {
  10245. this._show = false;
  10246. this._scene.unregisterBeforeRender(this._renderFunction);
  10247. }
  10248. if (this._renderLine) {
  10249. this._renderLine.dispose();
  10250. this._renderLine = null;
  10251. this._renderPoints = null;
  10252. }
  10253. };
  10254. Ray.prototype._render = function () {
  10255. var point = this._renderPoints[1];
  10256. point.copyFrom(this.direction);
  10257. point.scaleInPlace(this.length);
  10258. point.addInPlace(this.origin);
  10259. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  10260. };
  10261. /**
  10262. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  10263. * @param sega the first point of the segment to test the intersection against
  10264. * @param segb the second point of the segment to test the intersection against
  10265. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  10266. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  10267. */
  10268. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  10269. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  10270. var u = segb.subtract(sega);
  10271. var v = rsegb.subtract(this.origin);
  10272. var w = sega.subtract(this.origin);
  10273. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  10274. var b = BABYLON.Vector3.Dot(u, v);
  10275. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  10276. var d = BABYLON.Vector3.Dot(u, w);
  10277. var e = BABYLON.Vector3.Dot(v, w);
  10278. var D = a * c - b * b; // always >= 0
  10279. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  10280. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  10281. // compute the line parameters of the two closest points
  10282. if (D < Ray.smallnum) {
  10283. sN = 0.0; // force using point P0 on segment S1
  10284. sD = 1.0; // to prevent possible division by 0.0 later
  10285. tN = e;
  10286. tD = c;
  10287. }
  10288. else {
  10289. sN = (b * e - c * d);
  10290. tN = (a * e - b * d);
  10291. if (sN < 0.0) {
  10292. sN = 0.0;
  10293. tN = e;
  10294. tD = c;
  10295. }
  10296. else if (sN > sD) {
  10297. sN = sD;
  10298. tN = e + b;
  10299. tD = c;
  10300. }
  10301. }
  10302. if (tN < 0.0) {
  10303. tN = 0.0;
  10304. // recompute sc for this edge
  10305. if (-d < 0.0) {
  10306. sN = 0.0;
  10307. }
  10308. else if (-d > a)
  10309. sN = sD;
  10310. else {
  10311. sN = -d;
  10312. sD = a;
  10313. }
  10314. }
  10315. else if (tN > tD) {
  10316. tN = tD;
  10317. // recompute sc for this edge
  10318. if ((-d + b) < 0.0) {
  10319. sN = 0;
  10320. }
  10321. else if ((-d + b) > a) {
  10322. sN = sD;
  10323. }
  10324. else {
  10325. sN = (-d + b);
  10326. sD = a;
  10327. }
  10328. }
  10329. // finally do the division to get sc and tc
  10330. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  10331. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  10332. // get the difference of the two closest points
  10333. var qtc = v.multiplyByFloats(tc, tc, tc);
  10334. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  10335. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  10336. if (isIntersected) {
  10337. return qtc.length();
  10338. }
  10339. return -1;
  10340. };
  10341. // Statics
  10342. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  10343. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  10344. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  10345. var direction = end.subtract(start);
  10346. direction.normalize();
  10347. return new Ray(start, direction);
  10348. };
  10349. /**
  10350. * 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
  10351. * transformed to the given world matrix.
  10352. * @param origin The origin point
  10353. * @param end The end point
  10354. * @param world a matrix to transform the ray to. Default is the identity matrix.
  10355. */
  10356. Ray.CreateNewFromTo = function (origin, end, world) {
  10357. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  10358. var direction = end.subtract(origin);
  10359. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  10360. direction.normalize();
  10361. return Ray.Transform(new Ray(origin, direction, length), world);
  10362. };
  10363. Ray.Transform = function (ray, matrix) {
  10364. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  10365. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  10366. newDirection.normalize();
  10367. return new Ray(newOrigin, newDirection, ray.length);
  10368. };
  10369. Ray.TransformToRef = function (ray, matrix, result) {
  10370. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  10371. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  10372. ray.direction.normalize();
  10373. };
  10374. return Ray;
  10375. }());
  10376. Ray.smallnum = 0.00000001;
  10377. Ray.rayl = 10e8;
  10378. BABYLON.Ray = Ray;
  10379. })(BABYLON || (BABYLON = {}));
  10380. //# sourceMappingURL=babylon.ray.js.map
  10381. var BABYLON;
  10382. (function (BABYLON) {
  10383. var AbstractMesh = (function (_super) {
  10384. __extends(AbstractMesh, _super);
  10385. // Constructor
  10386. function AbstractMesh(name, scene) {
  10387. var _this = _super.call(this, name, scene) || this;
  10388. // Events
  10389. /**
  10390. * An event triggered when this mesh collides with another one
  10391. * @type {BABYLON.Observable}
  10392. */
  10393. _this.onCollideObservable = new BABYLON.Observable();
  10394. /**
  10395. * An event triggered when the collision's position changes
  10396. * @type {BABYLON.Observable}
  10397. */
  10398. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10399. /**
  10400. * An event triggered after the world matrix is updated
  10401. * @type {BABYLON.Observable}
  10402. */
  10403. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10404. // Properties
  10405. _this.definedFacingForward = true; // orientation for POV movement & rotation
  10406. _this.position = new BABYLON.Vector3(0, 0, 0);
  10407. _this._rotation = new BABYLON.Vector3(0, 0, 0);
  10408. _this._scaling = new BABYLON.Vector3(1, 1, 1);
  10409. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10410. _this.visibility = 1.0;
  10411. _this.alphaIndex = Number.MAX_VALUE;
  10412. _this.infiniteDistance = false;
  10413. _this.isVisible = true;
  10414. _this.isPickable = true;
  10415. _this.showBoundingBox = false;
  10416. _this.showSubMeshesBoundingBox = false;
  10417. _this.isBlocker = false;
  10418. _this.renderingGroupId = 0;
  10419. _this.receiveShadows = false;
  10420. _this.renderOutline = false;
  10421. _this.outlineColor = BABYLON.Color3.Red();
  10422. _this.outlineWidth = 0.02;
  10423. _this.renderOverlay = false;
  10424. _this.overlayColor = BABYLON.Color3.Red();
  10425. _this.overlayAlpha = 0.5;
  10426. _this.hasVertexAlpha = false;
  10427. _this.useVertexColors = true;
  10428. _this.applyFog = true;
  10429. _this.computeBonesUsingShaders = true;
  10430. _this.scalingDeterminant = 1;
  10431. _this.numBoneInfluencers = 4;
  10432. _this.useOctreeForRenderingSelection = true;
  10433. _this.useOctreeForPicking = true;
  10434. _this.useOctreeForCollisions = true;
  10435. _this.layerMask = 0x0FFFFFFF;
  10436. _this.alwaysSelectAsActiveMesh = false;
  10437. // Collisions
  10438. _this._checkCollisions = false;
  10439. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10440. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10441. _this._collider = new BABYLON.Collider();
  10442. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10443. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10444. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10445. // Edges
  10446. _this.edgesWidth = 1;
  10447. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10448. // Cache
  10449. _this._localWorld = BABYLON.Matrix.Zero();
  10450. _this._worldMatrix = BABYLON.Matrix.Zero();
  10451. _this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10452. _this._absolutePosition = BABYLON.Vector3.Zero();
  10453. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10454. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10455. _this._isDirty = false;
  10456. _this._pivotMatrix = BABYLON.Matrix.Identity();
  10457. _this._isDisposed = false;
  10458. _this._renderId = 0;
  10459. _this._intersectionsInProgress = new Array();
  10460. _this._isWorldMatrixFrozen = false;
  10461. _this._unIndexed = false;
  10462. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10463. if (collidedMesh === void 0) { collidedMesh = null; }
  10464. //TODO move this to the collision coordinator!
  10465. if (_this.getScene().workerCollisions)
  10466. newPosition.multiplyInPlace(_this._collider.radius);
  10467. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10468. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10469. _this.position.addInPlace(_this._diffPositionForCollisions);
  10470. }
  10471. if (collidedMesh) {
  10472. _this.onCollideObservable.notifyObservers(collidedMesh);
  10473. }
  10474. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10475. };
  10476. scene.addMesh(_this);
  10477. return _this;
  10478. }
  10479. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10480. get: function () {
  10481. return AbstractMesh._BILLBOARDMODE_NONE;
  10482. },
  10483. enumerable: true,
  10484. configurable: true
  10485. });
  10486. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10487. get: function () {
  10488. return AbstractMesh._BILLBOARDMODE_X;
  10489. },
  10490. enumerable: true,
  10491. configurable: true
  10492. });
  10493. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10494. get: function () {
  10495. return AbstractMesh._BILLBOARDMODE_Y;
  10496. },
  10497. enumerable: true,
  10498. configurable: true
  10499. });
  10500. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10501. get: function () {
  10502. return AbstractMesh._BILLBOARDMODE_Z;
  10503. },
  10504. enumerable: true,
  10505. configurable: true
  10506. });
  10507. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10508. get: function () {
  10509. return AbstractMesh._BILLBOARDMODE_ALL;
  10510. },
  10511. enumerable: true,
  10512. configurable: true
  10513. });
  10514. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10515. set: function (callback) {
  10516. if (this._onCollideObserver) {
  10517. this.onCollideObservable.remove(this._onCollideObserver);
  10518. }
  10519. this._onCollideObserver = this.onCollideObservable.add(callback);
  10520. },
  10521. enumerable: true,
  10522. configurable: true
  10523. });
  10524. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10525. set: function (callback) {
  10526. if (this._onCollisionPositionChangeObserver) {
  10527. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10528. }
  10529. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10530. },
  10531. enumerable: true,
  10532. configurable: true
  10533. });
  10534. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10535. get: function () {
  10536. return this._skeleton;
  10537. },
  10538. set: function (value) {
  10539. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10540. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10541. }
  10542. if (value && value.needInitialSkinMatrix) {
  10543. value._registerMeshWithPoseMatrix(this);
  10544. }
  10545. this._skeleton = value;
  10546. if (!this._skeleton) {
  10547. this._bonesTransformMatrices = null;
  10548. }
  10549. },
  10550. enumerable: true,
  10551. configurable: true
  10552. });
  10553. AbstractMesh.prototype.getClassName = function () {
  10554. return "AbstractMesh";
  10555. };
  10556. /**
  10557. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10558. */
  10559. AbstractMesh.prototype.toString = function (fullDetails) {
  10560. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10561. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10562. if (this._skeleton) {
  10563. ret += ", skeleton: " + this._skeleton.name;
  10564. }
  10565. if (fullDetails) {
  10566. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10567. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10568. }
  10569. return ret;
  10570. };
  10571. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  10572. /**
  10573. * Getting the rotation object.
  10574. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  10575. */
  10576. get: function () {
  10577. return this._rotation;
  10578. },
  10579. set: function (newRotation) {
  10580. this._rotation = newRotation;
  10581. },
  10582. enumerable: true,
  10583. configurable: true
  10584. });
  10585. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  10586. get: function () {
  10587. return this._scaling;
  10588. },
  10589. set: function (newScaling) {
  10590. this._scaling = newScaling;
  10591. if (this.physicsImpostor) {
  10592. this.physicsImpostor.forceUpdate();
  10593. }
  10594. },
  10595. enumerable: true,
  10596. configurable: true
  10597. });
  10598. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  10599. get: function () {
  10600. return this._rotationQuaternion;
  10601. },
  10602. set: function (quaternion) {
  10603. this._rotationQuaternion = quaternion;
  10604. //reset the rotation vector.
  10605. if (quaternion && this.rotation.length()) {
  10606. this.rotation.copyFromFloats(0, 0, 0);
  10607. }
  10608. },
  10609. enumerable: true,
  10610. configurable: true
  10611. });
  10612. // Methods
  10613. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  10614. this._poseMatrix.copyFrom(matrix);
  10615. };
  10616. AbstractMesh.prototype.getPoseMatrix = function () {
  10617. return this._poseMatrix;
  10618. };
  10619. AbstractMesh.prototype.disableEdgesRendering = function () {
  10620. if (this._edgesRenderer !== undefined) {
  10621. this._edgesRenderer.dispose();
  10622. this._edgesRenderer = undefined;
  10623. }
  10624. };
  10625. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  10626. if (epsilon === void 0) { epsilon = 0.95; }
  10627. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  10628. this.disableEdgesRendering();
  10629. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  10630. };
  10631. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10632. get: function () {
  10633. return false;
  10634. },
  10635. enumerable: true,
  10636. configurable: true
  10637. });
  10638. AbstractMesh.prototype.getLOD = function (camera) {
  10639. return this;
  10640. };
  10641. AbstractMesh.prototype.getTotalVertices = function () {
  10642. return 0;
  10643. };
  10644. AbstractMesh.prototype.getIndices = function () {
  10645. return null;
  10646. };
  10647. AbstractMesh.prototype.getVerticesData = function (kind) {
  10648. return null;
  10649. };
  10650. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10651. return false;
  10652. };
  10653. AbstractMesh.prototype.getBoundingInfo = function () {
  10654. if (this._masterMesh) {
  10655. return this._masterMesh.getBoundingInfo();
  10656. }
  10657. if (!this._boundingInfo) {
  10658. this._updateBoundingInfo();
  10659. }
  10660. return this._boundingInfo;
  10661. };
  10662. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10663. this._boundingInfo = boundingInfo;
  10664. };
  10665. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10666. get: function () {
  10667. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10668. },
  10669. enumerable: true,
  10670. configurable: true
  10671. });
  10672. AbstractMesh.prototype._preActivate = function () {
  10673. };
  10674. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10675. };
  10676. AbstractMesh.prototype._activate = function (renderId) {
  10677. this._renderId = renderId;
  10678. };
  10679. AbstractMesh.prototype.getWorldMatrix = function () {
  10680. if (this._masterMesh) {
  10681. return this._masterMesh.getWorldMatrix();
  10682. }
  10683. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10684. this.computeWorldMatrix();
  10685. }
  10686. return this._worldMatrix;
  10687. };
  10688. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10689. get: function () {
  10690. return this._worldMatrix;
  10691. },
  10692. enumerable: true,
  10693. configurable: true
  10694. });
  10695. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10696. get: function () {
  10697. return this._absolutePosition;
  10698. },
  10699. enumerable: true,
  10700. configurable: true
  10701. });
  10702. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10703. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10704. this.computeWorldMatrix(true);
  10705. this._isWorldMatrixFrozen = true;
  10706. };
  10707. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10708. this._isWorldMatrixFrozen = false;
  10709. this.computeWorldMatrix(true);
  10710. };
  10711. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10712. get: function () {
  10713. return this._isWorldMatrixFrozen;
  10714. },
  10715. enumerable: true,
  10716. configurable: true
  10717. });
  10718. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10719. axis.normalize();
  10720. if (!this.rotationQuaternion) {
  10721. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10722. this.rotation = BABYLON.Vector3.Zero();
  10723. }
  10724. var rotationQuaternion;
  10725. if (!space || space === BABYLON.Space.LOCAL) {
  10726. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10727. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  10728. }
  10729. else {
  10730. if (this.parent) {
  10731. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10732. invertParentWorldMatrix.invert();
  10733. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10734. }
  10735. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10736. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  10737. }
  10738. };
  10739. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10740. var displacementVector = axis.scale(distance);
  10741. if (!space || space === BABYLON.Space.LOCAL) {
  10742. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10743. this.setPositionWithLocalVector(tempV3);
  10744. }
  10745. else {
  10746. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10747. }
  10748. };
  10749. AbstractMesh.prototype.getAbsolutePosition = function () {
  10750. this.computeWorldMatrix();
  10751. return this._absolutePosition;
  10752. };
  10753. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10754. if (!absolutePosition) {
  10755. return;
  10756. }
  10757. var absolutePositionX;
  10758. var absolutePositionY;
  10759. var absolutePositionZ;
  10760. if (absolutePosition.x === undefined) {
  10761. if (arguments.length < 3) {
  10762. return;
  10763. }
  10764. absolutePositionX = arguments[0];
  10765. absolutePositionY = arguments[1];
  10766. absolutePositionZ = arguments[2];
  10767. }
  10768. else {
  10769. absolutePositionX = absolutePosition.x;
  10770. absolutePositionY = absolutePosition.y;
  10771. absolutePositionZ = absolutePosition.z;
  10772. }
  10773. if (this.parent) {
  10774. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10775. invertParentWorldMatrix.invert();
  10776. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10777. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10778. }
  10779. else {
  10780. this.position.x = absolutePositionX;
  10781. this.position.y = absolutePositionY;
  10782. this.position.z = absolutePositionZ;
  10783. }
  10784. };
  10785. // ================================== Point of View Movement =================================
  10786. /**
  10787. * Perform relative position change from the point of view of behind the front of the mesh.
  10788. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10789. * Supports definition of mesh facing forward or backward.
  10790. * @param {number} amountRight
  10791. * @param {number} amountUp
  10792. * @param {number} amountForward
  10793. */
  10794. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10795. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10796. };
  10797. /**
  10798. * Calculate relative position change from the point of view of behind the front of the mesh.
  10799. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10800. * Supports definition of mesh facing forward or backward.
  10801. * @param {number} amountRight
  10802. * @param {number} amountUp
  10803. * @param {number} amountForward
  10804. */
  10805. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10806. var rotMatrix = new BABYLON.Matrix();
  10807. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10808. rotQuaternion.toRotationMatrix(rotMatrix);
  10809. var translationDelta = BABYLON.Vector3.Zero();
  10810. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10811. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10812. return translationDelta;
  10813. };
  10814. // ================================== Point of View Rotation =================================
  10815. /**
  10816. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10817. * Supports definition of mesh facing forward or backward.
  10818. * @param {number} flipBack
  10819. * @param {number} twirlClockwise
  10820. * @param {number} tiltRight
  10821. */
  10822. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10823. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10824. };
  10825. /**
  10826. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10827. * Supports definition of mesh facing forward or backward.
  10828. * @param {number} flipBack
  10829. * @param {number} twirlClockwise
  10830. * @param {number} tiltRight
  10831. */
  10832. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10833. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10834. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10835. };
  10836. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10837. this._pivotMatrix = matrix;
  10838. this._cache.pivotMatrixUpdated = true;
  10839. };
  10840. AbstractMesh.prototype.getPivotMatrix = function () {
  10841. return this._pivotMatrix;
  10842. };
  10843. AbstractMesh.prototype._isSynchronized = function () {
  10844. if (this._isDirty) {
  10845. return false;
  10846. }
  10847. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10848. return false;
  10849. if (this._cache.pivotMatrixUpdated) {
  10850. return false;
  10851. }
  10852. if (this.infiniteDistance) {
  10853. return false;
  10854. }
  10855. if (!this._cache.position.equals(this.position))
  10856. return false;
  10857. if (this.rotationQuaternion) {
  10858. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10859. return false;
  10860. }
  10861. if (!this._cache.rotation.equals(this.rotation))
  10862. return false;
  10863. if (!this._cache.scaling.equals(this.scaling))
  10864. return false;
  10865. return true;
  10866. };
  10867. AbstractMesh.prototype._initCache = function () {
  10868. _super.prototype._initCache.call(this);
  10869. this._cache.localMatrixUpdated = false;
  10870. this._cache.position = BABYLON.Vector3.Zero();
  10871. this._cache.scaling = BABYLON.Vector3.Zero();
  10872. this._cache.rotation = BABYLON.Vector3.Zero();
  10873. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10874. this._cache.billboardMode = -1;
  10875. };
  10876. AbstractMesh.prototype.markAsDirty = function (property) {
  10877. if (property === "rotation") {
  10878. this.rotationQuaternion = null;
  10879. }
  10880. this._currentRenderId = Number.MAX_VALUE;
  10881. this._isDirty = true;
  10882. };
  10883. AbstractMesh.prototype._updateBoundingInfo = function () {
  10884. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10885. this._boundingInfo.update(this.worldMatrixFromCache);
  10886. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10887. };
  10888. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10889. if (!this.subMeshes) {
  10890. return;
  10891. }
  10892. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10893. var subMesh = this.subMeshes[subIndex];
  10894. if (!subMesh.IsGlobal) {
  10895. subMesh.updateBoundingInfo(matrix);
  10896. }
  10897. }
  10898. };
  10899. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10900. if (this._isWorldMatrixFrozen) {
  10901. return this._worldMatrix;
  10902. }
  10903. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10904. this._currentRenderId = this.getScene().getRenderId();
  10905. return this._worldMatrix;
  10906. }
  10907. this._cache.position.copyFrom(this.position);
  10908. this._cache.scaling.copyFrom(this.scaling);
  10909. this._cache.pivotMatrixUpdated = false;
  10910. this._cache.billboardMode = this.billboardMode;
  10911. this._currentRenderId = this.getScene().getRenderId();
  10912. this._isDirty = false;
  10913. // Scaling
  10914. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  10915. // Rotation
  10916. //rotate, if quaternion is set and rotation was used
  10917. if (this.rotationQuaternion) {
  10918. var len = this.rotation.length();
  10919. if (len) {
  10920. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  10921. this.rotation.copyFromFloats(0, 0, 0);
  10922. }
  10923. }
  10924. if (this.rotationQuaternion) {
  10925. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  10926. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10927. }
  10928. else {
  10929. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  10930. this._cache.rotation.copyFrom(this.rotation);
  10931. }
  10932. // Translation
  10933. if (this.infiniteDistance && !this.parent) {
  10934. var camera = this.getScene().activeCamera;
  10935. if (camera) {
  10936. var cameraWorldMatrix = camera.getWorldMatrix();
  10937. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10938. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  10939. }
  10940. }
  10941. else {
  10942. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  10943. }
  10944. // Composing transformations
  10945. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  10946. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  10947. // Billboarding
  10948. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10949. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  10950. var localPosition = BABYLON.Tmp.Vector3[0];
  10951. if (this.parent && this.parent.getWorldMatrix) {
  10952. this._markSyncedWithParent();
  10953. var parentMatrix;
  10954. if (this._meshToBoneReferal) {
  10955. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10956. parentMatrix = BABYLON.Tmp.Matrix[6];
  10957. }
  10958. else {
  10959. parentMatrix = this.parent.getWorldMatrix();
  10960. }
  10961. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  10962. localPosition = BABYLON.Tmp.Vector3[1];
  10963. }
  10964. var zero = this.getScene().activeCamera.globalPosition.clone();
  10965. if (this.parent && this.parent.position) {
  10966. localPosition.addInPlace(this.parent.position);
  10967. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  10968. }
  10969. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  10970. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10971. zero.x = localPosition.x + BABYLON.Epsilon;
  10972. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10973. zero.y = localPosition.y + BABYLON.Epsilon;
  10974. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10975. zero.z = localPosition.z + BABYLON.Epsilon;
  10976. }
  10977. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  10978. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  10979. BABYLON.Tmp.Matrix[3].invert();
  10980. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  10981. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  10982. }
  10983. // Local world
  10984. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  10985. // Parent
  10986. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10987. this._markSyncedWithParent();
  10988. if (this._meshToBoneReferal) {
  10989. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10990. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  10991. }
  10992. else {
  10993. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10994. }
  10995. }
  10996. else {
  10997. this._worldMatrix.copyFrom(this._localWorld);
  10998. }
  10999. // Bounding info
  11000. this._updateBoundingInfo();
  11001. // Absolute position
  11002. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  11003. // Callbacks
  11004. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  11005. if (!this._poseMatrix) {
  11006. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  11007. }
  11008. return this._worldMatrix;
  11009. };
  11010. /**
  11011. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  11012. * @param func: callback function to add
  11013. */
  11014. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  11015. this.onAfterWorldMatrixUpdateObservable.add(func);
  11016. };
  11017. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  11018. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  11019. };
  11020. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  11021. this.computeWorldMatrix();
  11022. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  11023. };
  11024. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  11025. this.computeWorldMatrix();
  11026. var invLocalWorldMatrix = this._localWorld.clone();
  11027. invLocalWorldMatrix.invert();
  11028. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  11029. };
  11030. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  11031. this.computeWorldMatrix(true);
  11032. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  11033. };
  11034. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  11035. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  11036. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  11037. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  11038. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  11039. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  11040. /// <returns>Mesh oriented towards targetMesh</returns>
  11041. if (yawCor === void 0) { yawCor = 0; }
  11042. if (pitchCor === void 0) { pitchCor = 0; }
  11043. if (rollCor === void 0) { rollCor = 0; }
  11044. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11045. var dv = AbstractMesh._lookAtVectorCache;
  11046. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  11047. targetPoint.subtractToRef(pos, dv);
  11048. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  11049. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  11050. var pitch = Math.atan2(dv.y, len);
  11051. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  11052. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  11053. };
  11054. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  11055. this._meshToBoneReferal = affectedMesh;
  11056. this.parent = bone;
  11057. if (bone.getWorldMatrix().determinant() < 0) {
  11058. this.scalingDeterminant *= -1;
  11059. }
  11060. };
  11061. AbstractMesh.prototype.detachFromBone = function () {
  11062. if (this.parent.getWorldMatrix().determinant() < 0) {
  11063. this.scalingDeterminant *= -1;
  11064. }
  11065. this._meshToBoneReferal = null;
  11066. this.parent = null;
  11067. };
  11068. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  11069. return this._boundingInfo.isInFrustum(frustumPlanes);
  11070. };
  11071. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11072. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  11073. ;
  11074. };
  11075. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  11076. if (!this._boundingInfo || !mesh._boundingInfo) {
  11077. return false;
  11078. }
  11079. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  11080. };
  11081. AbstractMesh.prototype.intersectsPoint = function (point) {
  11082. if (!this._boundingInfo) {
  11083. return false;
  11084. }
  11085. return this._boundingInfo.intersectsPoint(point);
  11086. };
  11087. // Physics
  11088. /**
  11089. * @Deprecated. Use new PhysicsImpostor instead.
  11090. * */
  11091. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  11092. //legacy support
  11093. if (impostor.impostor) {
  11094. options = impostor;
  11095. impostor = impostor.impostor;
  11096. }
  11097. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  11098. return this.physicsImpostor.physicsBody;
  11099. };
  11100. AbstractMesh.prototype.getPhysicsImpostor = function () {
  11101. return this.physicsImpostor;
  11102. };
  11103. /**
  11104. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  11105. */
  11106. AbstractMesh.prototype.getPhysicsMass = function () {
  11107. return this.physicsImpostor.getParam("mass");
  11108. };
  11109. /**
  11110. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  11111. */
  11112. AbstractMesh.prototype.getPhysicsFriction = function () {
  11113. return this.physicsImpostor.getParam("friction");
  11114. };
  11115. /**
  11116. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  11117. */
  11118. AbstractMesh.prototype.getPhysicsRestitution = function () {
  11119. return this.physicsImpostor.getParam("restitution");
  11120. };
  11121. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  11122. if (!camera) {
  11123. camera = this.getScene().activeCamera;
  11124. }
  11125. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  11126. };
  11127. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  11128. if (!camera) {
  11129. camera = this.getScene().activeCamera;
  11130. }
  11131. return this.absolutePosition.subtract(camera.position).length();
  11132. };
  11133. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  11134. if (!this.physicsImpostor) {
  11135. return;
  11136. }
  11137. this.physicsImpostor.applyImpulse(force, contactPoint);
  11138. };
  11139. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  11140. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  11141. return;
  11142. }
  11143. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  11144. mainPivot: pivot1,
  11145. connectedPivot: pivot2,
  11146. nativeParams: options
  11147. });
  11148. };
  11149. /**
  11150. * @Deprecated
  11151. */
  11152. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  11153. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  11154. this.updatePhysicsBody();
  11155. };
  11156. /**
  11157. * @Deprecated
  11158. * Calling this function is not needed anymore.
  11159. * The physics engine takes care of transofmration automatically.
  11160. */
  11161. AbstractMesh.prototype.updatePhysicsBody = function () {
  11162. //Unneeded
  11163. };
  11164. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  11165. // Collisions
  11166. get: function () {
  11167. return this._checkCollisions;
  11168. },
  11169. set: function (collisionEnabled) {
  11170. this._checkCollisions = collisionEnabled;
  11171. if (this.getScene().workerCollisions) {
  11172. this.getScene().collisionCoordinator.onMeshUpdated(this);
  11173. }
  11174. },
  11175. enumerable: true,
  11176. configurable: true
  11177. });
  11178. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  11179. var globalPosition = this.getAbsolutePosition();
  11180. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  11181. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  11182. this._collider.radius = this.ellipsoid;
  11183. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  11184. };
  11185. // Submeshes octree
  11186. /**
  11187. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  11188. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  11189. */
  11190. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  11191. if (maxCapacity === void 0) { maxCapacity = 64; }
  11192. if (maxDepth === void 0) { maxDepth = 2; }
  11193. if (!this._submeshesOctree) {
  11194. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  11195. }
  11196. this.computeWorldMatrix(true);
  11197. // Update octree
  11198. var bbox = this.getBoundingInfo().boundingBox;
  11199. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  11200. return this._submeshesOctree;
  11201. };
  11202. // Collisions
  11203. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  11204. this._generatePointsArray();
  11205. // Transformation
  11206. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  11207. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  11208. subMesh._lastColliderWorldVertices = [];
  11209. subMesh._trianglePlanes = [];
  11210. var start = subMesh.verticesStart;
  11211. var end = (subMesh.verticesStart + subMesh.verticesCount);
  11212. for (var i = start; i < end; i++) {
  11213. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  11214. }
  11215. }
  11216. // Collide
  11217. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  11218. if (collider.collisionFound) {
  11219. collider.collidedMesh = this;
  11220. }
  11221. };
  11222. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  11223. var subMeshes;
  11224. var len;
  11225. // Octrees
  11226. if (this._submeshesOctree && this.useOctreeForCollisions) {
  11227. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  11228. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  11229. len = intersections.length;
  11230. subMeshes = intersections.data;
  11231. }
  11232. else {
  11233. subMeshes = this.subMeshes;
  11234. len = subMeshes.length;
  11235. }
  11236. for (var index = 0; index < len; index++) {
  11237. var subMesh = subMeshes[index];
  11238. // Bounding test
  11239. if (len > 1 && !subMesh._checkCollision(collider))
  11240. continue;
  11241. this._collideForSubMesh(subMesh, transformMatrix, collider);
  11242. }
  11243. };
  11244. AbstractMesh.prototype._checkCollision = function (collider) {
  11245. // Bounding box test
  11246. if (!this._boundingInfo._checkCollision(collider))
  11247. return;
  11248. // Transformation matrix
  11249. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  11250. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  11251. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  11252. };
  11253. // Picking
  11254. AbstractMesh.prototype._generatePointsArray = function () {
  11255. return false;
  11256. };
  11257. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  11258. var pickingInfo = new BABYLON.PickingInfo();
  11259. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  11260. return pickingInfo;
  11261. }
  11262. if (!this._generatePointsArray()) {
  11263. return pickingInfo;
  11264. }
  11265. var intersectInfo = null;
  11266. // Octrees
  11267. var subMeshes;
  11268. var len;
  11269. if (this._submeshesOctree && this.useOctreeForPicking) {
  11270. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  11271. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  11272. len = intersections.length;
  11273. subMeshes = intersections.data;
  11274. }
  11275. else {
  11276. subMeshes = this.subMeshes;
  11277. len = subMeshes.length;
  11278. }
  11279. for (var index = 0; index < len; index++) {
  11280. var subMesh = subMeshes[index];
  11281. // Bounding test
  11282. if (len > 1 && !subMesh.canIntersects(ray))
  11283. continue;
  11284. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  11285. if (currentIntersectInfo) {
  11286. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11287. intersectInfo = currentIntersectInfo;
  11288. intersectInfo.subMeshId = index;
  11289. if (fastCheck) {
  11290. break;
  11291. }
  11292. }
  11293. }
  11294. }
  11295. if (intersectInfo) {
  11296. // Get picked point
  11297. var world = this.getWorldMatrix();
  11298. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  11299. var direction = ray.direction.clone();
  11300. direction = direction.scale(intersectInfo.distance);
  11301. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  11302. var pickedPoint = worldOrigin.add(worldDirection);
  11303. // Return result
  11304. pickingInfo.hit = true;
  11305. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  11306. pickingInfo.pickedPoint = pickedPoint;
  11307. pickingInfo.pickedMesh = this;
  11308. pickingInfo.bu = intersectInfo.bu;
  11309. pickingInfo.bv = intersectInfo.bv;
  11310. pickingInfo.faceId = intersectInfo.faceId;
  11311. pickingInfo.subMeshId = intersectInfo.subMeshId;
  11312. return pickingInfo;
  11313. }
  11314. return pickingInfo;
  11315. };
  11316. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11317. return null;
  11318. };
  11319. AbstractMesh.prototype.releaseSubMeshes = function () {
  11320. if (this.subMeshes) {
  11321. while (this.subMeshes.length) {
  11322. this.subMeshes[0].dispose();
  11323. }
  11324. }
  11325. else {
  11326. this.subMeshes = new Array();
  11327. }
  11328. };
  11329. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  11330. var _this = this;
  11331. var index;
  11332. // Action manager
  11333. if (this.actionManager) {
  11334. this.actionManager.dispose();
  11335. this.actionManager = null;
  11336. }
  11337. // Skeleton
  11338. this.skeleton = null;
  11339. // Animations
  11340. this.getScene().stopAnimation(this);
  11341. // Physics
  11342. if (this.physicsImpostor) {
  11343. this.physicsImpostor.dispose();
  11344. }
  11345. // Intersections in progress
  11346. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  11347. var other = this._intersectionsInProgress[index];
  11348. var pos = other._intersectionsInProgress.indexOf(this);
  11349. other._intersectionsInProgress.splice(pos, 1);
  11350. }
  11351. this._intersectionsInProgress = [];
  11352. // Lights
  11353. var lights = this.getScene().lights;
  11354. lights.forEach(function (light) {
  11355. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  11356. if (meshIndex !== -1) {
  11357. light.includedOnlyMeshes.splice(meshIndex, 1);
  11358. }
  11359. meshIndex = light.excludedMeshes.indexOf(_this);
  11360. if (meshIndex !== -1) {
  11361. light.excludedMeshes.splice(meshIndex, 1);
  11362. }
  11363. // Shadow generators
  11364. var generator = light.getShadowGenerator();
  11365. if (generator) {
  11366. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  11367. if (meshIndex !== -1) {
  11368. generator.getShadowMap().renderList.splice(meshIndex, 1);
  11369. }
  11370. }
  11371. });
  11372. // Edges
  11373. if (this._edgesRenderer) {
  11374. this._edgesRenderer.dispose();
  11375. this._edgesRenderer = null;
  11376. }
  11377. // SubMeshes
  11378. this.releaseSubMeshes();
  11379. // Engine
  11380. this.getScene().getEngine().unbindAllAttributes();
  11381. this.getScene().getEngine().wipeCaches();
  11382. // Remove from scene
  11383. this.getScene().removeMesh(this);
  11384. if (!doNotRecurse) {
  11385. // Particles
  11386. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  11387. if (this.getScene().particleSystems[index].emitter === this) {
  11388. this.getScene().particleSystems[index].dispose();
  11389. index--;
  11390. }
  11391. }
  11392. // Children
  11393. var objects = this.getDescendants(true);
  11394. for (index = 0; index < objects.length; index++) {
  11395. objects[index].dispose();
  11396. }
  11397. }
  11398. else {
  11399. var childMeshes = this.getChildMeshes(true);
  11400. for (index = 0; index < childMeshes.length; index++) {
  11401. var child = childMeshes[index];
  11402. child.parent = null;
  11403. child.computeWorldMatrix(true);
  11404. }
  11405. }
  11406. this.onAfterWorldMatrixUpdateObservable.clear();
  11407. this.onCollideObservable.clear();
  11408. this.onCollisionPositionChangeObservable.clear();
  11409. this._isDisposed = true;
  11410. _super.prototype.dispose.call(this);
  11411. };
  11412. AbstractMesh.prototype.getDirection = function (localAxis) {
  11413. var result = BABYLON.Vector3.Zero();
  11414. this.getDirectionToRef(localAxis, result);
  11415. return result;
  11416. };
  11417. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  11418. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  11419. };
  11420. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  11421. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11422. if (this.getScene().getRenderId() == 0) {
  11423. this.computeWorldMatrix(true);
  11424. }
  11425. var wm = this.getWorldMatrix();
  11426. if (space == BABYLON.Space.WORLD) {
  11427. var tmat = BABYLON.Tmp.Matrix[0];
  11428. wm.invertToRef(tmat);
  11429. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  11430. }
  11431. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  11432. this._pivotMatrix.m[12] = -point.x;
  11433. this._pivotMatrix.m[13] = -point.y;
  11434. this._pivotMatrix.m[14] = -point.z;
  11435. this._cache.pivotMatrixUpdated = true;
  11436. };
  11437. AbstractMesh.prototype.getPivotPoint = function () {
  11438. var point = BABYLON.Vector3.Zero();
  11439. this.getPivotPointToRef(point);
  11440. return point;
  11441. };
  11442. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  11443. result.x = -this._pivotMatrix.m[12];
  11444. result.y = -this._pivotMatrix.m[13];
  11445. result.z = -this._pivotMatrix.m[14];
  11446. };
  11447. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  11448. var point = BABYLON.Vector3.Zero();
  11449. this.getAbsolutePivotPointToRef(point);
  11450. return point;
  11451. };
  11452. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  11453. result.x = this._pivotMatrix.m[12];
  11454. result.y = this._pivotMatrix.m[13];
  11455. result.z = this._pivotMatrix.m[14];
  11456. this.getPivotPointToRef(result);
  11457. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  11458. };
  11459. return AbstractMesh;
  11460. }(BABYLON.Node));
  11461. // Statics
  11462. AbstractMesh._BILLBOARDMODE_NONE = 0;
  11463. AbstractMesh._BILLBOARDMODE_X = 1;
  11464. AbstractMesh._BILLBOARDMODE_Y = 2;
  11465. AbstractMesh._BILLBOARDMODE_Z = 4;
  11466. AbstractMesh._BILLBOARDMODE_ALL = 7;
  11467. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  11468. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  11469. BABYLON.AbstractMesh = AbstractMesh;
  11470. })(BABYLON || (BABYLON = {}));
  11471. //# sourceMappingURL=babylon.abstractMesh.js.map
  11472. var BABYLON;
  11473. (function (BABYLON) {
  11474. var Light = (function (_super) {
  11475. __extends(Light, _super);
  11476. function Light(name, scene) {
  11477. var _this = _super.call(this, name, scene) || this;
  11478. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  11479. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  11480. _this.intensity = 1.0;
  11481. _this.range = Number.MAX_VALUE;
  11482. _this.includeOnlyWithLayerMask = 0;
  11483. _this.includedOnlyMeshes = new Array();
  11484. _this.excludedMeshes = new Array();
  11485. _this.excludeWithLayerMask = 0;
  11486. _this.lightmapMode = 0;
  11487. // PBR Properties.
  11488. _this.radius = 0.00001;
  11489. _this._excludedMeshesIds = new Array();
  11490. _this._includedOnlyMeshesIds = new Array();
  11491. scene.addLight(_this);
  11492. return _this;
  11493. }
  11494. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  11495. /**
  11496. * If every light affecting the material is in this lightmapMode,
  11497. * material.lightmapTexture adds or multiplies
  11498. * (depends on material.useLightmapAsShadowmap)
  11499. * after every other light calculations.
  11500. */
  11501. get: function () {
  11502. return Light._LIGHTMAP_DEFAULT;
  11503. },
  11504. enumerable: true,
  11505. configurable: true
  11506. });
  11507. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  11508. /**
  11509. * material.lightmapTexture as only diffuse lighting from this light
  11510. * adds pnly specular lighting from this light
  11511. * adds dynamic shadows
  11512. */
  11513. get: function () {
  11514. return Light._LIGHTMAP_SPECULAR;
  11515. },
  11516. enumerable: true,
  11517. configurable: true
  11518. });
  11519. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  11520. /**
  11521. * material.lightmapTexture as only lighting
  11522. * no light calculation from this light
  11523. * only adds dynamic shadows from this light
  11524. */
  11525. get: function () {
  11526. return Light._LIGHTMAP_SHADOWSONLY;
  11527. },
  11528. enumerable: true,
  11529. configurable: true
  11530. });
  11531. Light.prototype.getClassName = function () {
  11532. return "Light";
  11533. };
  11534. /**
  11535. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11536. */
  11537. Light.prototype.toString = function (fullDetails) {
  11538. var ret = "Name: " + this.name;
  11539. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  11540. if (this.animations) {
  11541. for (var i = 0; i < this.animations.length; i++) {
  11542. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11543. }
  11544. }
  11545. if (fullDetails) {
  11546. }
  11547. return ret;
  11548. };
  11549. Light.prototype.getShadowGenerator = function () {
  11550. return this._shadowGenerator;
  11551. };
  11552. Light.prototype.getAbsolutePosition = function () {
  11553. return BABYLON.Vector3.Zero();
  11554. };
  11555. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  11556. };
  11557. Light.prototype._getWorldMatrix = function () {
  11558. return BABYLON.Matrix.Identity();
  11559. };
  11560. Light.prototype.canAffectMesh = function (mesh) {
  11561. if (!mesh) {
  11562. return true;
  11563. }
  11564. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  11565. return false;
  11566. }
  11567. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  11568. return false;
  11569. }
  11570. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  11571. return false;
  11572. }
  11573. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  11574. return false;
  11575. }
  11576. return true;
  11577. };
  11578. Light.prototype.getWorldMatrix = function () {
  11579. this._currentRenderId = this.getScene().getRenderId();
  11580. var worldMatrix = this._getWorldMatrix();
  11581. if (this.parent && this.parent.getWorldMatrix) {
  11582. if (!this._parentedWorldMatrix) {
  11583. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  11584. }
  11585. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  11586. this._markSyncedWithParent();
  11587. return this._parentedWorldMatrix;
  11588. }
  11589. return worldMatrix;
  11590. };
  11591. Light.prototype.dispose = function () {
  11592. if (this._shadowGenerator) {
  11593. this._shadowGenerator.dispose();
  11594. this._shadowGenerator = null;
  11595. }
  11596. // Animations
  11597. this.getScene().stopAnimation(this);
  11598. // Remove from scene
  11599. this.getScene().removeLight(this);
  11600. _super.prototype.dispose.call(this);
  11601. };
  11602. Light.prototype.getTypeID = function () {
  11603. return 0;
  11604. };
  11605. Light.prototype.clone = function (name) {
  11606. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  11607. };
  11608. Light.prototype.serialize = function () {
  11609. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11610. // Type
  11611. serializationObject.type = this.getTypeID();
  11612. // Parent
  11613. if (this.parent) {
  11614. serializationObject.parentId = this.parent.id;
  11615. }
  11616. // Inclusion / exclusions
  11617. if (this.excludedMeshes.length > 0) {
  11618. serializationObject.excludedMeshesIds = [];
  11619. this.excludedMeshes.forEach(function (mesh) {
  11620. serializationObject.excludedMeshesIds.push(mesh.id);
  11621. });
  11622. }
  11623. if (this.includedOnlyMeshes.length > 0) {
  11624. serializationObject.includedOnlyMeshesIds = [];
  11625. this.includedOnlyMeshes.forEach(function (mesh) {
  11626. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  11627. });
  11628. }
  11629. // Animations
  11630. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11631. serializationObject.ranges = this.serializeAnimationRanges();
  11632. return serializationObject;
  11633. };
  11634. Light.GetConstructorFromName = function (type, name, scene) {
  11635. switch (type) {
  11636. case 0:
  11637. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  11638. case 1:
  11639. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  11640. case 2:
  11641. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  11642. case 3:
  11643. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  11644. }
  11645. };
  11646. Light.Parse = function (parsedLight, scene) {
  11647. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  11648. // Inclusion / exclusions
  11649. if (parsedLight.excludedMeshesIds) {
  11650. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  11651. }
  11652. if (parsedLight.includedOnlyMeshesIds) {
  11653. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  11654. }
  11655. // Parent
  11656. if (parsedLight.parentId) {
  11657. light._waitingParentId = parsedLight.parentId;
  11658. }
  11659. // Animations
  11660. if (parsedLight.animations) {
  11661. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  11662. var parsedAnimation = parsedLight.animations[animationIndex];
  11663. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11664. }
  11665. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  11666. }
  11667. if (parsedLight.autoAnimate) {
  11668. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  11669. }
  11670. return light;
  11671. };
  11672. return Light;
  11673. }(BABYLON.Node));
  11674. //lightmapMode Consts
  11675. Light._LIGHTMAP_DEFAULT = 0;
  11676. Light._LIGHTMAP_SPECULAR = 1;
  11677. Light._LIGHTMAP_SHADOWSONLY = 2;
  11678. __decorate([
  11679. BABYLON.serializeAsColor3()
  11680. ], Light.prototype, "diffuse", void 0);
  11681. __decorate([
  11682. BABYLON.serializeAsColor3()
  11683. ], Light.prototype, "specular", void 0);
  11684. __decorate([
  11685. BABYLON.serialize()
  11686. ], Light.prototype, "intensity", void 0);
  11687. __decorate([
  11688. BABYLON.serialize()
  11689. ], Light.prototype, "range", void 0);
  11690. __decorate([
  11691. BABYLON.serialize()
  11692. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  11693. __decorate([
  11694. BABYLON.serialize()
  11695. ], Light.prototype, "excludeWithLayerMask", void 0);
  11696. __decorate([
  11697. BABYLON.serialize()
  11698. ], Light.prototype, "lightmapMode", void 0);
  11699. __decorate([
  11700. BABYLON.serialize()
  11701. ], Light.prototype, "radius", void 0);
  11702. BABYLON.Light = Light;
  11703. })(BABYLON || (BABYLON = {}));
  11704. //# sourceMappingURL=babylon.light.js.map
  11705. var BABYLON;
  11706. (function (BABYLON) {
  11707. var PointLight = (function (_super) {
  11708. __extends(PointLight, _super);
  11709. function PointLight(name, position, scene) {
  11710. var _this = _super.call(this, name, scene) || this;
  11711. _this.position = position;
  11712. return _this;
  11713. }
  11714. PointLight.prototype.getClassName = function () {
  11715. return "PointLight";
  11716. };
  11717. PointLight.prototype.getAbsolutePosition = function () {
  11718. return this.transformedPosition ? this.transformedPosition : this.position;
  11719. };
  11720. PointLight.prototype.computeTransformedPosition = function () {
  11721. if (this.parent && this.parent.getWorldMatrix) {
  11722. if (!this.transformedPosition) {
  11723. this.transformedPosition = BABYLON.Vector3.Zero();
  11724. }
  11725. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11726. return true;
  11727. }
  11728. return false;
  11729. };
  11730. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  11731. if (this.parent && this.parent.getWorldMatrix) {
  11732. this.computeTransformedPosition();
  11733. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  11734. return;
  11735. }
  11736. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  11737. };
  11738. PointLight.prototype.needCube = function () {
  11739. return true;
  11740. };
  11741. PointLight.prototype.supportsVSM = function () {
  11742. return false;
  11743. };
  11744. PointLight.prototype.needRefreshPerFrame = function () {
  11745. return false;
  11746. };
  11747. PointLight.prototype.getShadowDirection = function (faceIndex) {
  11748. switch (faceIndex) {
  11749. case 0:
  11750. return new BABYLON.Vector3(1, 0, 0);
  11751. case 1:
  11752. return new BABYLON.Vector3(-1, 0, 0);
  11753. case 2:
  11754. return new BABYLON.Vector3(0, -1, 0);
  11755. case 3:
  11756. return new BABYLON.Vector3(0, 1, 0);
  11757. case 4:
  11758. return new BABYLON.Vector3(0, 0, 1);
  11759. case 5:
  11760. return new BABYLON.Vector3(0, 0, -1);
  11761. }
  11762. return BABYLON.Vector3.Zero();
  11763. };
  11764. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11765. var activeCamera = this.getScene().activeCamera;
  11766. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11767. };
  11768. PointLight.prototype._getWorldMatrix = function () {
  11769. if (!this._worldMatrix) {
  11770. this._worldMatrix = BABYLON.Matrix.Identity();
  11771. }
  11772. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11773. return this._worldMatrix;
  11774. };
  11775. PointLight.prototype.getTypeID = function () {
  11776. return 0;
  11777. };
  11778. return PointLight;
  11779. }(BABYLON.Light));
  11780. __decorate([
  11781. BABYLON.serializeAsVector3()
  11782. ], PointLight.prototype, "position", void 0);
  11783. BABYLON.PointLight = PointLight;
  11784. })(BABYLON || (BABYLON = {}));
  11785. //# sourceMappingURL=babylon.pointLight.js.map
  11786. var BABYLON;
  11787. (function (BABYLON) {
  11788. var SpotLight = (function (_super) {
  11789. __extends(SpotLight, _super);
  11790. function SpotLight(name, position, direction, angle, exponent, scene) {
  11791. var _this = _super.call(this, name, scene) || this;
  11792. _this.position = position;
  11793. _this.direction = direction;
  11794. _this.angle = angle;
  11795. _this.exponent = exponent;
  11796. return _this;
  11797. }
  11798. SpotLight.prototype.getClassName = function () {
  11799. return "SpotLight";
  11800. };
  11801. SpotLight.prototype.getAbsolutePosition = function () {
  11802. return this.transformedPosition ? this.transformedPosition : this.position;
  11803. };
  11804. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11805. var activeCamera = this.getScene().activeCamera;
  11806. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11807. };
  11808. SpotLight.prototype.needCube = function () {
  11809. return false;
  11810. };
  11811. SpotLight.prototype.supportsVSM = function () {
  11812. return true;
  11813. };
  11814. SpotLight.prototype.needRefreshPerFrame = function () {
  11815. return false;
  11816. };
  11817. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  11818. return this.direction;
  11819. };
  11820. SpotLight.prototype.setDirectionToTarget = function (target) {
  11821. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11822. return this.direction;
  11823. };
  11824. SpotLight.prototype.computeTransformedPosition = function () {
  11825. if (this.parent && this.parent.getWorldMatrix) {
  11826. if (!this.transformedPosition) {
  11827. this.transformedPosition = BABYLON.Vector3.Zero();
  11828. }
  11829. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11830. return true;
  11831. }
  11832. return false;
  11833. };
  11834. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  11835. var normalizeDirection;
  11836. if (this.parent && this.parent.getWorldMatrix) {
  11837. if (!this._transformedDirection) {
  11838. this._transformedDirection = BABYLON.Vector3.Zero();
  11839. }
  11840. this.computeTransformedPosition();
  11841. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11842. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  11843. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  11844. }
  11845. else {
  11846. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  11847. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11848. }
  11849. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  11850. };
  11851. SpotLight.prototype._getWorldMatrix = function () {
  11852. if (!this._worldMatrix) {
  11853. this._worldMatrix = BABYLON.Matrix.Identity();
  11854. }
  11855. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11856. return this._worldMatrix;
  11857. };
  11858. SpotLight.prototype.getTypeID = function () {
  11859. return 2;
  11860. };
  11861. SpotLight.prototype.getRotation = function () {
  11862. this.direction.normalize();
  11863. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  11864. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  11865. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  11866. };
  11867. return SpotLight;
  11868. }(BABYLON.Light));
  11869. __decorate([
  11870. BABYLON.serializeAsVector3()
  11871. ], SpotLight.prototype, "position", void 0);
  11872. __decorate([
  11873. BABYLON.serializeAsVector3()
  11874. ], SpotLight.prototype, "direction", void 0);
  11875. __decorate([
  11876. BABYLON.serialize()
  11877. ], SpotLight.prototype, "angle", void 0);
  11878. __decorate([
  11879. BABYLON.serialize()
  11880. ], SpotLight.prototype, "exponent", void 0);
  11881. BABYLON.SpotLight = SpotLight;
  11882. })(BABYLON || (BABYLON = {}));
  11883. //# sourceMappingURL=babylon.spotLight.js.map
  11884. var BABYLON;
  11885. (function (BABYLON) {
  11886. var HemisphericLight = (function (_super) {
  11887. __extends(HemisphericLight, _super);
  11888. function HemisphericLight(name, direction, scene) {
  11889. var _this = _super.call(this, name, scene) || this;
  11890. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  11891. _this.direction = direction;
  11892. return _this;
  11893. }
  11894. HemisphericLight.prototype.getClassName = function () {
  11895. return "HemisphericLight";
  11896. };
  11897. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  11898. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  11899. return this.direction;
  11900. };
  11901. HemisphericLight.prototype.getShadowGenerator = function () {
  11902. return null;
  11903. };
  11904. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  11905. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11906. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  11907. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  11908. };
  11909. HemisphericLight.prototype._getWorldMatrix = function () {
  11910. if (!this._worldMatrix) {
  11911. this._worldMatrix = BABYLON.Matrix.Identity();
  11912. }
  11913. return this._worldMatrix;
  11914. };
  11915. HemisphericLight.prototype.getTypeID = function () {
  11916. return 3;
  11917. };
  11918. return HemisphericLight;
  11919. }(BABYLON.Light));
  11920. __decorate([
  11921. BABYLON.serializeAsColor3()
  11922. ], HemisphericLight.prototype, "groundColor", void 0);
  11923. __decorate([
  11924. BABYLON.serializeAsVector3()
  11925. ], HemisphericLight.prototype, "direction", void 0);
  11926. BABYLON.HemisphericLight = HemisphericLight;
  11927. })(BABYLON || (BABYLON = {}));
  11928. //# sourceMappingURL=babylon.hemisphericLight.js.map
  11929. var BABYLON;
  11930. (function (BABYLON) {
  11931. var DirectionalLight = (function (_super) {
  11932. __extends(DirectionalLight, _super);
  11933. function DirectionalLight(name, direction, scene) {
  11934. var _this = _super.call(this, name, scene) || this;
  11935. _this.shadowOrthoScale = 0.5;
  11936. _this.autoUpdateExtends = true;
  11937. // Cache
  11938. _this._orthoLeft = Number.MAX_VALUE;
  11939. _this._orthoRight = Number.MIN_VALUE;
  11940. _this._orthoTop = Number.MIN_VALUE;
  11941. _this._orthoBottom = Number.MAX_VALUE;
  11942. _this.position = direction.scale(-1);
  11943. _this.direction = direction;
  11944. return _this;
  11945. }
  11946. DirectionalLight.prototype.getClassName = function () {
  11947. return "DirectionalLight";
  11948. };
  11949. DirectionalLight.prototype.getAbsolutePosition = function () {
  11950. return this.transformedPosition ? this.transformedPosition : this.position;
  11951. };
  11952. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  11953. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11954. return this.direction;
  11955. };
  11956. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11957. var activeCamera = this.getScene().activeCamera;
  11958. // Check extends
  11959. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  11960. var tempVector3 = BABYLON.Vector3.Zero();
  11961. this._orthoLeft = Number.MAX_VALUE;
  11962. this._orthoRight = Number.MIN_VALUE;
  11963. this._orthoTop = Number.MIN_VALUE;
  11964. this._orthoBottom = Number.MAX_VALUE;
  11965. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  11966. var mesh = renderList[meshIndex];
  11967. if (!mesh) {
  11968. continue;
  11969. }
  11970. var boundingInfo = mesh.getBoundingInfo();
  11971. if (!boundingInfo) {
  11972. continue;
  11973. }
  11974. var boundingBox = boundingInfo.boundingBox;
  11975. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  11976. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  11977. if (tempVector3.x < this._orthoLeft)
  11978. this._orthoLeft = tempVector3.x;
  11979. if (tempVector3.y < this._orthoBottom)
  11980. this._orthoBottom = tempVector3.y;
  11981. if (tempVector3.x > this._orthoRight)
  11982. this._orthoRight = tempVector3.x;
  11983. if (tempVector3.y > this._orthoTop)
  11984. this._orthoTop = tempVector3.y;
  11985. }
  11986. }
  11987. }
  11988. var xOffset = this._orthoRight - this._orthoLeft;
  11989. var yOffset = this._orthoTop - this._orthoBottom;
  11990. BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  11991. };
  11992. DirectionalLight.prototype.supportsVSM = function () {
  11993. return true;
  11994. };
  11995. DirectionalLight.prototype.needRefreshPerFrame = function () {
  11996. return true;
  11997. };
  11998. DirectionalLight.prototype.needCube = function () {
  11999. return false;
  12000. };
  12001. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  12002. return this.direction;
  12003. };
  12004. DirectionalLight.prototype.computeTransformedPosition = function () {
  12005. if (this.parent && this.parent.getWorldMatrix) {
  12006. if (!this.transformedPosition) {
  12007. this.transformedPosition = BABYLON.Vector3.Zero();
  12008. }
  12009. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  12010. return true;
  12011. }
  12012. return false;
  12013. };
  12014. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  12015. if (this.parent && this.parent.getWorldMatrix) {
  12016. if (!this._transformedDirection) {
  12017. this._transformedDirection = BABYLON.Vector3.Zero();
  12018. }
  12019. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  12020. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  12021. return;
  12022. }
  12023. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  12024. };
  12025. DirectionalLight.prototype._getWorldMatrix = function () {
  12026. if (!this._worldMatrix) {
  12027. this._worldMatrix = BABYLON.Matrix.Identity();
  12028. }
  12029. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  12030. return this._worldMatrix;
  12031. };
  12032. DirectionalLight.prototype.getTypeID = function () {
  12033. return 1;
  12034. };
  12035. return DirectionalLight;
  12036. }(BABYLON.Light));
  12037. __decorate([
  12038. BABYLON.serializeAsVector3()
  12039. ], DirectionalLight.prototype, "position", void 0);
  12040. __decorate([
  12041. BABYLON.serializeAsVector3()
  12042. ], DirectionalLight.prototype, "direction", void 0);
  12043. __decorate([
  12044. BABYLON.serialize()
  12045. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  12046. __decorate([
  12047. BABYLON.serialize()
  12048. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  12049. BABYLON.DirectionalLight = DirectionalLight;
  12050. })(BABYLON || (BABYLON = {}));
  12051. //# sourceMappingURL=babylon.directionalLight.js.map
  12052. var BABYLON;
  12053. (function (BABYLON) {
  12054. var ShadowGenerator = (function () {
  12055. function ShadowGenerator(mapSize, light) {
  12056. var _this = this;
  12057. // Members
  12058. this._filter = ShadowGenerator.FILTER_NONE;
  12059. this.blurScale = 2;
  12060. this._blurBoxOffset = 0;
  12061. this._bias = 0.00005;
  12062. this._lightDirection = BABYLON.Vector3.Zero();
  12063. this.forceBackFacesOnly = false;
  12064. this._darkness = 0;
  12065. this._transparencyShadow = false;
  12066. this._viewMatrix = BABYLON.Matrix.Zero();
  12067. this._projectionMatrix = BABYLON.Matrix.Zero();
  12068. this._transformMatrix = BABYLON.Matrix.Zero();
  12069. this._worldViewProjection = BABYLON.Matrix.Zero();
  12070. this._currentFaceIndex = 0;
  12071. this._currentFaceIndexCache = 0;
  12072. this._useFullFloat = true;
  12073. this._light = light;
  12074. this._scene = light.getScene();
  12075. this._mapSize = mapSize;
  12076. light._shadowGenerator = this;
  12077. // Texture type fallback from float to int if not supported.
  12078. var textureType;
  12079. var caps = this._scene.getEngine().getCaps();
  12080. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  12081. this._useFullFloat = true;
  12082. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  12083. }
  12084. else {
  12085. this._useFullFloat = false;
  12086. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  12087. }
  12088. // Render target
  12089. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  12090. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12091. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12092. this._shadowMap.anisotropicFilteringLevel = 1;
  12093. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12094. this._shadowMap.renderParticles = false;
  12095. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  12096. _this._currentFaceIndex = faceIndex;
  12097. });
  12098. this._shadowMap.onAfterUnbindObservable.add(function () {
  12099. if (!_this.useBlurVarianceShadowMap) {
  12100. return;
  12101. }
  12102. if (!_this._shadowMap2) {
  12103. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  12104. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12105. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12106. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  12107. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  12108. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  12109. effect.setTexture("textureSampler", _this._shadowMap);
  12110. });
  12111. _this.blurBoxOffset = 1;
  12112. }
  12113. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  12114. });
  12115. // Custom render function
  12116. var renderSubMesh = function (subMesh) {
  12117. var mesh = subMesh.getRenderingMesh();
  12118. var scene = _this._scene;
  12119. var engine = scene.getEngine();
  12120. // Culling
  12121. engine.setState(subMesh.getMaterial().backFaceCulling);
  12122. // Managing instances
  12123. var batch = mesh._getInstancesRenderList(subMesh._id);
  12124. if (batch.mustReturn) {
  12125. return;
  12126. }
  12127. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  12128. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  12129. engine.enableEffect(_this._effect);
  12130. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  12131. var material = subMesh.getMaterial();
  12132. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  12133. _this._effect.setVector3("lightPosition", _this.getLight().position);
  12134. if (_this.getLight().needCube()) {
  12135. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  12136. }
  12137. // Alpha test
  12138. if (material && material.needAlphaTesting()) {
  12139. var alphaTexture = material.getAlphaTestTexture();
  12140. _this._effect.setTexture("diffuseSampler", alphaTexture);
  12141. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  12142. }
  12143. // Bones
  12144. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  12145. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  12146. }
  12147. if (_this.forceBackFacesOnly) {
  12148. engine.setState(true, 0, false, true);
  12149. }
  12150. // Draw
  12151. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  12152. if (_this.forceBackFacesOnly) {
  12153. engine.setState(true, 0, false, false);
  12154. }
  12155. }
  12156. else {
  12157. // Need to reset refresh rate of the shadowMap
  12158. _this._shadowMap.resetRefreshCounter();
  12159. }
  12160. };
  12161. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  12162. var index;
  12163. for (index = 0; index < opaqueSubMeshes.length; index++) {
  12164. renderSubMesh(opaqueSubMeshes.data[index]);
  12165. }
  12166. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  12167. renderSubMesh(alphaTestSubMeshes.data[index]);
  12168. }
  12169. if (_this._transparencyShadow) {
  12170. for (index = 0; index < transparentSubMeshes.length; index++) {
  12171. renderSubMesh(transparentSubMeshes.data[index]);
  12172. }
  12173. }
  12174. };
  12175. this._shadowMap.onClearObservable.add(function (engine) {
  12176. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  12177. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  12178. }
  12179. else {
  12180. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  12181. }
  12182. });
  12183. }
  12184. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  12185. // Static
  12186. get: function () {
  12187. return ShadowGenerator._FILTER_NONE;
  12188. },
  12189. enumerable: true,
  12190. configurable: true
  12191. });
  12192. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  12193. get: function () {
  12194. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  12195. },
  12196. enumerable: true,
  12197. configurable: true
  12198. });
  12199. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  12200. get: function () {
  12201. return ShadowGenerator._FILTER_POISSONSAMPLING;
  12202. },
  12203. enumerable: true,
  12204. configurable: true
  12205. });
  12206. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  12207. get: function () {
  12208. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  12209. },
  12210. enumerable: true,
  12211. configurable: true
  12212. });
  12213. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  12214. get: function () {
  12215. return this._bias;
  12216. },
  12217. set: function (bias) {
  12218. this._bias = bias;
  12219. },
  12220. enumerable: true,
  12221. configurable: true
  12222. });
  12223. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  12224. get: function () {
  12225. return this._blurBoxOffset;
  12226. },
  12227. set: function (value) {
  12228. var _this = this;
  12229. if (this._blurBoxOffset === value) {
  12230. return;
  12231. }
  12232. this._blurBoxOffset = value;
  12233. if (this._boxBlurPostprocess) {
  12234. this._boxBlurPostprocess.dispose();
  12235. }
  12236. 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);
  12237. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  12238. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  12239. });
  12240. },
  12241. enumerable: true,
  12242. configurable: true
  12243. });
  12244. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  12245. get: function () {
  12246. return this._filter;
  12247. },
  12248. set: function (value) {
  12249. if (this._filter === value) {
  12250. return;
  12251. }
  12252. this._filter = value;
  12253. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  12254. this._shadowMap.anisotropicFilteringLevel = 16;
  12255. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  12256. }
  12257. else {
  12258. this._shadowMap.anisotropicFilteringLevel = 1;
  12259. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12260. }
  12261. },
  12262. enumerable: true,
  12263. configurable: true
  12264. });
  12265. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  12266. get: function () {
  12267. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  12268. },
  12269. set: function (value) {
  12270. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  12271. },
  12272. enumerable: true,
  12273. configurable: true
  12274. });
  12275. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  12276. get: function () {
  12277. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  12278. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  12279. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  12280. },
  12281. set: function (value) {
  12282. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  12283. },
  12284. enumerable: true,
  12285. configurable: true
  12286. });
  12287. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  12288. get: function () {
  12289. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  12290. },
  12291. set: function (value) {
  12292. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  12293. },
  12294. enumerable: true,
  12295. configurable: true
  12296. });
  12297. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  12298. var defines = [];
  12299. if (this._useFullFloat) {
  12300. defines.push("#define FULLFLOAT");
  12301. }
  12302. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  12303. defines.push("#define VSM");
  12304. }
  12305. if (this.getLight().needCube()) {
  12306. defines.push("#define CUBEMAP");
  12307. }
  12308. var attribs = [BABYLON.VertexBuffer.PositionKind];
  12309. var mesh = subMesh.getMesh();
  12310. var material = subMesh.getMaterial();
  12311. // Alpha test
  12312. if (material && material.needAlphaTesting()) {
  12313. defines.push("#define ALPHATEST");
  12314. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12315. attribs.push(BABYLON.VertexBuffer.UVKind);
  12316. defines.push("#define UV1");
  12317. }
  12318. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  12319. var alphaTexture = material.getAlphaTestTexture();
  12320. if (alphaTexture.coordinatesIndex === 1) {
  12321. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  12322. defines.push("#define UV2");
  12323. }
  12324. }
  12325. }
  12326. // Bones
  12327. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  12328. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  12329. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  12330. if (mesh.numBoneInfluencers > 4) {
  12331. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  12332. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  12333. }
  12334. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  12335. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  12336. }
  12337. else {
  12338. defines.push("#define NUM_BONE_INFLUENCERS 0");
  12339. }
  12340. // Instances
  12341. if (useInstances) {
  12342. defines.push("#define INSTANCES");
  12343. attribs.push("world0");
  12344. attribs.push("world1");
  12345. attribs.push("world2");
  12346. attribs.push("world3");
  12347. }
  12348. // Get correct effect
  12349. var join = defines.join("\n");
  12350. if (this._cachedDefines !== join) {
  12351. this._cachedDefines = join;
  12352. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  12353. }
  12354. return this._effect.isReady();
  12355. };
  12356. ShadowGenerator.prototype.getShadowMap = function () {
  12357. return this._shadowMap;
  12358. };
  12359. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  12360. if (this._shadowMap2) {
  12361. return this._shadowMap2;
  12362. }
  12363. return this._shadowMap;
  12364. };
  12365. ShadowGenerator.prototype.getLight = function () {
  12366. return this._light;
  12367. };
  12368. // Methods
  12369. ShadowGenerator.prototype.getTransformMatrix = function () {
  12370. var scene = this._scene;
  12371. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  12372. return this._transformMatrix;
  12373. }
  12374. this._currentRenderID = scene.getRenderId();
  12375. this._currentFaceIndexCache = this._currentFaceIndex;
  12376. var lightPosition = this._light.position;
  12377. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  12378. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  12379. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  12380. }
  12381. if (this._light.computeTransformedPosition()) {
  12382. lightPosition = this._light.transformedPosition;
  12383. }
  12384. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  12385. this._cachedPosition = lightPosition.clone();
  12386. this._cachedDirection = this._lightDirection.clone();
  12387. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  12388. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  12389. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12390. }
  12391. return this._transformMatrix;
  12392. };
  12393. ShadowGenerator.prototype.getDarkness = function () {
  12394. return this._darkness;
  12395. };
  12396. ShadowGenerator.prototype.setDarkness = function (darkness) {
  12397. if (darkness >= 1.0)
  12398. this._darkness = 1.0;
  12399. else if (darkness <= 0.0)
  12400. this._darkness = 0.0;
  12401. else
  12402. this._darkness = darkness;
  12403. };
  12404. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  12405. this._transparencyShadow = hasShadow;
  12406. };
  12407. ShadowGenerator.prototype._packHalf = function (depth) {
  12408. var scale = depth * 255.0;
  12409. var fract = scale - Math.floor(scale);
  12410. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  12411. };
  12412. ShadowGenerator.prototype.dispose = function () {
  12413. this._shadowMap.dispose();
  12414. if (this._shadowMap2) {
  12415. this._shadowMap2.dispose();
  12416. }
  12417. if (this._downSamplePostprocess) {
  12418. this._downSamplePostprocess.dispose();
  12419. }
  12420. if (this._boxBlurPostprocess) {
  12421. this._boxBlurPostprocess.dispose();
  12422. }
  12423. };
  12424. ShadowGenerator.prototype.serialize = function () {
  12425. var serializationObject = {};
  12426. serializationObject.lightId = this._light.id;
  12427. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  12428. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  12429. serializationObject.usePoissonSampling = this.usePoissonSampling;
  12430. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  12431. serializationObject.renderList = [];
  12432. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  12433. var mesh = this.getShadowMap().renderList[meshIndex];
  12434. serializationObject.renderList.push(mesh.id);
  12435. }
  12436. return serializationObject;
  12437. };
  12438. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  12439. //casting to point light, as light is missing the position attr and typescript complains.
  12440. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  12441. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  12442. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  12443. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  12444. meshes.forEach(function (mesh) {
  12445. shadowGenerator.getShadowMap().renderList.push(mesh);
  12446. });
  12447. }
  12448. if (parsedShadowGenerator.usePoissonSampling) {
  12449. shadowGenerator.usePoissonSampling = true;
  12450. }
  12451. else if (parsedShadowGenerator.useVarianceShadowMap) {
  12452. shadowGenerator.useVarianceShadowMap = true;
  12453. }
  12454. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  12455. shadowGenerator.useBlurVarianceShadowMap = true;
  12456. if (parsedShadowGenerator.blurScale) {
  12457. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  12458. }
  12459. if (parsedShadowGenerator.blurBoxOffset) {
  12460. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  12461. }
  12462. }
  12463. if (parsedShadowGenerator.bias !== undefined) {
  12464. shadowGenerator.bias = parsedShadowGenerator.bias;
  12465. }
  12466. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  12467. return shadowGenerator;
  12468. };
  12469. return ShadowGenerator;
  12470. }());
  12471. ShadowGenerator._FILTER_NONE = 0;
  12472. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  12473. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  12474. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  12475. BABYLON.ShadowGenerator = ShadowGenerator;
  12476. })(BABYLON || (BABYLON = {}));
  12477. //# sourceMappingURL=babylon.shadowGenerator.js.map
  12478. var BABYLON;
  12479. (function (BABYLON) {
  12480. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  12481. if (boxMin.x > sphereCenter.x + sphereRadius)
  12482. return false;
  12483. if (sphereCenter.x - sphereRadius > boxMax.x)
  12484. return false;
  12485. if (boxMin.y > sphereCenter.y + sphereRadius)
  12486. return false;
  12487. if (sphereCenter.y - sphereRadius > boxMax.y)
  12488. return false;
  12489. if (boxMin.z > sphereCenter.z + sphereRadius)
  12490. return false;
  12491. if (sphereCenter.z - sphereRadius > boxMax.z)
  12492. return false;
  12493. return true;
  12494. };
  12495. var getLowestRoot = (function () {
  12496. var result = { root: 0, found: false };
  12497. return function (a, b, c, maxR) {
  12498. result.root = 0;
  12499. result.found = false;
  12500. var determinant = b * b - 4.0 * a * c;
  12501. if (determinant < 0)
  12502. return result;
  12503. var sqrtD = Math.sqrt(determinant);
  12504. var r1 = (-b - sqrtD) / (2.0 * a);
  12505. var r2 = (-b + sqrtD) / (2.0 * a);
  12506. if (r1 > r2) {
  12507. var temp = r2;
  12508. r2 = r1;
  12509. r1 = temp;
  12510. }
  12511. if (r1 > 0 && r1 < maxR) {
  12512. result.root = r1;
  12513. result.found = true;
  12514. return result;
  12515. }
  12516. if (r2 > 0 && r2 < maxR) {
  12517. result.root = r2;
  12518. result.found = true;
  12519. return result;
  12520. }
  12521. return result;
  12522. };
  12523. })();
  12524. var Collider = (function () {
  12525. function Collider() {
  12526. this.radius = new BABYLON.Vector3(1, 1, 1);
  12527. this.retry = 0;
  12528. this.basePointWorld = BABYLON.Vector3.Zero();
  12529. this.velocityWorld = BABYLON.Vector3.Zero();
  12530. this.normalizedVelocity = BABYLON.Vector3.Zero();
  12531. this._collisionPoint = BABYLON.Vector3.Zero();
  12532. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  12533. this._tempVector = BABYLON.Vector3.Zero();
  12534. this._tempVector2 = BABYLON.Vector3.Zero();
  12535. this._tempVector3 = BABYLON.Vector3.Zero();
  12536. this._tempVector4 = BABYLON.Vector3.Zero();
  12537. this._edge = BABYLON.Vector3.Zero();
  12538. this._baseToVertex = BABYLON.Vector3.Zero();
  12539. this._destinationPoint = BABYLON.Vector3.Zero();
  12540. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  12541. this._displacementVector = BABYLON.Vector3.Zero();
  12542. }
  12543. // Methods
  12544. Collider.prototype._initialize = function (source, dir, e) {
  12545. this.velocity = dir;
  12546. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  12547. this.basePoint = source;
  12548. source.multiplyToRef(this.radius, this.basePointWorld);
  12549. dir.multiplyToRef(this.radius, this.velocityWorld);
  12550. this.velocityWorldLength = this.velocityWorld.length();
  12551. this.epsilon = e;
  12552. this.collisionFound = false;
  12553. };
  12554. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  12555. pa.subtractToRef(point, this._tempVector);
  12556. pb.subtractToRef(point, this._tempVector2);
  12557. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  12558. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12559. if (d < 0)
  12560. return false;
  12561. pc.subtractToRef(point, this._tempVector3);
  12562. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  12563. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12564. if (d < 0)
  12565. return false;
  12566. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  12567. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12568. return d >= 0;
  12569. };
  12570. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  12571. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  12572. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  12573. if (distance > this.velocityWorldLength + max + sphereRadius) {
  12574. return false;
  12575. }
  12576. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  12577. return false;
  12578. return true;
  12579. };
  12580. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  12581. var t0;
  12582. var embeddedInPlane = false;
  12583. //defensive programming, actually not needed.
  12584. if (!trianglePlaneArray) {
  12585. trianglePlaneArray = [];
  12586. }
  12587. if (!trianglePlaneArray[faceIndex]) {
  12588. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  12589. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  12590. }
  12591. var trianglePlane = trianglePlaneArray[faceIndex];
  12592. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  12593. return;
  12594. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  12595. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  12596. if (normalDotVelocity == 0) {
  12597. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  12598. return;
  12599. embeddedInPlane = true;
  12600. t0 = 0;
  12601. }
  12602. else {
  12603. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12604. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12605. if (t0 > t1) {
  12606. var temp = t1;
  12607. t1 = t0;
  12608. t0 = temp;
  12609. }
  12610. if (t0 > 1.0 || t1 < 0.0)
  12611. return;
  12612. if (t0 < 0)
  12613. t0 = 0;
  12614. if (t0 > 1.0)
  12615. t0 = 1.0;
  12616. }
  12617. this._collisionPoint.copyFromFloats(0, 0, 0);
  12618. var found = false;
  12619. var t = 1.0;
  12620. if (!embeddedInPlane) {
  12621. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  12622. this.velocity.scaleToRef(t0, this._tempVector);
  12623. this._planeIntersectionPoint.addInPlace(this._tempVector);
  12624. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  12625. found = true;
  12626. t = t0;
  12627. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  12628. }
  12629. }
  12630. if (!found) {
  12631. var velocitySquaredLength = this.velocity.lengthSquared();
  12632. var a = velocitySquaredLength;
  12633. this.basePoint.subtractToRef(p1, this._tempVector);
  12634. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12635. var c = this._tempVector.lengthSquared() - 1.0;
  12636. var lowestRoot = getLowestRoot(a, b, c, t);
  12637. if (lowestRoot.found) {
  12638. t = lowestRoot.root;
  12639. found = true;
  12640. this._collisionPoint.copyFrom(p1);
  12641. }
  12642. this.basePoint.subtractToRef(p2, this._tempVector);
  12643. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12644. c = this._tempVector.lengthSquared() - 1.0;
  12645. lowestRoot = getLowestRoot(a, b, c, t);
  12646. if (lowestRoot.found) {
  12647. t = lowestRoot.root;
  12648. found = true;
  12649. this._collisionPoint.copyFrom(p2);
  12650. }
  12651. this.basePoint.subtractToRef(p3, this._tempVector);
  12652. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12653. c = this._tempVector.lengthSquared() - 1.0;
  12654. lowestRoot = getLowestRoot(a, b, c, t);
  12655. if (lowestRoot.found) {
  12656. t = lowestRoot.root;
  12657. found = true;
  12658. this._collisionPoint.copyFrom(p3);
  12659. }
  12660. p2.subtractToRef(p1, this._edge);
  12661. p1.subtractToRef(this.basePoint, this._baseToVertex);
  12662. var edgeSquaredLength = this._edge.lengthSquared();
  12663. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12664. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12665. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12666. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12667. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12668. lowestRoot = getLowestRoot(a, b, c, t);
  12669. if (lowestRoot.found) {
  12670. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12671. if (f >= 0.0 && f <= 1.0) {
  12672. t = lowestRoot.root;
  12673. found = true;
  12674. this._edge.scaleInPlace(f);
  12675. p1.addToRef(this._edge, this._collisionPoint);
  12676. }
  12677. }
  12678. p3.subtractToRef(p2, this._edge);
  12679. p2.subtractToRef(this.basePoint, this._baseToVertex);
  12680. edgeSquaredLength = this._edge.lengthSquared();
  12681. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12682. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12683. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12684. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12685. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12686. lowestRoot = getLowestRoot(a, b, c, t);
  12687. if (lowestRoot.found) {
  12688. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12689. if (f >= 0.0 && f <= 1.0) {
  12690. t = lowestRoot.root;
  12691. found = true;
  12692. this._edge.scaleInPlace(f);
  12693. p2.addToRef(this._edge, this._collisionPoint);
  12694. }
  12695. }
  12696. p1.subtractToRef(p3, this._edge);
  12697. p3.subtractToRef(this.basePoint, this._baseToVertex);
  12698. edgeSquaredLength = this._edge.lengthSquared();
  12699. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12700. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12701. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12702. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12703. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12704. lowestRoot = getLowestRoot(a, b, c, t);
  12705. if (lowestRoot.found) {
  12706. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12707. if (f >= 0.0 && f <= 1.0) {
  12708. t = lowestRoot.root;
  12709. found = true;
  12710. this._edge.scaleInPlace(f);
  12711. p3.addToRef(this._edge, this._collisionPoint);
  12712. }
  12713. }
  12714. }
  12715. if (found) {
  12716. var distToCollision = t * this.velocity.length();
  12717. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  12718. if (!this.intersectionPoint) {
  12719. this.intersectionPoint = this._collisionPoint.clone();
  12720. }
  12721. else {
  12722. this.intersectionPoint.copyFrom(this._collisionPoint);
  12723. }
  12724. this.nearestDistance = distToCollision;
  12725. this.collisionFound = true;
  12726. }
  12727. }
  12728. };
  12729. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  12730. for (var i = indexStart; i < indexEnd; i += 3) {
  12731. var p1 = pts[indices[i] - decal];
  12732. var p2 = pts[indices[i + 1] - decal];
  12733. var p3 = pts[indices[i + 2] - decal];
  12734. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  12735. }
  12736. };
  12737. Collider.prototype._getResponse = function (pos, vel) {
  12738. pos.addToRef(vel, this._destinationPoint);
  12739. vel.scaleInPlace((this.nearestDistance / vel.length()));
  12740. this.basePoint.addToRef(vel, pos);
  12741. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  12742. this._slidePlaneNormal.normalize();
  12743. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  12744. pos.addInPlace(this._displacementVector);
  12745. this.intersectionPoint.addInPlace(this._displacementVector);
  12746. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  12747. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  12748. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  12749. };
  12750. return Collider;
  12751. }());
  12752. BABYLON.Collider = Collider;
  12753. })(BABYLON || (BABYLON = {}));
  12754. //# sourceMappingURL=babylon.collider.js.map
  12755. var BABYLON;
  12756. (function (BABYLON) {
  12757. //WebWorker code will be inserted to this variable.
  12758. BABYLON.CollisionWorker = "";
  12759. var WorkerTaskType;
  12760. (function (WorkerTaskType) {
  12761. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  12762. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  12763. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  12764. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  12765. var WorkerReplyType;
  12766. (function (WorkerReplyType) {
  12767. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  12768. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  12769. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  12770. var CollisionCoordinatorWorker = (function () {
  12771. function CollisionCoordinatorWorker() {
  12772. var _this = this;
  12773. this._scaledPosition = BABYLON.Vector3.Zero();
  12774. this._scaledVelocity = BABYLON.Vector3.Zero();
  12775. this.onMeshUpdated = function (mesh) {
  12776. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  12777. };
  12778. this.onGeometryUpdated = function (geometry) {
  12779. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  12780. };
  12781. this._afterRender = function () {
  12782. if (!_this._init)
  12783. return;
  12784. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  12785. return;
  12786. }
  12787. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  12788. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  12789. if (_this._runningUpdated > 4) {
  12790. return;
  12791. }
  12792. ++_this._runningUpdated;
  12793. var payload = {
  12794. updatedMeshes: _this._addUpdateMeshesList,
  12795. updatedGeometries: _this._addUpdateGeometriesList,
  12796. removedGeometries: _this._toRemoveGeometryArray,
  12797. removedMeshes: _this._toRemoveMeshesArray
  12798. };
  12799. var message = {
  12800. payload: payload,
  12801. taskType: WorkerTaskType.UPDATE
  12802. };
  12803. var serializable = [];
  12804. for (var id in payload.updatedGeometries) {
  12805. if (payload.updatedGeometries.hasOwnProperty(id)) {
  12806. //prepare transferables
  12807. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  12808. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  12809. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  12810. }
  12811. }
  12812. _this._worker.postMessage(message, serializable);
  12813. _this._addUpdateMeshesList = {};
  12814. _this._addUpdateGeometriesList = {};
  12815. _this._toRemoveGeometryArray = [];
  12816. _this._toRemoveMeshesArray = [];
  12817. };
  12818. this._onMessageFromWorker = function (e) {
  12819. var returnData = e.data;
  12820. if (returnData.error != WorkerReplyType.SUCCESS) {
  12821. //TODO what errors can be returned from the worker?
  12822. BABYLON.Tools.Warn("error returned from worker!");
  12823. return;
  12824. }
  12825. switch (returnData.taskType) {
  12826. case WorkerTaskType.INIT:
  12827. _this._init = true;
  12828. //Update the worked with ALL of the scene's current state
  12829. _this._scene.meshes.forEach(function (mesh) {
  12830. _this.onMeshAdded(mesh);
  12831. });
  12832. _this._scene.getGeometries().forEach(function (geometry) {
  12833. _this.onGeometryAdded(geometry);
  12834. });
  12835. break;
  12836. case WorkerTaskType.UPDATE:
  12837. _this._runningUpdated--;
  12838. break;
  12839. case WorkerTaskType.COLLIDE:
  12840. _this._runningCollisionTask = false;
  12841. var returnPayload = returnData.payload;
  12842. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  12843. return;
  12844. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  12845. //cleanup
  12846. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  12847. break;
  12848. }
  12849. };
  12850. this._collisionsCallbackArray = [];
  12851. this._init = false;
  12852. this._runningUpdated = 0;
  12853. this._runningCollisionTask = false;
  12854. this._addUpdateMeshesList = {};
  12855. this._addUpdateGeometriesList = {};
  12856. this._toRemoveGeometryArray = [];
  12857. this._toRemoveMeshesArray = [];
  12858. }
  12859. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12860. if (!this._init)
  12861. return;
  12862. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  12863. return;
  12864. position.divideToRef(collider.radius, this._scaledPosition);
  12865. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12866. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  12867. var payload = {
  12868. collider: {
  12869. position: this._scaledPosition.asArray(),
  12870. velocity: this._scaledVelocity.asArray(),
  12871. radius: collider.radius.asArray()
  12872. },
  12873. collisionId: collisionIndex,
  12874. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  12875. maximumRetry: maximumRetry
  12876. };
  12877. var message = {
  12878. payload: payload,
  12879. taskType: WorkerTaskType.COLLIDE
  12880. };
  12881. this._worker.postMessage(message);
  12882. };
  12883. CollisionCoordinatorWorker.prototype.init = function (scene) {
  12884. this._scene = scene;
  12885. this._scene.registerAfterRender(this._afterRender);
  12886. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  12887. this._worker = new Worker(workerUrl);
  12888. this._worker.onmessage = this._onMessageFromWorker;
  12889. var message = {
  12890. payload: {},
  12891. taskType: WorkerTaskType.INIT
  12892. };
  12893. this._worker.postMessage(message);
  12894. };
  12895. CollisionCoordinatorWorker.prototype.destroy = function () {
  12896. this._scene.unregisterAfterRender(this._afterRender);
  12897. this._worker.terminate();
  12898. };
  12899. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  12900. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  12901. this.onMeshUpdated(mesh);
  12902. };
  12903. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  12904. this._toRemoveMeshesArray.push(mesh.uniqueId);
  12905. };
  12906. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  12907. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  12908. geometry.onGeometryUpdated = this.onGeometryUpdated;
  12909. this.onGeometryUpdated(geometry);
  12910. };
  12911. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  12912. this._toRemoveGeometryArray.push(geometry.id);
  12913. };
  12914. return CollisionCoordinatorWorker;
  12915. }());
  12916. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  12917. var submeshes = [];
  12918. if (mesh.subMeshes) {
  12919. submeshes = mesh.subMeshes.map(function (sm, idx) {
  12920. return {
  12921. position: idx,
  12922. verticesStart: sm.verticesStart,
  12923. verticesCount: sm.verticesCount,
  12924. indexStart: sm.indexStart,
  12925. indexCount: sm.indexCount,
  12926. hasMaterial: !!sm.getMaterial(),
  12927. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12928. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  12929. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12930. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  12931. };
  12932. });
  12933. }
  12934. var geometryId = null;
  12935. if (mesh instanceof BABYLON.Mesh) {
  12936. geometryId = mesh.geometry ? mesh.geometry.id : null;
  12937. }
  12938. else if (mesh instanceof BABYLON.InstancedMesh) {
  12939. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  12940. }
  12941. return {
  12942. uniqueId: mesh.uniqueId,
  12943. id: mesh.id,
  12944. name: mesh.name,
  12945. geometryId: geometryId,
  12946. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12947. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  12948. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12949. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  12950. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  12951. subMeshes: submeshes,
  12952. checkCollisions: mesh.checkCollisions
  12953. };
  12954. };
  12955. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  12956. return {
  12957. id: geometry.id,
  12958. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  12959. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  12960. indices: new Int32Array(geometry.getIndices() || []),
  12961. };
  12962. };
  12963. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  12964. var CollisionCoordinatorLegacy = (function () {
  12965. function CollisionCoordinatorLegacy() {
  12966. this._scaledPosition = BABYLON.Vector3.Zero();
  12967. this._scaledVelocity = BABYLON.Vector3.Zero();
  12968. this._finalPosition = BABYLON.Vector3.Zero();
  12969. }
  12970. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12971. position.divideToRef(collider.radius, this._scaledPosition);
  12972. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12973. collider.collidedMesh = null;
  12974. collider.retry = 0;
  12975. collider.initialVelocity = this._scaledVelocity;
  12976. collider.initialPosition = this._scaledPosition;
  12977. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  12978. this._finalPosition.multiplyInPlace(collider.radius);
  12979. //run the callback
  12980. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  12981. };
  12982. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  12983. this._scene = scene;
  12984. };
  12985. CollisionCoordinatorLegacy.prototype.destroy = function () {
  12986. //Legacy need no destruction method.
  12987. };
  12988. //No update in legacy mode
  12989. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  12990. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  12991. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  12992. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  12993. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  12994. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  12995. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  12996. if (excludedMesh === void 0) { excludedMesh = null; }
  12997. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  12998. if (collider.retry >= maximumRetry) {
  12999. finalPosition.copyFrom(position);
  13000. return;
  13001. }
  13002. collider._initialize(position, velocity, closeDistance);
  13003. // Check all meshes
  13004. for (var index = 0; index < this._scene.meshes.length; index++) {
  13005. var mesh = this._scene.meshes[index];
  13006. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  13007. mesh._checkCollision(collider);
  13008. }
  13009. }
  13010. if (!collider.collisionFound) {
  13011. position.addToRef(velocity, finalPosition);
  13012. return;
  13013. }
  13014. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  13015. collider._getResponse(position, velocity);
  13016. }
  13017. if (velocity.length() <= closeDistance) {
  13018. finalPosition.copyFrom(position);
  13019. return;
  13020. }
  13021. collider.retry++;
  13022. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  13023. };
  13024. return CollisionCoordinatorLegacy;
  13025. }());
  13026. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  13027. })(BABYLON || (BABYLON = {}));
  13028. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  13029. var BABYLON;
  13030. (function (BABYLON) {
  13031. var Camera = (function (_super) {
  13032. __extends(Camera, _super);
  13033. function Camera(name, position, scene) {
  13034. var _this = _super.call(this, name, scene) || this;
  13035. _this.upVector = BABYLON.Vector3.Up();
  13036. _this.orthoLeft = null;
  13037. _this.orthoRight = null;
  13038. _this.orthoBottom = null;
  13039. _this.orthoTop = null;
  13040. _this.fov = 0.8;
  13041. _this.minZ = 1.0;
  13042. _this.maxZ = 10000.0;
  13043. _this.inertia = 0.9;
  13044. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13045. _this.isIntermediate = false;
  13046. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13047. _this.layerMask = 0x0FFFFFFF;
  13048. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13049. // Camera rig members
  13050. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13051. _this._rigCameras = new Array();
  13052. // Cache
  13053. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13054. _this._projectionMatrix = new BABYLON.Matrix();
  13055. _this._doNotComputeProjectionMatrix = false;
  13056. _this._postProcesses = new Array();
  13057. _this._transformMatrix = BABYLON.Matrix.Zero();
  13058. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13059. _this._activeMeshes = new BABYLON.SmartArray(256);
  13060. _this._globalPosition = BABYLON.Vector3.Zero();
  13061. _this._refreshFrustumPlanes = true;
  13062. scene.addCamera(_this);
  13063. if (!scene.activeCamera) {
  13064. scene.activeCamera = _this;
  13065. }
  13066. _this.position = position;
  13067. return _this;
  13068. }
  13069. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13070. get: function () {
  13071. return Camera._PERSPECTIVE_CAMERA;
  13072. },
  13073. enumerable: true,
  13074. configurable: true
  13075. });
  13076. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13077. get: function () {
  13078. return Camera._ORTHOGRAPHIC_CAMERA;
  13079. },
  13080. enumerable: true,
  13081. configurable: true
  13082. });
  13083. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13084. get: function () {
  13085. return Camera._FOVMODE_VERTICAL_FIXED;
  13086. },
  13087. enumerable: true,
  13088. configurable: true
  13089. });
  13090. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13091. get: function () {
  13092. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13093. },
  13094. enumerable: true,
  13095. configurable: true
  13096. });
  13097. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13098. get: function () {
  13099. return Camera._RIG_MODE_NONE;
  13100. },
  13101. enumerable: true,
  13102. configurable: true
  13103. });
  13104. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13105. get: function () {
  13106. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13107. },
  13108. enumerable: true,
  13109. configurable: true
  13110. });
  13111. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13112. get: function () {
  13113. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13114. },
  13115. enumerable: true,
  13116. configurable: true
  13117. });
  13118. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13119. get: function () {
  13120. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13121. },
  13122. enumerable: true,
  13123. configurable: true
  13124. });
  13125. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13126. get: function () {
  13127. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13128. },
  13129. enumerable: true,
  13130. configurable: true
  13131. });
  13132. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13133. get: function () {
  13134. return Camera._RIG_MODE_VR;
  13135. },
  13136. enumerable: true,
  13137. configurable: true
  13138. });
  13139. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13140. get: function () {
  13141. return Camera._RIG_MODE_WEBVR;
  13142. },
  13143. enumerable: true,
  13144. configurable: true
  13145. });
  13146. Camera.prototype.getClassName = function () {
  13147. return "Camera";
  13148. };
  13149. /**
  13150. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13151. */
  13152. Camera.prototype.toString = function (fullDetails) {
  13153. var ret = "Name: " + this.name;
  13154. ret += ", type: " + this.getClassName();
  13155. if (this.animations) {
  13156. for (var i = 0; i < this.animations.length; i++) {
  13157. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13158. }
  13159. }
  13160. if (fullDetails) {
  13161. }
  13162. return ret;
  13163. };
  13164. Object.defineProperty(Camera.prototype, "globalPosition", {
  13165. get: function () {
  13166. return this._globalPosition;
  13167. },
  13168. enumerable: true,
  13169. configurable: true
  13170. });
  13171. Camera.prototype.getActiveMeshes = function () {
  13172. return this._activeMeshes;
  13173. };
  13174. Camera.prototype.isActiveMesh = function (mesh) {
  13175. return (this._activeMeshes.indexOf(mesh) !== -1);
  13176. };
  13177. //Cache
  13178. Camera.prototype._initCache = function () {
  13179. _super.prototype._initCache.call(this);
  13180. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13181. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13182. this._cache.mode = undefined;
  13183. this._cache.minZ = undefined;
  13184. this._cache.maxZ = undefined;
  13185. this._cache.fov = undefined;
  13186. this._cache.fovMode = undefined;
  13187. this._cache.aspectRatio = undefined;
  13188. this._cache.orthoLeft = undefined;
  13189. this._cache.orthoRight = undefined;
  13190. this._cache.orthoBottom = undefined;
  13191. this._cache.orthoTop = undefined;
  13192. this._cache.renderWidth = undefined;
  13193. this._cache.renderHeight = undefined;
  13194. };
  13195. Camera.prototype._updateCache = function (ignoreParentClass) {
  13196. if (!ignoreParentClass) {
  13197. _super.prototype._updateCache.call(this);
  13198. }
  13199. var engine = this.getEngine();
  13200. this._cache.position.copyFrom(this.position);
  13201. this._cache.upVector.copyFrom(this.upVector);
  13202. this._cache.mode = this.mode;
  13203. this._cache.minZ = this.minZ;
  13204. this._cache.maxZ = this.maxZ;
  13205. this._cache.fov = this.fov;
  13206. this._cache.fovMode = this.fovMode;
  13207. this._cache.aspectRatio = engine.getAspectRatio(this);
  13208. this._cache.orthoLeft = this.orthoLeft;
  13209. this._cache.orthoRight = this.orthoRight;
  13210. this._cache.orthoBottom = this.orthoBottom;
  13211. this._cache.orthoTop = this.orthoTop;
  13212. this._cache.renderWidth = engine.getRenderWidth();
  13213. this._cache.renderHeight = engine.getRenderHeight();
  13214. };
  13215. Camera.prototype._updateFromScene = function () {
  13216. this.updateCache();
  13217. this.update();
  13218. };
  13219. // Synchronized
  13220. Camera.prototype._isSynchronized = function () {
  13221. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  13222. };
  13223. Camera.prototype._isSynchronizedViewMatrix = function () {
  13224. if (!_super.prototype._isSynchronized.call(this))
  13225. return false;
  13226. return this._cache.position.equals(this.position)
  13227. && this._cache.upVector.equals(this.upVector)
  13228. && this.isSynchronizedWithParent();
  13229. };
  13230. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  13231. var check = this._cache.mode === this.mode
  13232. && this._cache.minZ === this.minZ
  13233. && this._cache.maxZ === this.maxZ;
  13234. if (!check) {
  13235. return false;
  13236. }
  13237. var engine = this.getEngine();
  13238. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13239. check = this._cache.fov === this.fov
  13240. && this._cache.fovMode === this.fovMode
  13241. && this._cache.aspectRatio === engine.getAspectRatio(this);
  13242. }
  13243. else {
  13244. check = this._cache.orthoLeft === this.orthoLeft
  13245. && this._cache.orthoRight === this.orthoRight
  13246. && this._cache.orthoBottom === this.orthoBottom
  13247. && this._cache.orthoTop === this.orthoTop
  13248. && this._cache.renderWidth === engine.getRenderWidth()
  13249. && this._cache.renderHeight === engine.getRenderHeight();
  13250. }
  13251. return check;
  13252. };
  13253. // Controls
  13254. Camera.prototype.attachControl = function (element, noPreventDefault) {
  13255. };
  13256. Camera.prototype.detachControl = function (element) {
  13257. };
  13258. Camera.prototype.update = function () {
  13259. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13260. this._updateRigCameras();
  13261. }
  13262. this._checkInputs();
  13263. };
  13264. Camera.prototype._checkInputs = function () {
  13265. };
  13266. Camera.prototype._cascadePostProcessesToRigCams = function () {
  13267. // invalidate framebuffer
  13268. if (this._postProcesses.length > 0) {
  13269. this._postProcesses[0].markTextureDirty();
  13270. }
  13271. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  13272. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  13273. var cam = this._rigCameras[i];
  13274. var rigPostProcess = cam._rigPostProcess;
  13275. // for VR rig, there does not have to be a post process
  13276. if (rigPostProcess) {
  13277. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  13278. if (isPass) {
  13279. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  13280. cam.isIntermediate = this._postProcesses.length === 0;
  13281. }
  13282. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  13283. rigPostProcess.markTextureDirty();
  13284. }
  13285. else {
  13286. cam._postProcesses = this._postProcesses.slice(0);
  13287. }
  13288. }
  13289. };
  13290. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  13291. if (insertAt === void 0) { insertAt = null; }
  13292. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  13293. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  13294. return 0;
  13295. }
  13296. if (insertAt == null || insertAt < 0) {
  13297. this._postProcesses.push(postProcess);
  13298. }
  13299. else {
  13300. this._postProcesses.splice(insertAt, 0, postProcess);
  13301. }
  13302. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13303. return this._postProcesses.indexOf(postProcess);
  13304. };
  13305. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  13306. if (atIndices === void 0) { atIndices = null; }
  13307. var result = [];
  13308. var i;
  13309. var index;
  13310. if (!atIndices) {
  13311. var idx = this._postProcesses.indexOf(postProcess);
  13312. if (idx !== -1) {
  13313. this._postProcesses.splice(idx, 1);
  13314. }
  13315. }
  13316. else {
  13317. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  13318. // iterate descending, so can just splice as we go
  13319. for (i = atIndices.length - 1; i >= 0; i--) {
  13320. if (this._postProcesses[atIndices[i]] !== postProcess) {
  13321. result.push(i);
  13322. continue;
  13323. }
  13324. this._postProcesses.splice(index, 1);
  13325. }
  13326. }
  13327. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13328. return result;
  13329. };
  13330. Camera.prototype.getWorldMatrix = function () {
  13331. if (!this._worldMatrix) {
  13332. this._worldMatrix = BABYLON.Matrix.Identity();
  13333. }
  13334. var viewMatrix = this.getViewMatrix();
  13335. viewMatrix.invertToRef(this._worldMatrix);
  13336. return this._worldMatrix;
  13337. };
  13338. Camera.prototype._getViewMatrix = function () {
  13339. return BABYLON.Matrix.Identity();
  13340. };
  13341. Camera.prototype.getViewMatrix = function (force) {
  13342. this._computedViewMatrix = this._computeViewMatrix(force);
  13343. if (!force && this._isSynchronizedViewMatrix()) {
  13344. return this._computedViewMatrix;
  13345. }
  13346. this._refreshFrustumPlanes = true;
  13347. if (!this.parent || !this.parent.getWorldMatrix) {
  13348. this._globalPosition.copyFrom(this.position);
  13349. }
  13350. else {
  13351. if (!this._worldMatrix) {
  13352. this._worldMatrix = BABYLON.Matrix.Identity();
  13353. }
  13354. this._computedViewMatrix.invertToRef(this._worldMatrix);
  13355. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  13356. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  13357. this._computedViewMatrix.invert();
  13358. this._markSyncedWithParent();
  13359. }
  13360. this._currentRenderId = this.getScene().getRenderId();
  13361. return this._computedViewMatrix;
  13362. };
  13363. Camera.prototype._computeViewMatrix = function (force) {
  13364. if (!force && this._isSynchronizedViewMatrix()) {
  13365. return this._computedViewMatrix;
  13366. }
  13367. this._computedViewMatrix = this._getViewMatrix();
  13368. this._currentRenderId = this.getScene().getRenderId();
  13369. return this._computedViewMatrix;
  13370. };
  13371. Camera.prototype.freezeProjectionMatrix = function (projection) {
  13372. this._doNotComputeProjectionMatrix = true;
  13373. if (projection !== undefined) {
  13374. this._projectionMatrix = projection;
  13375. }
  13376. };
  13377. ;
  13378. Camera.prototype.unfreezeProjectionMatrix = function () {
  13379. this._doNotComputeProjectionMatrix = false;
  13380. };
  13381. ;
  13382. Camera.prototype.getProjectionMatrix = function (force) {
  13383. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  13384. return this._projectionMatrix;
  13385. }
  13386. this._refreshFrustumPlanes = true;
  13387. var engine = this.getEngine();
  13388. var scene = this.getScene();
  13389. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13390. if (this.minZ <= 0) {
  13391. this.minZ = 0.1;
  13392. }
  13393. if (scene.useRightHandedSystem) {
  13394. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13395. }
  13396. else {
  13397. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13398. }
  13399. return this._projectionMatrix;
  13400. }
  13401. var halfWidth = engine.getRenderWidth() / 2.0;
  13402. var halfHeight = engine.getRenderHeight() / 2.0;
  13403. if (scene.useRightHandedSystem) {
  13404. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13405. }
  13406. else {
  13407. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13408. }
  13409. return this._projectionMatrix;
  13410. };
  13411. Camera.prototype.getTranformationMatrix = function () {
  13412. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13413. return this._transformMatrix;
  13414. };
  13415. Camera.prototype.updateFrustumPlanes = function () {
  13416. if (!this._refreshFrustumPlanes) {
  13417. return;
  13418. }
  13419. this.getTranformationMatrix();
  13420. if (!this._frustumPlanes) {
  13421. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13422. }
  13423. else {
  13424. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13425. }
  13426. this._refreshFrustumPlanes = false;
  13427. };
  13428. Camera.prototype.isInFrustum = function (target) {
  13429. this.updateFrustumPlanes();
  13430. return target.isInFrustum(this._frustumPlanes);
  13431. };
  13432. Camera.prototype.isCompletelyInFrustum = function (target) {
  13433. this.updateFrustumPlanes();
  13434. return target.isCompletelyInFrustum(this._frustumPlanes);
  13435. };
  13436. Camera.prototype.dispose = function () {
  13437. // Animations
  13438. this.getScene().stopAnimation(this);
  13439. // Remove from scene
  13440. this.getScene().removeCamera(this);
  13441. while (this._rigCameras.length > 0) {
  13442. this._rigCameras.pop().dispose();
  13443. }
  13444. // Postprocesses
  13445. var i = this._postProcesses.length;
  13446. while (--i >= 0) {
  13447. this._postProcesses[i].dispose(this);
  13448. }
  13449. _super.prototype.dispose.call(this);
  13450. };
  13451. // ---- Camera rigs section ----
  13452. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  13453. while (this._rigCameras.length > 0) {
  13454. this._rigCameras.pop().dispose();
  13455. }
  13456. this.cameraRigMode = mode;
  13457. this._cameraRigParams = {};
  13458. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  13459. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  13460. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  13461. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  13462. // create the rig cameras, unless none
  13463. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13464. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  13465. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  13466. }
  13467. switch (this.cameraRigMode) {
  13468. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13469. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13470. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  13471. break;
  13472. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13473. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13474. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13475. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13476. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13477. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  13478. break;
  13479. case Camera.RIG_MODE_VR:
  13480. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  13481. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  13482. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13483. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13484. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  13485. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  13486. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  13487. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  13488. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13489. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13490. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  13491. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  13492. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  13493. if (metrics.compensateDistortion) {
  13494. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  13495. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  13496. }
  13497. break;
  13498. case Camera.RIG_MODE_WEBVR:
  13499. if (rigParams.vrDisplay) {
  13500. //var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  13501. //var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  13502. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13503. this._rigCameras[0].setCameraRigParameter("left", true);
  13504. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  13505. //this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  13506. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13507. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13508. //this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  13509. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13510. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  13511. //this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  13512. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13513. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13514. }
  13515. break;
  13516. }
  13517. this._cascadePostProcessesToRigCams();
  13518. this.
  13519. update();
  13520. };
  13521. Camera.prototype._getVRProjectionMatrix = function () {
  13522. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13523. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  13524. return this._projectionMatrix;
  13525. };
  13526. Camera.prototype._getWebVRProjectionMatrix = function () {
  13527. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  13528. //babylon compatible matrix
  13529. [8, 9, 10, 11].forEach(function (num) {
  13530. projectionArray[num] *= -1;
  13531. });
  13532. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  13533. return this._projectionMatrix;
  13534. };
  13535. //Can be used, but we'll use the free camera's view matrix calculation
  13536. Camera.prototype._getWebVRViewMatrix = function () {
  13537. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  13538. //babylon compatible matrix
  13539. [8, 9, 10, 11].forEach(function (num) {
  13540. projectionArray[num] *= -1;
  13541. });
  13542. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._webvrViewMatrix);
  13543. return this._webvrViewMatrix;
  13544. };
  13545. Camera.prototype.setCameraRigParameter = function (name, value) {
  13546. if (!this._cameraRigParams) {
  13547. this._cameraRigParams = {};
  13548. }
  13549. this._cameraRigParams[name] = value;
  13550. //provisionnally:
  13551. if (name === "interaxialDistance") {
  13552. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  13553. }
  13554. };
  13555. /**
  13556. * needs to be overridden by children so sub has required properties to be copied
  13557. */
  13558. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  13559. return null;
  13560. };
  13561. /**
  13562. * May need to be overridden by children
  13563. */
  13564. Camera.prototype._updateRigCameras = function () {
  13565. for (var i = 0; i < this._rigCameras.length; i++) {
  13566. this._rigCameras[i].minZ = this.minZ;
  13567. this._rigCameras[i].maxZ = this.maxZ;
  13568. this._rigCameras[i].fov = this.fov;
  13569. }
  13570. // only update viewport when ANAGLYPH
  13571. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  13572. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  13573. }
  13574. };
  13575. Camera.prototype._setupInputs = function () {
  13576. };
  13577. Camera.prototype.serialize = function () {
  13578. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13579. // Type
  13580. serializationObject.type = this.getClassName();
  13581. // Parent
  13582. if (this.parent) {
  13583. serializationObject.parentId = this.parent.id;
  13584. }
  13585. if (this.inputs) {
  13586. this.inputs.serialize(serializationObject);
  13587. }
  13588. // Animations
  13589. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13590. serializationObject.ranges = this.serializeAnimationRanges();
  13591. return serializationObject;
  13592. };
  13593. Camera.prototype.clone = function (name) {
  13594. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  13595. };
  13596. Camera.prototype.getDirection = function (localAxis) {
  13597. var result = BABYLON.Vector3.Zero();
  13598. this.getDirectionToRef(localAxis, result);
  13599. return result;
  13600. };
  13601. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  13602. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13603. };
  13604. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  13605. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  13606. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  13607. switch (type) {
  13608. case "ArcRotateCamera":
  13609. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  13610. case "DeviceOrientationCamera":
  13611. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  13612. case "FollowCamera":
  13613. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  13614. case "ArcFollowCamera":
  13615. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  13616. case "GamepadCamera":
  13617. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13618. case "TouchCamera":
  13619. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  13620. case "VirtualJoysticksCamera":
  13621. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  13622. case "WebVRFreeCamera":
  13623. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13624. case "VRDeviceOrientationFreeCamera":
  13625. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13626. case "AnaglyphArcRotateCamera":
  13627. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13628. case "AnaglyphFreeCamera":
  13629. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13630. case "AnaglyphGamepadCamera":
  13631. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13632. case "AnaglyphUniversalCamera":
  13633. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13634. case "StereoscopicArcRotateCamera":
  13635. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13636. case "StereoscopicFreeCamera":
  13637. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13638. case "StereoscopicGamepadCamera":
  13639. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13640. case "StereoscopicUniversalCamera":
  13641. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13642. case "FreeCamera":
  13643. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13644. default:
  13645. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13646. }
  13647. };
  13648. Camera.Parse = function (parsedCamera, scene) {
  13649. var type = parsedCamera.type;
  13650. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13651. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13652. // Parent
  13653. if (parsedCamera.parentId) {
  13654. camera._waitingParentId = parsedCamera.parentId;
  13655. }
  13656. //If camera has an input manager, let it parse inputs settings
  13657. if (camera.inputs) {
  13658. camera.inputs.parse(parsedCamera);
  13659. camera._setupInputs();
  13660. }
  13661. // Target
  13662. if (parsedCamera.target) {
  13663. if (camera.setTarget) {
  13664. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13665. }
  13666. }
  13667. // Apply 3d rig, when found
  13668. if (parsedCamera.cameraRigMode) {
  13669. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13670. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13671. }
  13672. // Animations
  13673. if (parsedCamera.animations) {
  13674. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13675. var parsedAnimation = parsedCamera.animations[animationIndex];
  13676. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13677. }
  13678. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13679. }
  13680. if (parsedCamera.autoAnimate) {
  13681. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13682. }
  13683. return camera;
  13684. };
  13685. return Camera;
  13686. }(BABYLON.Node));
  13687. // Statics
  13688. Camera._PERSPECTIVE_CAMERA = 0;
  13689. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13690. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13691. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13692. Camera._RIG_MODE_NONE = 0;
  13693. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13694. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13695. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13696. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13697. Camera._RIG_MODE_VR = 20;
  13698. Camera._RIG_MODE_WEBVR = 21;
  13699. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13700. __decorate([
  13701. BABYLON.serializeAsVector3()
  13702. ], Camera.prototype, "position", void 0);
  13703. __decorate([
  13704. BABYLON.serializeAsVector3()
  13705. ], Camera.prototype, "upVector", void 0);
  13706. __decorate([
  13707. BABYLON.serialize()
  13708. ], Camera.prototype, "orthoLeft", void 0);
  13709. __decorate([
  13710. BABYLON.serialize()
  13711. ], Camera.prototype, "orthoRight", void 0);
  13712. __decorate([
  13713. BABYLON.serialize()
  13714. ], Camera.prototype, "orthoBottom", void 0);
  13715. __decorate([
  13716. BABYLON.serialize()
  13717. ], Camera.prototype, "orthoTop", void 0);
  13718. __decorate([
  13719. BABYLON.serialize()
  13720. ], Camera.prototype, "fov", void 0);
  13721. __decorate([
  13722. BABYLON.serialize()
  13723. ], Camera.prototype, "minZ", void 0);
  13724. __decorate([
  13725. BABYLON.serialize()
  13726. ], Camera.prototype, "maxZ", void 0);
  13727. __decorate([
  13728. BABYLON.serialize()
  13729. ], Camera.prototype, "inertia", void 0);
  13730. __decorate([
  13731. BABYLON.serialize()
  13732. ], Camera.prototype, "mode", void 0);
  13733. __decorate([
  13734. BABYLON.serialize()
  13735. ], Camera.prototype, "layerMask", void 0);
  13736. __decorate([
  13737. BABYLON.serialize()
  13738. ], Camera.prototype, "fovMode", void 0);
  13739. __decorate([
  13740. BABYLON.serialize()
  13741. ], Camera.prototype, "cameraRigMode", void 0);
  13742. __decorate([
  13743. BABYLON.serialize()
  13744. ], Camera.prototype, "interaxialDistance", void 0);
  13745. __decorate([
  13746. BABYLON.serialize()
  13747. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13748. BABYLON.Camera = Camera;
  13749. })(BABYLON || (BABYLON = {}));
  13750. //# sourceMappingURL=babylon.camera.js.map
  13751. var BABYLON;
  13752. (function (BABYLON) {
  13753. BABYLON.CameraInputTypes = {};
  13754. var CameraInputsManager = (function () {
  13755. function CameraInputsManager(camera) {
  13756. this.attached = {};
  13757. this.camera = camera;
  13758. this.checkInputs = function () { };
  13759. }
  13760. CameraInputsManager.prototype.add = function (input) {
  13761. var type = input.getSimpleName();
  13762. if (this.attached[type]) {
  13763. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  13764. return;
  13765. }
  13766. this.attached[type] = input;
  13767. input.camera = this.camera;
  13768. //for checkInputs, we are dynamically creating a function
  13769. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  13770. if (input.checkInputs) {
  13771. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13772. }
  13773. if (this.attachedElement) {
  13774. input.attachControl(this.attachedElement);
  13775. }
  13776. };
  13777. CameraInputsManager.prototype.remove = function (inputToRemove) {
  13778. for (var cam in this.attached) {
  13779. var input = this.attached[cam];
  13780. if (input === inputToRemove) {
  13781. input.detachControl(this.attachedElement);
  13782. delete this.attached[cam];
  13783. this.rebuildInputCheck();
  13784. }
  13785. }
  13786. };
  13787. CameraInputsManager.prototype.removeByType = function (inputType) {
  13788. for (var cam in this.attached) {
  13789. var input = this.attached[cam];
  13790. if (input.getTypeName() === inputType) {
  13791. input.detachControl(this.attachedElement);
  13792. delete this.attached[cam];
  13793. this.rebuildInputCheck();
  13794. }
  13795. }
  13796. };
  13797. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  13798. var current = this.checkInputs;
  13799. return function () {
  13800. current();
  13801. fn();
  13802. };
  13803. };
  13804. CameraInputsManager.prototype.attachInput = function (input) {
  13805. input.attachControl(this.attachedElement, this.noPreventDefault);
  13806. };
  13807. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  13808. if (this.attachedElement) {
  13809. return;
  13810. }
  13811. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  13812. this.attachedElement = element;
  13813. this.noPreventDefault = noPreventDefault;
  13814. for (var cam in this.attached) {
  13815. var input = this.attached[cam];
  13816. this.attached[cam].attachControl(element, noPreventDefault);
  13817. }
  13818. };
  13819. CameraInputsManager.prototype.detachElement = function (element) {
  13820. if (this.attachedElement !== element) {
  13821. return;
  13822. }
  13823. for (var cam in this.attached) {
  13824. var input = this.attached[cam];
  13825. this.attached[cam].detachControl(element);
  13826. }
  13827. this.attachedElement = null;
  13828. };
  13829. CameraInputsManager.prototype.rebuildInputCheck = function () {
  13830. this.checkInputs = function () { };
  13831. for (var cam in this.attached) {
  13832. var input = this.attached[cam];
  13833. if (input.checkInputs) {
  13834. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13835. }
  13836. }
  13837. };
  13838. CameraInputsManager.prototype.clear = function () {
  13839. if (this.attachedElement) {
  13840. this.detachElement(this.attachedElement);
  13841. }
  13842. this.attached = {};
  13843. this.attachedElement = null;
  13844. this.checkInputs = function () { };
  13845. };
  13846. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  13847. var inputs = {};
  13848. for (var cam in this.attached) {
  13849. var input = this.attached[cam];
  13850. var res = BABYLON.SerializationHelper.Serialize(input);
  13851. inputs[input.getTypeName()] = res;
  13852. }
  13853. serializedCamera.inputsmgr = inputs;
  13854. };
  13855. CameraInputsManager.prototype.parse = function (parsedCamera) {
  13856. var parsedInputs = parsedCamera.inputsmgr;
  13857. if (parsedInputs) {
  13858. this.clear();
  13859. for (var n in parsedInputs) {
  13860. var construct = BABYLON.CameraInputTypes[n];
  13861. if (construct) {
  13862. var parsedinput = parsedInputs[n];
  13863. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  13864. this.add(input);
  13865. }
  13866. }
  13867. }
  13868. else {
  13869. //2016-03-08 this part is for managing backward compatibility
  13870. for (var n in this.attached) {
  13871. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  13872. if (construct) {
  13873. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  13874. this.remove(this.attached[n]);
  13875. this.add(input);
  13876. }
  13877. }
  13878. }
  13879. };
  13880. return CameraInputsManager;
  13881. }());
  13882. BABYLON.CameraInputsManager = CameraInputsManager;
  13883. })(BABYLON || (BABYLON = {}));
  13884. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  13885. var BABYLON;
  13886. (function (BABYLON) {
  13887. var FreeCameraMouseInput = (function () {
  13888. function FreeCameraMouseInput(touchEnabled) {
  13889. if (touchEnabled === void 0) { touchEnabled = true; }
  13890. this.touchEnabled = touchEnabled;
  13891. this.buttons = [0, 1, 2];
  13892. this.angularSensibility = 2000.0;
  13893. }
  13894. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  13895. var _this = this;
  13896. var engine = this.camera.getEngine();
  13897. if (!this._pointerInput) {
  13898. this._pointerInput = function (p, s) {
  13899. var evt = p.event;
  13900. if (!_this.touchEnabled && evt.pointerType === "touch") {
  13901. return;
  13902. }
  13903. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  13904. return;
  13905. }
  13906. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13907. try {
  13908. evt.srcElement.setPointerCapture(evt.pointerId);
  13909. }
  13910. catch (e) {
  13911. }
  13912. _this.previousPosition = {
  13913. x: evt.clientX,
  13914. y: evt.clientY
  13915. };
  13916. if (!noPreventDefault) {
  13917. evt.preventDefault();
  13918. element.focus();
  13919. }
  13920. }
  13921. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13922. try {
  13923. evt.srcElement.releasePointerCapture(evt.pointerId);
  13924. }
  13925. catch (e) {
  13926. }
  13927. _this.previousPosition = null;
  13928. if (!noPreventDefault) {
  13929. evt.preventDefault();
  13930. }
  13931. }
  13932. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13933. if (!_this.previousPosition || engine.isPointerLock) {
  13934. return;
  13935. }
  13936. var offsetX = evt.clientX - _this.previousPosition.x;
  13937. var offsetY = evt.clientY - _this.previousPosition.y;
  13938. if (_this.camera.getScene().useRightHandedSystem) {
  13939. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13940. }
  13941. else {
  13942. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13943. }
  13944. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13945. _this.previousPosition = {
  13946. x: evt.clientX,
  13947. y: evt.clientY
  13948. };
  13949. if (!noPreventDefault) {
  13950. evt.preventDefault();
  13951. }
  13952. }
  13953. };
  13954. }
  13955. this._onMouseMove = function (evt) {
  13956. if (!engine.isPointerLock) {
  13957. return;
  13958. }
  13959. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13960. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13961. if (_this.camera.getScene().useRightHandedSystem) {
  13962. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13963. }
  13964. else {
  13965. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13966. }
  13967. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13968. _this.previousPosition = null;
  13969. if (!noPreventDefault) {
  13970. evt.preventDefault();
  13971. }
  13972. };
  13973. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13974. element.addEventListener("mousemove", this._onMouseMove, false);
  13975. };
  13976. FreeCameraMouseInput.prototype.detachControl = function (element) {
  13977. if (this._observer && element) {
  13978. this.camera.getScene().onPointerObservable.remove(this._observer);
  13979. element.removeEventListener("mousemove", this._onMouseMove);
  13980. this._observer = null;
  13981. this._onMouseMove = null;
  13982. this.previousPosition = null;
  13983. }
  13984. };
  13985. FreeCameraMouseInput.prototype.getTypeName = function () {
  13986. return "FreeCameraMouseInput";
  13987. };
  13988. FreeCameraMouseInput.prototype.getSimpleName = function () {
  13989. return "mouse";
  13990. };
  13991. return FreeCameraMouseInput;
  13992. }());
  13993. __decorate([
  13994. BABYLON.serialize()
  13995. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  13996. __decorate([
  13997. BABYLON.serialize()
  13998. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  13999. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  14000. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  14001. })(BABYLON || (BABYLON = {}));
  14002. //# sourceMappingURL=babylon.freecamera.input.mouse.js.map
  14003. var BABYLON;
  14004. (function (BABYLON) {
  14005. var FreeCameraKeyboardMoveInput = (function () {
  14006. function FreeCameraKeyboardMoveInput() {
  14007. this._keys = [];
  14008. this.keysUp = [38];
  14009. this.keysDown = [40];
  14010. this.keysLeft = [37];
  14011. this.keysRight = [39];
  14012. }
  14013. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  14014. var _this = this;
  14015. if (!this._onKeyDown) {
  14016. element.tabIndex = 1;
  14017. this._onKeyDown = function (evt) {
  14018. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14019. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14020. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14021. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14022. var index = _this._keys.indexOf(evt.keyCode);
  14023. if (index === -1) {
  14024. _this._keys.push(evt.keyCode);
  14025. }
  14026. if (!noPreventDefault) {
  14027. evt.preventDefault();
  14028. }
  14029. }
  14030. };
  14031. this._onKeyUp = function (evt) {
  14032. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14033. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14034. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14035. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14036. var index = _this._keys.indexOf(evt.keyCode);
  14037. if (index >= 0) {
  14038. _this._keys.splice(index, 1);
  14039. }
  14040. if (!noPreventDefault) {
  14041. evt.preventDefault();
  14042. }
  14043. }
  14044. };
  14045. element.addEventListener("keydown", this._onKeyDown, false);
  14046. element.addEventListener("keyup", this._onKeyUp, false);
  14047. BABYLON.Tools.RegisterTopRootEvents([
  14048. { name: "blur", handler: this._onLostFocus }
  14049. ]);
  14050. }
  14051. };
  14052. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  14053. if (this._onKeyDown) {
  14054. element.removeEventListener("keydown", this._onKeyDown);
  14055. element.removeEventListener("keyup", this._onKeyUp);
  14056. BABYLON.Tools.UnregisterTopRootEvents([
  14057. { name: "blur", handler: this._onLostFocus }
  14058. ]);
  14059. this._keys = [];
  14060. this._onKeyDown = null;
  14061. this._onKeyUp = null;
  14062. }
  14063. };
  14064. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  14065. if (this._onKeyDown) {
  14066. var camera = this.camera;
  14067. // Keyboard
  14068. for (var index = 0; index < this._keys.length; index++) {
  14069. var keyCode = this._keys[index];
  14070. var speed = camera._computeLocalCameraSpeed();
  14071. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14072. camera._localDirection.copyFromFloats(-speed, 0, 0);
  14073. }
  14074. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14075. camera._localDirection.copyFromFloats(0, 0, speed);
  14076. }
  14077. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14078. camera._localDirection.copyFromFloats(speed, 0, 0);
  14079. }
  14080. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14081. camera._localDirection.copyFromFloats(0, 0, -speed);
  14082. }
  14083. if (camera.getScene().useRightHandedSystem) {
  14084. camera._localDirection.z *= -1;
  14085. }
  14086. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  14087. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  14088. camera.cameraDirection.addInPlace(camera._transformedDirection);
  14089. }
  14090. }
  14091. };
  14092. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14093. return "FreeCameraKeyboardMoveInput";
  14094. };
  14095. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  14096. this._keys = [];
  14097. };
  14098. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14099. return "keyboard";
  14100. };
  14101. return FreeCameraKeyboardMoveInput;
  14102. }());
  14103. __decorate([
  14104. BABYLON.serialize()
  14105. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14106. __decorate([
  14107. BABYLON.serialize()
  14108. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14109. __decorate([
  14110. BABYLON.serialize()
  14111. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14112. __decorate([
  14113. BABYLON.serialize()
  14114. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14115. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  14116. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  14117. })(BABYLON || (BABYLON = {}));
  14118. //# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
  14119. var BABYLON;
  14120. (function (BABYLON) {
  14121. var FreeCameraTouchInput = (function () {
  14122. function FreeCameraTouchInput() {
  14123. this._offsetX = null;
  14124. this._offsetY = null;
  14125. this._pointerCount = 0;
  14126. this._pointerPressed = [];
  14127. this.touchAngularSensibility = 200000.0;
  14128. this.touchMoveSensibility = 250.0;
  14129. }
  14130. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  14131. var _this = this;
  14132. var previousPosition;
  14133. if (this._pointerInput === undefined) {
  14134. this._onLostFocus = function (evt) {
  14135. _this._offsetX = null;
  14136. _this._offsetY = null;
  14137. };
  14138. this._pointerInput = function (p, s) {
  14139. var evt = p.event;
  14140. if (evt.pointerType === "mouse") {
  14141. return;
  14142. }
  14143. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14144. if (!noPreventDefault) {
  14145. evt.preventDefault();
  14146. }
  14147. _this._pointerPressed.push(evt.pointerId);
  14148. if (_this._pointerPressed.length !== 1) {
  14149. return;
  14150. }
  14151. previousPosition = {
  14152. x: evt.clientX,
  14153. y: evt.clientY
  14154. };
  14155. }
  14156. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14157. if (!noPreventDefault) {
  14158. evt.preventDefault();
  14159. }
  14160. var index = _this._pointerPressed.indexOf(evt.pointerId);
  14161. if (index === -1) {
  14162. return;
  14163. }
  14164. _this._pointerPressed.splice(index, 1);
  14165. if (index != 0) {
  14166. return;
  14167. }
  14168. previousPosition = null;
  14169. _this._offsetX = null;
  14170. _this._offsetY = null;
  14171. }
  14172. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14173. if (!noPreventDefault) {
  14174. evt.preventDefault();
  14175. }
  14176. if (!previousPosition) {
  14177. return;
  14178. }
  14179. var index = _this._pointerPressed.indexOf(evt.pointerId);
  14180. if (index != 0) {
  14181. return;
  14182. }
  14183. _this._offsetX = evt.clientX - previousPosition.x;
  14184. _this._offsetY = -(evt.clientY - previousPosition.y);
  14185. }
  14186. };
  14187. }
  14188. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14189. element.addEventListener("blur", this._onLostFocus);
  14190. };
  14191. FreeCameraTouchInput.prototype.detachControl = function (element) {
  14192. if (this._pointerInput && element) {
  14193. this.camera.getScene().onPointerObservable.remove(this._observer);
  14194. this._observer = null;
  14195. element.removeEventListener("blur", this._onLostFocus);
  14196. this._onLostFocus = null;
  14197. this._pointerPressed = [];
  14198. this._offsetX = null;
  14199. this._offsetY = null;
  14200. this._pointerCount = 0;
  14201. }
  14202. };
  14203. FreeCameraTouchInput.prototype.checkInputs = function () {
  14204. if (this._offsetX) {
  14205. var camera = this.camera;
  14206. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  14207. if (this._pointerPressed.length > 1) {
  14208. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  14209. }
  14210. else {
  14211. var speed = camera._computeLocalCameraSpeed();
  14212. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  14213. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  14214. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  14215. }
  14216. }
  14217. };
  14218. FreeCameraTouchInput.prototype.getTypeName = function () {
  14219. return "FreeCameraTouchInput";
  14220. };
  14221. FreeCameraTouchInput.prototype.getSimpleName = function () {
  14222. return "touch";
  14223. };
  14224. return FreeCameraTouchInput;
  14225. }());
  14226. __decorate([
  14227. BABYLON.serialize()
  14228. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  14229. __decorate([
  14230. BABYLON.serialize()
  14231. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  14232. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  14233. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  14234. })(BABYLON || (BABYLON = {}));
  14235. //# sourceMappingURL=babylon.freecamera.input.touch.js.map
  14236. var BABYLON;
  14237. (function (BABYLON) {
  14238. var FreeCameraDeviceOrientationInput = (function () {
  14239. function FreeCameraDeviceOrientationInput() {
  14240. var _this = this;
  14241. this._screenOrientationAngle = 0;
  14242. this._screenQuaternion = new BABYLON.Quaternion();
  14243. this._alpha = 0;
  14244. this._beta = 0;
  14245. this._gamma = 0;
  14246. this._orientationChanged = function () {
  14247. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  14248. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  14249. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  14250. };
  14251. this._deviceOrientation = function (evt) {
  14252. _this._alpha = evt.alpha;
  14253. _this._beta = evt.beta;
  14254. _this._gamma = evt.gamma;
  14255. };
  14256. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  14257. this._orientationChanged();
  14258. }
  14259. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  14260. get: function () {
  14261. return this._camera;
  14262. },
  14263. set: function (camera) {
  14264. this._camera = camera;
  14265. if (!this._camera.rotationQuaternion)
  14266. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  14267. },
  14268. enumerable: true,
  14269. configurable: true
  14270. });
  14271. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14272. window.addEventListener("orientationchange", this._orientationChanged);
  14273. window.addEventListener("deviceorientation", this._deviceOrientation);
  14274. //In certain cases, the attach control is called AFTER orientation was changed,
  14275. //So this is needed.
  14276. this._orientationChanged();
  14277. };
  14278. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  14279. window.removeEventListener("orientationchange", this._orientationChanged);
  14280. window.removeEventListener("deviceorientation", this._deviceOrientation);
  14281. };
  14282. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  14283. //if no device orientation provided, don't update the rotation.
  14284. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  14285. if (!this._alpha)
  14286. return;
  14287. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  14288. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  14289. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  14290. //Mirror on XY Plane
  14291. this._camera.rotationQuaternion.z *= -1;
  14292. this._camera.rotationQuaternion.w *= -1;
  14293. };
  14294. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  14295. return "FreeCameraDeviceOrientationInput";
  14296. };
  14297. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  14298. return "deviceOrientation";
  14299. };
  14300. return FreeCameraDeviceOrientationInput;
  14301. }());
  14302. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  14303. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  14304. })(BABYLON || (BABYLON = {}));
  14305. //# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
  14306. var BABYLON;
  14307. (function (BABYLON) {
  14308. var FreeCameraGamepadInput = (function () {
  14309. function FreeCameraGamepadInput() {
  14310. this.gamepadAngularSensibility = 200;
  14311. this.gamepadMoveSensibility = 40;
  14312. }
  14313. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14314. var _this = this;
  14315. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14316. };
  14317. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  14318. if (this._gamepads) {
  14319. this._gamepads.dispose();
  14320. }
  14321. this.gamepad = null;
  14322. };
  14323. FreeCameraGamepadInput.prototype.checkInputs = function () {
  14324. if (this.gamepad) {
  14325. var camera = this.camera;
  14326. var LSValues = this.gamepad.leftStick;
  14327. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  14328. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14329. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  14330. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  14331. var RSValues = this.gamepad.rightStick;
  14332. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  14333. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  14334. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  14335. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  14336. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  14337. var speed = camera._computeLocalCameraSpeed() * 50.0;
  14338. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  14339. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  14340. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  14341. }
  14342. };
  14343. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14344. // Only the first gamepad can control the camera
  14345. if (gamepad.index === 0) {
  14346. this.gamepad = gamepad;
  14347. }
  14348. };
  14349. FreeCameraGamepadInput.prototype.getTypeName = function () {
  14350. return "FreeCameraGamepadInput";
  14351. };
  14352. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  14353. return "gamepad";
  14354. };
  14355. return FreeCameraGamepadInput;
  14356. }());
  14357. __decorate([
  14358. BABYLON.serialize()
  14359. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  14360. __decorate([
  14361. BABYLON.serialize()
  14362. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14363. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  14364. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  14365. })(BABYLON || (BABYLON = {}));
  14366. //# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
  14367. var BABYLON;
  14368. (function (BABYLON) {
  14369. var ArcRotateCameraKeyboardMoveInput = (function () {
  14370. function ArcRotateCameraKeyboardMoveInput() {
  14371. this._keys = [];
  14372. this.keysUp = [38];
  14373. this.keysDown = [40];
  14374. this.keysLeft = [37];
  14375. this.keysRight = [39];
  14376. }
  14377. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  14378. var _this = this;
  14379. element.tabIndex = 1;
  14380. this._onKeyDown = function (evt) {
  14381. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14382. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14383. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14384. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14385. var index = _this._keys.indexOf(evt.keyCode);
  14386. if (index === -1) {
  14387. _this._keys.push(evt.keyCode);
  14388. }
  14389. if (evt.preventDefault) {
  14390. if (!noPreventDefault) {
  14391. evt.preventDefault();
  14392. }
  14393. }
  14394. }
  14395. };
  14396. this._onKeyUp = function (evt) {
  14397. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14398. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14399. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14400. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14401. var index = _this._keys.indexOf(evt.keyCode);
  14402. if (index >= 0) {
  14403. _this._keys.splice(index, 1);
  14404. }
  14405. if (evt.preventDefault) {
  14406. if (!noPreventDefault) {
  14407. evt.preventDefault();
  14408. }
  14409. }
  14410. }
  14411. };
  14412. this._onLostFocus = function () {
  14413. _this._keys = [];
  14414. };
  14415. element.addEventListener("keydown", this._onKeyDown, false);
  14416. element.addEventListener("keyup", this._onKeyUp, false);
  14417. BABYLON.Tools.RegisterTopRootEvents([
  14418. { name: "blur", handler: this._onLostFocus }
  14419. ]);
  14420. };
  14421. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  14422. if (element) {
  14423. element.removeEventListener("keydown", this._onKeyDown);
  14424. element.removeEventListener("keyup", this._onKeyUp);
  14425. }
  14426. BABYLON.Tools.UnregisterTopRootEvents([
  14427. { name: "blur", handler: this._onLostFocus }
  14428. ]);
  14429. this._keys = [];
  14430. this._onKeyDown = null;
  14431. this._onKeyUp = null;
  14432. this._onLostFocus = null;
  14433. };
  14434. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  14435. if (this._onKeyDown) {
  14436. var camera = this.camera;
  14437. for (var index = 0; index < this._keys.length; index++) {
  14438. var keyCode = this._keys[index];
  14439. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14440. camera.inertialAlphaOffset -= 0.01;
  14441. }
  14442. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14443. camera.inertialBetaOffset -= 0.01;
  14444. }
  14445. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14446. camera.inertialAlphaOffset += 0.01;
  14447. }
  14448. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14449. camera.inertialBetaOffset += 0.01;
  14450. }
  14451. }
  14452. }
  14453. };
  14454. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14455. return "ArcRotateCameraKeyboardMoveInput";
  14456. };
  14457. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14458. return "keyboard";
  14459. };
  14460. return ArcRotateCameraKeyboardMoveInput;
  14461. }());
  14462. __decorate([
  14463. BABYLON.serialize()
  14464. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14465. __decorate([
  14466. BABYLON.serialize()
  14467. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14468. __decorate([
  14469. BABYLON.serialize()
  14470. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14471. __decorate([
  14472. BABYLON.serialize()
  14473. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14474. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  14475. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  14476. })(BABYLON || (BABYLON = {}));
  14477. //# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
  14478. var BABYLON;
  14479. (function (BABYLON) {
  14480. var ArcRotateCameraMouseWheelInput = (function () {
  14481. function ArcRotateCameraMouseWheelInput() {
  14482. this.wheelPrecision = 3.0;
  14483. }
  14484. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  14485. var _this = this;
  14486. this._wheel = function (p, s) {
  14487. //sanity check - this should be a PointerWheel event.
  14488. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  14489. return;
  14490. var event = p.event;
  14491. var delta = 0;
  14492. if (event.wheelDelta) {
  14493. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  14494. }
  14495. else if (event.detail) {
  14496. delta = -event.detail / _this.wheelPrecision;
  14497. }
  14498. if (delta)
  14499. _this.camera.inertialRadiusOffset += delta;
  14500. if (event.preventDefault) {
  14501. if (!noPreventDefault) {
  14502. event.preventDefault();
  14503. }
  14504. }
  14505. };
  14506. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  14507. };
  14508. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  14509. if (this._observer && element) {
  14510. this.camera.getScene().onPointerObservable.remove(this._observer);
  14511. this._observer = null;
  14512. this._wheel = null;
  14513. }
  14514. };
  14515. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  14516. return "ArcRotateCameraMouseWheelInput";
  14517. };
  14518. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  14519. return "mousewheel";
  14520. };
  14521. return ArcRotateCameraMouseWheelInput;
  14522. }());
  14523. __decorate([
  14524. BABYLON.serialize()
  14525. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  14526. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  14527. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  14528. })(BABYLON || (BABYLON = {}));
  14529. //# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
  14530. var BABYLON;
  14531. (function (BABYLON) {
  14532. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14533. var ArcRotateCameraPointersInput = (function () {
  14534. function ArcRotateCameraPointersInput() {
  14535. this.buttons = [0, 1, 2];
  14536. this.angularSensibilityX = 1000.0;
  14537. this.angularSensibilityY = 1000.0;
  14538. this.pinchPrecision = 6.0;
  14539. this.panningSensibility = 50.0;
  14540. this._isPanClick = false;
  14541. this.pinchInwards = true;
  14542. }
  14543. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  14544. var _this = this;
  14545. var engine = this.camera.getEngine();
  14546. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  14547. var pointA, pointB;
  14548. var previousPinchDistance = 0;
  14549. this._pointerInput = function (p, s) {
  14550. var evt = p.event;
  14551. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  14552. return;
  14553. }
  14554. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14555. try {
  14556. evt.srcElement.setPointerCapture(evt.pointerId);
  14557. }
  14558. catch (e) {
  14559. }
  14560. // Manage panning with pan button click
  14561. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  14562. // manage pointers
  14563. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  14564. if (pointA === undefined) {
  14565. pointA = cacheSoloPointer;
  14566. }
  14567. else if (pointB === undefined) {
  14568. pointB = cacheSoloPointer;
  14569. }
  14570. if (!noPreventDefault) {
  14571. evt.preventDefault();
  14572. element.focus();
  14573. }
  14574. }
  14575. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14576. try {
  14577. evt.srcElement.releasePointerCapture(evt.pointerId);
  14578. }
  14579. catch (e) {
  14580. }
  14581. cacheSoloPointer = null;
  14582. previousPinchDistance = 0;
  14583. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  14584. //but emptying completly pointers collection is required to fix a bug on iPhone :
  14585. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  14586. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  14587. pointA = pointB = undefined;
  14588. if (!noPreventDefault) {
  14589. evt.preventDefault();
  14590. }
  14591. }
  14592. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14593. if (!noPreventDefault) {
  14594. evt.preventDefault();
  14595. }
  14596. // One button down
  14597. if (pointA && pointB === undefined) {
  14598. if (_this.panningSensibility !== 0 &&
  14599. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  14600. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  14601. _this.camera
  14602. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  14603. _this.camera
  14604. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  14605. }
  14606. else {
  14607. var offsetX = evt.clientX - cacheSoloPointer.x;
  14608. var offsetY = evt.clientY - cacheSoloPointer.y;
  14609. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14610. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14611. }
  14612. cacheSoloPointer.x = evt.clientX;
  14613. cacheSoloPointer.y = evt.clientY;
  14614. }
  14615. else if (pointA && pointB) {
  14616. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  14617. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  14618. ed.x = evt.clientX;
  14619. ed.y = evt.clientY;
  14620. var direction = _this.pinchInwards ? 1 : -1;
  14621. var distX = pointA.x - pointB.x;
  14622. var distY = pointA.y - pointB.y;
  14623. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  14624. if (previousPinchDistance === 0) {
  14625. previousPinchDistance = pinchSquaredDistance;
  14626. return;
  14627. }
  14628. if (pinchSquaredDistance !== previousPinchDistance) {
  14629. _this.camera
  14630. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  14631. (_this.pinchPrecision *
  14632. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  14633. direction);
  14634. previousPinchDistance = pinchSquaredDistance;
  14635. }
  14636. }
  14637. }
  14638. };
  14639. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14640. this._onContextMenu = function (evt) {
  14641. evt.preventDefault();
  14642. };
  14643. if (!this.camera._useCtrlForPanning) {
  14644. element.addEventListener("contextmenu", this._onContextMenu, false);
  14645. }
  14646. this._onLostFocus = function () {
  14647. //this._keys = [];
  14648. pointA = pointB = undefined;
  14649. previousPinchDistance = 0;
  14650. cacheSoloPointer = null;
  14651. };
  14652. this._onMouseMove = function (evt) {
  14653. if (!engine.isPointerLock) {
  14654. return;
  14655. }
  14656. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  14657. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  14658. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14659. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14660. if (!noPreventDefault) {
  14661. evt.preventDefault();
  14662. }
  14663. };
  14664. this._onGestureStart = function (e) {
  14665. if (window.MSGesture === undefined) {
  14666. return;
  14667. }
  14668. if (!_this._MSGestureHandler) {
  14669. _this._MSGestureHandler = new MSGesture();
  14670. _this._MSGestureHandler.target = element;
  14671. }
  14672. _this._MSGestureHandler.addPointer(e.pointerId);
  14673. };
  14674. this._onGesture = function (e) {
  14675. _this.camera.radius *= e.scale;
  14676. if (e.preventDefault) {
  14677. if (!noPreventDefault) {
  14678. e.stopPropagation();
  14679. e.preventDefault();
  14680. }
  14681. }
  14682. };
  14683. element.addEventListener("mousemove", this._onMouseMove, false);
  14684. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  14685. element.addEventListener("MSGestureChange", this._onGesture, false);
  14686. element.addEventListener("keydown", this._onKeyDown, false);
  14687. element.addEventListener("keyup", this._onKeyUp, false);
  14688. BABYLON.Tools.RegisterTopRootEvents([
  14689. { name: "blur", handler: this._onLostFocus }
  14690. ]);
  14691. };
  14692. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  14693. if (element && this._observer) {
  14694. this.camera.getScene().onPointerObservable.remove(this._observer);
  14695. this._observer = null;
  14696. element.removeEventListener("contextmenu", this._onContextMenu);
  14697. element.removeEventListener("mousemove", this._onMouseMove);
  14698. element.removeEventListener("MSPointerDown", this._onGestureStart);
  14699. element.removeEventListener("MSGestureChange", this._onGesture);
  14700. element.removeEventListener("keydown", this._onKeyDown);
  14701. element.removeEventListener("keyup", this._onKeyUp);
  14702. this._isPanClick = false;
  14703. this.pinchInwards = true;
  14704. this._onKeyDown = null;
  14705. this._onKeyUp = null;
  14706. this._onMouseMove = null;
  14707. this._onGestureStart = null;
  14708. this._onGesture = null;
  14709. this._MSGestureHandler = null;
  14710. this._onLostFocus = null;
  14711. this._onContextMenu = null;
  14712. }
  14713. BABYLON.Tools.UnregisterTopRootEvents([
  14714. { name: "blur", handler: this._onLostFocus }
  14715. ]);
  14716. };
  14717. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  14718. return "ArcRotateCameraPointersInput";
  14719. };
  14720. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  14721. return "pointers";
  14722. };
  14723. return ArcRotateCameraPointersInput;
  14724. }());
  14725. __decorate([
  14726. BABYLON.serialize()
  14727. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  14728. __decorate([
  14729. BABYLON.serialize()
  14730. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  14731. __decorate([
  14732. BABYLON.serialize()
  14733. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  14734. __decorate([
  14735. BABYLON.serialize()
  14736. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  14737. __decorate([
  14738. BABYLON.serialize()
  14739. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  14740. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  14741. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  14742. })(BABYLON || (BABYLON = {}));
  14743. //# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
  14744. var BABYLON;
  14745. (function (BABYLON) {
  14746. var ArcRotateCameraGamepadInput = (function () {
  14747. function ArcRotateCameraGamepadInput() {
  14748. this.gamepadRotationSensibility = 80;
  14749. this.gamepadMoveSensibility = 40;
  14750. }
  14751. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14752. var _this = this;
  14753. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14754. };
  14755. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  14756. if (this._gamepads) {
  14757. this._gamepads.dispose();
  14758. }
  14759. this.gamepad = null;
  14760. };
  14761. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  14762. if (this.gamepad) {
  14763. var camera = this.camera;
  14764. var RSValues = this.gamepad.rightStick;
  14765. if (RSValues.x != 0) {
  14766. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  14767. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  14768. camera.inertialAlphaOffset += normalizedRX;
  14769. }
  14770. }
  14771. if (RSValues.y != 0) {
  14772. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  14773. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  14774. camera.inertialBetaOffset += normalizedRY;
  14775. }
  14776. }
  14777. var LSValues = this.gamepad.leftStick;
  14778. if (LSValues.y != 0) {
  14779. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14780. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  14781. this.camera.inertialRadiusOffset -= normalizedLY;
  14782. }
  14783. }
  14784. }
  14785. };
  14786. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14787. // Only the first gamepad can control the camera
  14788. if (gamepad.index === 0) {
  14789. this.gamepad = gamepad;
  14790. }
  14791. };
  14792. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  14793. return "ArcRotateCameraGamepadInput";
  14794. };
  14795. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  14796. return "gamepad";
  14797. };
  14798. return ArcRotateCameraGamepadInput;
  14799. }());
  14800. __decorate([
  14801. BABYLON.serialize()
  14802. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  14803. __decorate([
  14804. BABYLON.serialize()
  14805. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14806. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  14807. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  14808. })(BABYLON || (BABYLON = {}));
  14809. //# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
  14810. var BABYLON;
  14811. (function (BABYLON) {
  14812. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  14813. function ArcRotateCameraVRDeviceOrientationInput() {
  14814. this.alphaCorrection = 1;
  14815. this.betaCorrection = 1;
  14816. this.gammaCorrection = 1;
  14817. this._alpha = 0;
  14818. this._beta = 0;
  14819. this._gamma = 0;
  14820. this._dirty = false;
  14821. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  14822. }
  14823. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14824. this.camera.attachControl(element, noPreventDefault);
  14825. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  14826. };
  14827. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  14828. var camera = this.camera;
  14829. this._alpha = +evt.alpha | 0;
  14830. this._beta = +evt.beta | 0;
  14831. this._gamma = +evt.gamma | 0;
  14832. this._dirty = true;
  14833. };
  14834. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  14835. if (this._dirty) {
  14836. this._dirty = false;
  14837. if (this._gamma < 0) {
  14838. this._gamma = 180 + this._gamma;
  14839. }
  14840. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  14841. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  14842. }
  14843. };
  14844. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  14845. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  14846. };
  14847. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  14848. return "ArcRotateCameraVRDeviceOrientationInput";
  14849. };
  14850. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  14851. return "VRDeviceOrientation";
  14852. };
  14853. return ArcRotateCameraVRDeviceOrientationInput;
  14854. }());
  14855. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  14856. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  14857. })(BABYLON || (BABYLON = {}));
  14858. //# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
  14859. var BABYLON;
  14860. (function (BABYLON) {
  14861. var TargetCamera = (function (_super) {
  14862. __extends(TargetCamera, _super);
  14863. function TargetCamera(name, position, scene) {
  14864. var _this = _super.call(this, name, position, scene) || this;
  14865. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14866. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  14867. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  14868. _this.speed = 2.0;
  14869. _this.noRotationConstraint = false;
  14870. _this.lockedTarget = null;
  14871. _this._currentTarget = BABYLON.Vector3.Zero();
  14872. _this._viewMatrix = BABYLON.Matrix.Zero();
  14873. _this._camMatrix = BABYLON.Matrix.Zero();
  14874. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  14875. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  14876. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  14877. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  14878. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  14879. _this._lookAtTemp = BABYLON.Matrix.Zero();
  14880. _this._tempMatrix = BABYLON.Matrix.Zero();
  14881. return _this;
  14882. }
  14883. TargetCamera.prototype.getFrontPosition = function (distance) {
  14884. var direction = this.getTarget().subtract(this.position);
  14885. direction.normalize();
  14886. direction.scaleInPlace(distance);
  14887. return this.globalPosition.add(direction);
  14888. };
  14889. TargetCamera.prototype._getLockedTargetPosition = function () {
  14890. if (!this.lockedTarget) {
  14891. return null;
  14892. }
  14893. if (this.lockedTarget.absolutePosition) {
  14894. this.lockedTarget.computeWorldMatrix();
  14895. }
  14896. return this.lockedTarget.absolutePosition || this.lockedTarget;
  14897. };
  14898. // Cache
  14899. TargetCamera.prototype._initCache = function () {
  14900. _super.prototype._initCache.call(this);
  14901. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14902. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14903. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14904. };
  14905. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  14906. if (!ignoreParentClass) {
  14907. _super.prototype._updateCache.call(this);
  14908. }
  14909. var lockedTargetPosition = this._getLockedTargetPosition();
  14910. if (!lockedTargetPosition) {
  14911. this._cache.lockedTarget = null;
  14912. }
  14913. else {
  14914. if (!this._cache.lockedTarget) {
  14915. this._cache.lockedTarget = lockedTargetPosition.clone();
  14916. }
  14917. else {
  14918. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  14919. }
  14920. }
  14921. this._cache.rotation.copyFrom(this.rotation);
  14922. if (this.rotationQuaternion)
  14923. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14924. };
  14925. // Synchronized
  14926. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  14927. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  14928. return false;
  14929. }
  14930. var lockedTargetPosition = this._getLockedTargetPosition();
  14931. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  14932. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  14933. };
  14934. // Methods
  14935. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  14936. var engine = this.getEngine();
  14937. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  14938. };
  14939. // Target
  14940. TargetCamera.prototype.setTarget = function (target) {
  14941. this.upVector.normalize();
  14942. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  14943. this._camMatrix.invert();
  14944. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  14945. var vDir = target.subtract(this.position);
  14946. if (vDir.x >= 0.0) {
  14947. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  14948. }
  14949. else {
  14950. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  14951. }
  14952. this.rotation.z = 0;
  14953. if (isNaN(this.rotation.x)) {
  14954. this.rotation.x = 0;
  14955. }
  14956. if (isNaN(this.rotation.y)) {
  14957. this.rotation.y = 0;
  14958. }
  14959. if (isNaN(this.rotation.z)) {
  14960. this.rotation.z = 0;
  14961. }
  14962. if (this.rotationQuaternion) {
  14963. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  14964. }
  14965. };
  14966. TargetCamera.prototype.getTarget = function () {
  14967. return this._currentTarget;
  14968. };
  14969. TargetCamera.prototype._decideIfNeedsToMove = function () {
  14970. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14971. };
  14972. TargetCamera.prototype._updatePosition = function () {
  14973. this.position.addInPlace(this.cameraDirection);
  14974. };
  14975. TargetCamera.prototype._checkInputs = function () {
  14976. var needToMove = this._decideIfNeedsToMove();
  14977. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  14978. // Move
  14979. if (needToMove) {
  14980. this._updatePosition();
  14981. }
  14982. // Rotate
  14983. if (needToRotate) {
  14984. this.rotation.x += this.cameraRotation.x;
  14985. this.rotation.y += this.cameraRotation.y;
  14986. if (!this.noRotationConstraint) {
  14987. var limit = (Math.PI / 2) * 0.95;
  14988. if (this.rotation.x > limit)
  14989. this.rotation.x = limit;
  14990. if (this.rotation.x < -limit)
  14991. this.rotation.x = -limit;
  14992. }
  14993. }
  14994. // Inertia
  14995. if (needToMove) {
  14996. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  14997. this.cameraDirection.x = 0;
  14998. }
  14999. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  15000. this.cameraDirection.y = 0;
  15001. }
  15002. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  15003. this.cameraDirection.z = 0;
  15004. }
  15005. this.cameraDirection.scaleInPlace(this.inertia);
  15006. }
  15007. if (needToRotate) {
  15008. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  15009. this.cameraRotation.x = 0;
  15010. }
  15011. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  15012. this.cameraRotation.y = 0;
  15013. }
  15014. this.cameraRotation.scaleInPlace(this.inertia);
  15015. }
  15016. _super.prototype._checkInputs.call(this);
  15017. };
  15018. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  15019. if (this.rotationQuaternion) {
  15020. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  15021. //update the up vector!
  15022. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  15023. }
  15024. else {
  15025. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  15026. }
  15027. };
  15028. TargetCamera.prototype._getViewMatrix = function () {
  15029. if (!this.lockedTarget) {
  15030. // Compute
  15031. this._updateCameraRotationMatrix();
  15032. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  15033. // Computing target and final matrix
  15034. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  15035. }
  15036. else {
  15037. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  15038. }
  15039. if (this.getScene().useRightHandedSystem) {
  15040. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  15041. }
  15042. else {
  15043. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  15044. }
  15045. return this._viewMatrix;
  15046. };
  15047. /**
  15048. * @override
  15049. * Override Camera.createRigCamera
  15050. */
  15051. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15052. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  15053. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  15054. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  15055. if (!this.rotationQuaternion) {
  15056. this.rotationQuaternion = new BABYLON.Quaternion();
  15057. }
  15058. rigCamera._cameraRigParams = {};
  15059. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  15060. }
  15061. return rigCamera;
  15062. }
  15063. return null;
  15064. };
  15065. /**
  15066. * @override
  15067. * Override Camera._updateRigCameras
  15068. */
  15069. TargetCamera.prototype._updateRigCameras = function () {
  15070. var camLeft = this._rigCameras[0];
  15071. var camRight = this._rigCameras[1];
  15072. switch (this.cameraRigMode) {
  15073. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15074. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15075. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15076. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15077. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  15078. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  15079. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  15080. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  15081. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  15082. camLeft.setTarget(this.getTarget());
  15083. camRight.setTarget(this.getTarget());
  15084. break;
  15085. case BABYLON.Camera.RIG_MODE_VR:
  15086. case BABYLON.Camera.RIG_MODE_WEBVR:
  15087. if (camLeft.rotationQuaternion) {
  15088. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15089. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15090. }
  15091. else {
  15092. camLeft.rotation.copyFrom(this.rotation);
  15093. camRight.rotation.copyFrom(this.rotation);
  15094. }
  15095. camLeft.position.copyFrom(this.position);
  15096. camRight.position.copyFrom(this.position);
  15097. break;
  15098. }
  15099. _super.prototype._updateRigCameras.call(this);
  15100. };
  15101. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  15102. if (!this._rigCamTransformMatrix) {
  15103. this._rigCamTransformMatrix = new BABYLON.Matrix();
  15104. }
  15105. var target = this.getTarget();
  15106. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  15107. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  15108. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  15109. };
  15110. TargetCamera.prototype.getClassName = function () {
  15111. return "TargetCamera";
  15112. };
  15113. return TargetCamera;
  15114. }(BABYLON.Camera));
  15115. __decorate([
  15116. BABYLON.serializeAsVector3()
  15117. ], TargetCamera.prototype, "rotation", void 0);
  15118. __decorate([
  15119. BABYLON.serialize()
  15120. ], TargetCamera.prototype, "speed", void 0);
  15121. __decorate([
  15122. BABYLON.serializeAsMeshReference("lockedTargetId")
  15123. ], TargetCamera.prototype, "lockedTarget", void 0);
  15124. BABYLON.TargetCamera = TargetCamera;
  15125. })(BABYLON || (BABYLON = {}));
  15126. //# sourceMappingURL=babylon.targetCamera.js.map
  15127. var BABYLON;
  15128. (function (BABYLON) {
  15129. var FreeCamera = (function (_super) {
  15130. __extends(FreeCamera, _super);
  15131. function FreeCamera(name, position, scene) {
  15132. var _this = _super.call(this, name, position, scene) || this;
  15133. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15134. _this.checkCollisions = false;
  15135. _this.applyGravity = false;
  15136. _this._collider = new BABYLON.Collider();
  15137. _this._needMoveForGravity = false;
  15138. _this._oldPosition = BABYLON.Vector3.Zero();
  15139. _this._diffPosition = BABYLON.Vector3.Zero();
  15140. _this._newPosition = BABYLON.Vector3.Zero();
  15141. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15142. if (collidedMesh === void 0) { collidedMesh = null; }
  15143. //TODO move this to the collision coordinator!
  15144. if (_this.getScene().workerCollisions)
  15145. newPosition.multiplyInPlace(_this._collider.radius);
  15146. var updatePosition = function (newPos) {
  15147. _this._newPosition.copyFrom(newPos);
  15148. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  15149. var oldPosition = _this.position.clone();
  15150. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  15151. _this.position.addInPlace(_this._diffPosition);
  15152. if (_this.onCollide && collidedMesh) {
  15153. _this.onCollide(collidedMesh);
  15154. }
  15155. }
  15156. };
  15157. updatePosition(newPosition);
  15158. };
  15159. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  15160. _this.inputs.addKeyboard().addMouse();
  15161. return _this;
  15162. }
  15163. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  15164. //-- begin properties for backward compatibility for inputs
  15165. get: function () {
  15166. var mouse = this.inputs.attached["mouse"];
  15167. if (mouse)
  15168. return mouse.angularSensibility;
  15169. },
  15170. set: function (value) {
  15171. var mouse = this.inputs.attached["mouse"];
  15172. if (mouse)
  15173. mouse.angularSensibility = value;
  15174. },
  15175. enumerable: true,
  15176. configurable: true
  15177. });
  15178. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  15179. get: function () {
  15180. var keyboard = this.inputs.attached["keyboard"];
  15181. if (keyboard)
  15182. return keyboard.keysUp;
  15183. },
  15184. set: function (value) {
  15185. var keyboard = this.inputs.attached["keyboard"];
  15186. if (keyboard)
  15187. keyboard.keysUp = value;
  15188. },
  15189. enumerable: true,
  15190. configurable: true
  15191. });
  15192. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  15193. get: function () {
  15194. var keyboard = this.inputs.attached["keyboard"];
  15195. if (keyboard)
  15196. return keyboard.keysDown;
  15197. },
  15198. set: function (value) {
  15199. var keyboard = this.inputs.attached["keyboard"];
  15200. if (keyboard)
  15201. keyboard.keysDown = value;
  15202. },
  15203. enumerable: true,
  15204. configurable: true
  15205. });
  15206. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  15207. get: function () {
  15208. var keyboard = this.inputs.attached["keyboard"];
  15209. if (keyboard)
  15210. return keyboard.keysLeft;
  15211. },
  15212. set: function (value) {
  15213. var keyboard = this.inputs.attached["keyboard"];
  15214. if (keyboard)
  15215. keyboard.keysLeft = value;
  15216. },
  15217. enumerable: true,
  15218. configurable: true
  15219. });
  15220. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  15221. get: function () {
  15222. var keyboard = this.inputs.attached["keyboard"];
  15223. if (keyboard)
  15224. return keyboard.keysRight;
  15225. },
  15226. set: function (value) {
  15227. var keyboard = this.inputs.attached["keyboard"];
  15228. if (keyboard)
  15229. keyboard.keysRight = value;
  15230. },
  15231. enumerable: true,
  15232. configurable: true
  15233. });
  15234. // Controls
  15235. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  15236. this.inputs.attachElement(element, noPreventDefault);
  15237. };
  15238. FreeCamera.prototype.detachControl = function (element) {
  15239. this.inputs.detachElement(element);
  15240. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  15241. this.cameraRotation = new BABYLON.Vector2(0, 0);
  15242. };
  15243. FreeCamera.prototype._collideWithWorld = function (velocity) {
  15244. var globalPosition;
  15245. if (this.parent) {
  15246. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  15247. }
  15248. else {
  15249. globalPosition = this.position;
  15250. }
  15251. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  15252. this._collider.radius = this.ellipsoid;
  15253. //no need for clone, as long as gravity is not on.
  15254. var actualVelocity = velocity;
  15255. //add gravity to the velocity to prevent the dual-collision checking
  15256. if (this.applyGravity) {
  15257. //this prevents mending with cameraDirection, a global variable of the free camera class.
  15258. actualVelocity = velocity.add(this.getScene().gravity);
  15259. }
  15260. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15261. };
  15262. FreeCamera.prototype._checkInputs = function () {
  15263. if (!this._localDirection) {
  15264. this._localDirection = BABYLON.Vector3.Zero();
  15265. this._transformedDirection = BABYLON.Vector3.Zero();
  15266. }
  15267. this.inputs.checkInputs();
  15268. _super.prototype._checkInputs.call(this);
  15269. };
  15270. FreeCamera.prototype._decideIfNeedsToMove = function () {
  15271. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  15272. };
  15273. FreeCamera.prototype._updatePosition = function () {
  15274. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  15275. this._collideWithWorld(this.cameraDirection);
  15276. }
  15277. else {
  15278. this.position.addInPlace(this.cameraDirection);
  15279. }
  15280. };
  15281. FreeCamera.prototype.dispose = function () {
  15282. this.inputs.clear();
  15283. _super.prototype.dispose.call(this);
  15284. };
  15285. FreeCamera.prototype.getClassName = function () {
  15286. return "FreeCamera";
  15287. };
  15288. return FreeCamera;
  15289. }(BABYLON.TargetCamera));
  15290. __decorate([
  15291. BABYLON.serializeAsVector3()
  15292. ], FreeCamera.prototype, "ellipsoid", void 0);
  15293. __decorate([
  15294. BABYLON.serialize()
  15295. ], FreeCamera.prototype, "checkCollisions", void 0);
  15296. __decorate([
  15297. BABYLON.serialize()
  15298. ], FreeCamera.prototype, "applyGravity", void 0);
  15299. BABYLON.FreeCamera = FreeCamera;
  15300. })(BABYLON || (BABYLON = {}));
  15301. //# sourceMappingURL=babylon.freeCamera.js.map
  15302. var BABYLON;
  15303. (function (BABYLON) {
  15304. var FreeCameraInputsManager = (function (_super) {
  15305. __extends(FreeCameraInputsManager, _super);
  15306. function FreeCameraInputsManager(camera) {
  15307. return _super.call(this, camera) || this;
  15308. }
  15309. FreeCameraInputsManager.prototype.addKeyboard = function () {
  15310. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  15311. return this;
  15312. };
  15313. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  15314. if (touchEnabled === void 0) { touchEnabled = true; }
  15315. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  15316. return this;
  15317. };
  15318. FreeCameraInputsManager.prototype.addGamepad = function () {
  15319. this.add(new BABYLON.FreeCameraGamepadInput());
  15320. return this;
  15321. };
  15322. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  15323. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  15324. return this;
  15325. };
  15326. FreeCameraInputsManager.prototype.addTouch = function () {
  15327. this.add(new BABYLON.FreeCameraTouchInput());
  15328. return this;
  15329. };
  15330. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  15331. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  15332. return this;
  15333. };
  15334. return FreeCameraInputsManager;
  15335. }(BABYLON.CameraInputsManager));
  15336. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  15337. })(BABYLON || (BABYLON = {}));
  15338. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  15339. var BABYLON;
  15340. (function (BABYLON) {
  15341. var FollowCamera = (function (_super) {
  15342. __extends(FollowCamera, _super);
  15343. function FollowCamera(name, position, scene, lockedTarget) {
  15344. var _this = _super.call(this, name, position, scene) || this;
  15345. _this.radius = 12;
  15346. _this.rotationOffset = 0;
  15347. _this.heightOffset = 4;
  15348. _this.cameraAcceleration = 0.05;
  15349. _this.maxCameraSpeed = 20;
  15350. _this.lockedTarget = lockedTarget;
  15351. return _this;
  15352. }
  15353. FollowCamera.prototype.getRadians = function (degrees) {
  15354. return degrees * Math.PI / 180;
  15355. };
  15356. FollowCamera.prototype.follow = function (cameraTarget) {
  15357. if (!cameraTarget)
  15358. return;
  15359. var yRotation;
  15360. if (cameraTarget.rotationQuaternion) {
  15361. var rotMatrix = new BABYLON.Matrix();
  15362. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  15363. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  15364. }
  15365. else {
  15366. yRotation = cameraTarget.rotation.y;
  15367. }
  15368. var radians = this.getRadians(this.rotationOffset) + yRotation;
  15369. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  15370. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  15371. var dx = targetX - this.position.x;
  15372. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  15373. var dz = (targetZ) - this.position.z;
  15374. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  15375. var vy = dy * this.cameraAcceleration;
  15376. var vz = dz * this.cameraAcceleration * 2;
  15377. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  15378. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15379. }
  15380. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  15381. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15382. }
  15383. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  15384. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15385. }
  15386. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  15387. this.setTarget(cameraTarget.position);
  15388. };
  15389. FollowCamera.prototype._checkInputs = function () {
  15390. _super.prototype._checkInputs.call(this);
  15391. this.follow(this.lockedTarget);
  15392. };
  15393. FollowCamera.prototype.getClassName = function () {
  15394. return "FollowCamera";
  15395. };
  15396. return FollowCamera;
  15397. }(BABYLON.TargetCamera));
  15398. __decorate([
  15399. BABYLON.serialize()
  15400. ], FollowCamera.prototype, "radius", void 0);
  15401. __decorate([
  15402. BABYLON.serialize()
  15403. ], FollowCamera.prototype, "rotationOffset", void 0);
  15404. __decorate([
  15405. BABYLON.serialize()
  15406. ], FollowCamera.prototype, "heightOffset", void 0);
  15407. __decorate([
  15408. BABYLON.serialize()
  15409. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  15410. __decorate([
  15411. BABYLON.serialize()
  15412. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  15413. __decorate([
  15414. BABYLON.serializeAsMeshReference("lockedTargetId")
  15415. ], FollowCamera.prototype, "lockedTarget", void 0);
  15416. BABYLON.FollowCamera = FollowCamera;
  15417. var ArcFollowCamera = (function (_super) {
  15418. __extends(ArcFollowCamera, _super);
  15419. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  15420. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  15421. _this.alpha = alpha;
  15422. _this.beta = beta;
  15423. _this.radius = radius;
  15424. _this.target = target;
  15425. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  15426. _this.follow();
  15427. return _this;
  15428. }
  15429. ArcFollowCamera.prototype.follow = function () {
  15430. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  15431. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  15432. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  15433. this.position = this.target.position.add(this._cartesianCoordinates);
  15434. this.setTarget(this.target.position);
  15435. };
  15436. ArcFollowCamera.prototype._checkInputs = function () {
  15437. _super.prototype._checkInputs.call(this);
  15438. this.follow();
  15439. };
  15440. ArcFollowCamera.prototype.getClassName = function () {
  15441. return "ArcFollowCamera";
  15442. };
  15443. return ArcFollowCamera;
  15444. }(BABYLON.TargetCamera));
  15445. BABYLON.ArcFollowCamera = ArcFollowCamera;
  15446. })(BABYLON || (BABYLON = {}));
  15447. //# sourceMappingURL=babylon.followCamera.js.map
  15448. var BABYLON;
  15449. (function (BABYLON) {
  15450. // We're mainly based on the logic defined into the FreeCamera code
  15451. var TouchCamera = (function (_super) {
  15452. __extends(TouchCamera, _super);
  15453. //-- end properties for backward compatibility for inputs
  15454. function TouchCamera(name, position, scene) {
  15455. var _this = _super.call(this, name, position, scene) || this;
  15456. _this.inputs.addTouch();
  15457. _this._setupInputs();
  15458. return _this;
  15459. }
  15460. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  15461. //-- Begin properties for backward compatibility for inputs
  15462. get: function () {
  15463. var touch = this.inputs.attached["touch"];
  15464. if (touch)
  15465. return touch.touchAngularSensibility;
  15466. },
  15467. set: function (value) {
  15468. var touch = this.inputs.attached["touch"];
  15469. if (touch)
  15470. touch.touchAngularSensibility = value;
  15471. },
  15472. enumerable: true,
  15473. configurable: true
  15474. });
  15475. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  15476. get: function () {
  15477. var touch = this.inputs.attached["touch"];
  15478. if (touch)
  15479. return touch.touchMoveSensibility;
  15480. },
  15481. set: function (value) {
  15482. var touch = this.inputs.attached["touch"];
  15483. if (touch)
  15484. touch.touchMoveSensibility = value;
  15485. },
  15486. enumerable: true,
  15487. configurable: true
  15488. });
  15489. TouchCamera.prototype.getClassName = function () {
  15490. return "TouchCamera";
  15491. };
  15492. TouchCamera.prototype._setupInputs = function () {
  15493. var mouse = this.inputs.attached["mouse"];
  15494. if (mouse) {
  15495. mouse.touchEnabled = false;
  15496. }
  15497. };
  15498. return TouchCamera;
  15499. }(BABYLON.FreeCamera));
  15500. BABYLON.TouchCamera = TouchCamera;
  15501. })(BABYLON || (BABYLON = {}));
  15502. //# sourceMappingURL=babylon.touchCamera.js.map
  15503. var BABYLON;
  15504. (function (BABYLON) {
  15505. var ArcRotateCamera = (function (_super) {
  15506. __extends(ArcRotateCamera, _super);
  15507. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  15508. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  15509. _this.inertialAlphaOffset = 0;
  15510. _this.inertialBetaOffset = 0;
  15511. _this.inertialRadiusOffset = 0;
  15512. _this.lowerAlphaLimit = null;
  15513. _this.upperAlphaLimit = null;
  15514. _this.lowerBetaLimit = 0.01;
  15515. _this.upperBetaLimit = Math.PI;
  15516. _this.lowerRadiusLimit = null;
  15517. _this.upperRadiusLimit = null;
  15518. _this.inertialPanningX = 0;
  15519. _this.inertialPanningY = 0;
  15520. //-- end properties for backward compatibility for inputs
  15521. _this.zoomOnFactor = 1;
  15522. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  15523. _this.allowUpsideDown = true;
  15524. _this._viewMatrix = new BABYLON.Matrix();
  15525. // Panning
  15526. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  15527. _this.checkCollisions = false;
  15528. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15529. _this._collider = new BABYLON.Collider();
  15530. _this._previousPosition = BABYLON.Vector3.Zero();
  15531. _this._collisionVelocity = BABYLON.Vector3.Zero();
  15532. _this._newPosition = BABYLON.Vector3.Zero();
  15533. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15534. if (collidedMesh === void 0) { collidedMesh = null; }
  15535. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  15536. newPosition.multiplyInPlace(_this._collider.radius);
  15537. }
  15538. if (!collidedMesh) {
  15539. _this._previousPosition.copyFrom(_this.position);
  15540. }
  15541. else {
  15542. _this.setPosition(newPosition);
  15543. if (_this.onCollide) {
  15544. _this.onCollide(collidedMesh);
  15545. }
  15546. }
  15547. // Recompute because of constraints
  15548. var cosa = Math.cos(_this.alpha);
  15549. var sina = Math.sin(_this.alpha);
  15550. var cosb = Math.cos(_this.beta);
  15551. var sinb = Math.sin(_this.beta);
  15552. if (sinb === 0) {
  15553. sinb = 0.0001;
  15554. }
  15555. var target = _this._getTargetPosition();
  15556. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  15557. _this.position.copyFrom(_this._newPosition);
  15558. var up = _this.upVector;
  15559. if (_this.allowUpsideDown && _this.beta < 0) {
  15560. up = up.clone();
  15561. up = up.negate();
  15562. }
  15563. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  15564. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  15565. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  15566. _this._collisionTriggered = false;
  15567. };
  15568. if (!target) {
  15569. _this.target = BABYLON.Vector3.Zero();
  15570. }
  15571. else {
  15572. _this.target = target;
  15573. }
  15574. _this.alpha = alpha;
  15575. _this.beta = beta;
  15576. _this.radius = radius;
  15577. _this.getViewMatrix();
  15578. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  15579. _this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  15580. return _this;
  15581. }
  15582. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  15583. //-- begin properties for backward compatibility for inputs
  15584. get: function () {
  15585. var pointers = this.inputs.attached["pointers"];
  15586. if (pointers)
  15587. return pointers.angularSensibilityX;
  15588. },
  15589. set: function (value) {
  15590. var pointers = this.inputs.attached["pointers"];
  15591. if (pointers) {
  15592. pointers.angularSensibilityX = value;
  15593. }
  15594. },
  15595. enumerable: true,
  15596. configurable: true
  15597. });
  15598. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  15599. get: function () {
  15600. var pointers = this.inputs.attached["pointers"];
  15601. if (pointers)
  15602. return pointers.angularSensibilityY;
  15603. },
  15604. set: function (value) {
  15605. var pointers = this.inputs.attached["pointers"];
  15606. if (pointers) {
  15607. pointers.angularSensibilityY = value;
  15608. }
  15609. },
  15610. enumerable: true,
  15611. configurable: true
  15612. });
  15613. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  15614. get: function () {
  15615. var pointers = this.inputs.attached["pointers"];
  15616. if (pointers)
  15617. return pointers.pinchPrecision;
  15618. },
  15619. set: function (value) {
  15620. var pointers = this.inputs.attached["pointers"];
  15621. if (pointers) {
  15622. pointers.pinchPrecision = value;
  15623. }
  15624. },
  15625. enumerable: true,
  15626. configurable: true
  15627. });
  15628. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  15629. get: function () {
  15630. var pointers = this.inputs.attached["pointers"];
  15631. if (pointers)
  15632. return pointers.panningSensibility;
  15633. },
  15634. set: function (value) {
  15635. var pointers = this.inputs.attached["pointers"];
  15636. if (pointers) {
  15637. pointers.panningSensibility = value;
  15638. }
  15639. },
  15640. enumerable: true,
  15641. configurable: true
  15642. });
  15643. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  15644. get: function () {
  15645. var keyboard = this.inputs.attached["keyboard"];
  15646. if (keyboard)
  15647. return keyboard.keysUp;
  15648. },
  15649. set: function (value) {
  15650. var keyboard = this.inputs.attached["keyboard"];
  15651. if (keyboard)
  15652. keyboard.keysUp = value;
  15653. },
  15654. enumerable: true,
  15655. configurable: true
  15656. });
  15657. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  15658. get: function () {
  15659. var keyboard = this.inputs.attached["keyboard"];
  15660. if (keyboard)
  15661. return keyboard.keysDown;
  15662. },
  15663. set: function (value) {
  15664. var keyboard = this.inputs.attached["keyboard"];
  15665. if (keyboard)
  15666. keyboard.keysDown = value;
  15667. },
  15668. enumerable: true,
  15669. configurable: true
  15670. });
  15671. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  15672. get: function () {
  15673. var keyboard = this.inputs.attached["keyboard"];
  15674. if (keyboard)
  15675. return keyboard.keysLeft;
  15676. },
  15677. set: function (value) {
  15678. var keyboard = this.inputs.attached["keyboard"];
  15679. if (keyboard)
  15680. keyboard.keysLeft = value;
  15681. },
  15682. enumerable: true,
  15683. configurable: true
  15684. });
  15685. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  15686. get: function () {
  15687. var keyboard = this.inputs.attached["keyboard"];
  15688. if (keyboard)
  15689. return keyboard.keysRight;
  15690. },
  15691. set: function (value) {
  15692. var keyboard = this.inputs.attached["keyboard"];
  15693. if (keyboard)
  15694. keyboard.keysRight = value;
  15695. },
  15696. enumerable: true,
  15697. configurable: true
  15698. });
  15699. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  15700. get: function () {
  15701. var mousewheel = this.inputs.attached["mousewheel"];
  15702. if (mousewheel)
  15703. return mousewheel.wheelPrecision;
  15704. },
  15705. set: function (value) {
  15706. var mousewheel = this.inputs.attached["mousewheel"];
  15707. if (mousewheel)
  15708. mousewheel.wheelPrecision = value;
  15709. },
  15710. enumerable: true,
  15711. configurable: true
  15712. });
  15713. // Cache
  15714. ArcRotateCamera.prototype._initCache = function () {
  15715. _super.prototype._initCache.call(this);
  15716. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15717. this._cache.alpha = undefined;
  15718. this._cache.beta = undefined;
  15719. this._cache.radius = undefined;
  15720. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  15721. };
  15722. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  15723. if (!ignoreParentClass) {
  15724. _super.prototype._updateCache.call(this);
  15725. }
  15726. this._cache.target.copyFrom(this._getTargetPosition());
  15727. this._cache.alpha = this.alpha;
  15728. this._cache.beta = this.beta;
  15729. this._cache.radius = this.radius;
  15730. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  15731. };
  15732. ArcRotateCamera.prototype._getTargetPosition = function () {
  15733. if (this.target.getAbsolutePosition) {
  15734. var pos = this.target.getAbsolutePosition();
  15735. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  15736. }
  15737. return this.target;
  15738. };
  15739. // Synchronized
  15740. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  15741. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  15742. return false;
  15743. return this._cache.target.equals(this.target)
  15744. && this._cache.alpha === this.alpha
  15745. && this._cache.beta === this.beta
  15746. && this._cache.radius === this.radius
  15747. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  15748. };
  15749. // Methods
  15750. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  15751. var _this = this;
  15752. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  15753. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  15754. this._useCtrlForPanning = useCtrlForPanning;
  15755. this._panningMouseButton = panningMouseButton;
  15756. this.inputs.attachElement(element, noPreventDefault);
  15757. this._reset = function () {
  15758. _this.inertialAlphaOffset = 0;
  15759. _this.inertialBetaOffset = 0;
  15760. _this.inertialRadiusOffset = 0;
  15761. };
  15762. };
  15763. ArcRotateCamera.prototype.detachControl = function (element) {
  15764. this.inputs.detachElement(element);
  15765. if (this._reset) {
  15766. this._reset();
  15767. }
  15768. };
  15769. ArcRotateCamera.prototype._checkInputs = function () {
  15770. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  15771. if (this._collisionTriggered) {
  15772. return;
  15773. }
  15774. this.inputs.checkInputs();
  15775. // Inertia
  15776. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  15777. if (this.getScene().useRightHandedSystem) {
  15778. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15779. }
  15780. else {
  15781. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15782. }
  15783. this.beta += this.inertialBetaOffset;
  15784. this.radius -= this.inertialRadiusOffset;
  15785. this.inertialAlphaOffset *= this.inertia;
  15786. this.inertialBetaOffset *= this.inertia;
  15787. this.inertialRadiusOffset *= this.inertia;
  15788. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  15789. this.inertialAlphaOffset = 0;
  15790. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  15791. this.inertialBetaOffset = 0;
  15792. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  15793. this.inertialRadiusOffset = 0;
  15794. }
  15795. // Panning inertia
  15796. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  15797. if (!this._localDirection) {
  15798. this._localDirection = BABYLON.Vector3.Zero();
  15799. this._transformedDirection = BABYLON.Vector3.Zero();
  15800. }
  15801. this.inertialPanningX *= this.inertia;
  15802. this.inertialPanningY *= this.inertia;
  15803. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  15804. this.inertialPanningX = 0;
  15805. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  15806. this.inertialPanningY = 0;
  15807. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  15808. this._localDirection.multiplyInPlace(this.panningAxis);
  15809. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  15810. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  15811. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  15812. if (!this.panningAxis.y) {
  15813. this._transformedDirection.y = 0;
  15814. }
  15815. if (!this.target.getAbsolutePosition) {
  15816. this.target.addInPlace(this._transformedDirection);
  15817. }
  15818. }
  15819. // Limits
  15820. this._checkLimits();
  15821. _super.prototype._checkInputs.call(this);
  15822. };
  15823. ArcRotateCamera.prototype._checkLimits = function () {
  15824. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  15825. if (this.allowUpsideDown && this.beta > Math.PI) {
  15826. this.beta = this.beta - (2 * Math.PI);
  15827. }
  15828. }
  15829. else {
  15830. if (this.beta < this.lowerBetaLimit) {
  15831. this.beta = this.lowerBetaLimit;
  15832. }
  15833. }
  15834. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  15835. if (this.allowUpsideDown && this.beta < -Math.PI) {
  15836. this.beta = this.beta + (2 * Math.PI);
  15837. }
  15838. }
  15839. else {
  15840. if (this.beta > this.upperBetaLimit) {
  15841. this.beta = this.upperBetaLimit;
  15842. }
  15843. }
  15844. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  15845. this.alpha = this.lowerAlphaLimit;
  15846. }
  15847. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  15848. this.alpha = this.upperAlphaLimit;
  15849. }
  15850. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  15851. this.radius = this.lowerRadiusLimit;
  15852. }
  15853. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  15854. this.radius = this.upperRadiusLimit;
  15855. }
  15856. };
  15857. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  15858. var radiusv3 = this.position.subtract(this._getTargetPosition());
  15859. this.radius = radiusv3.length();
  15860. // Alpha
  15861. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  15862. if (radiusv3.z < 0) {
  15863. this.alpha = 2 * Math.PI - this.alpha;
  15864. }
  15865. // Beta
  15866. this.beta = Math.acos(radiusv3.y / this.radius);
  15867. this._checkLimits();
  15868. };
  15869. ArcRotateCamera.prototype.setPosition = function (position) {
  15870. if (this.position.equals(position)) {
  15871. return;
  15872. }
  15873. this.position.copyFrom(position);
  15874. this.rebuildAnglesAndRadius();
  15875. };
  15876. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter) {
  15877. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  15878. if (this._getTargetPosition().equals(target)) {
  15879. return;
  15880. }
  15881. if (toBoundingCenter && target.getBoundingInfo) {
  15882. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  15883. }
  15884. else {
  15885. this._targetBoundingCenter = null;
  15886. }
  15887. this.target = target;
  15888. this.rebuildAnglesAndRadius();
  15889. };
  15890. ArcRotateCamera.prototype._getViewMatrix = function () {
  15891. // Compute
  15892. var cosa = Math.cos(this.alpha);
  15893. var sina = Math.sin(this.alpha);
  15894. var cosb = Math.cos(this.beta);
  15895. var sinb = Math.sin(this.beta);
  15896. if (sinb === 0) {
  15897. sinb = 0.0001;
  15898. }
  15899. var target = this._getTargetPosition();
  15900. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  15901. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  15902. this._collider.radius = this.collisionRadius;
  15903. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  15904. this._collisionTriggered = true;
  15905. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15906. }
  15907. else {
  15908. this.position.copyFrom(this._newPosition);
  15909. var up = this.upVector;
  15910. if (this.allowUpsideDown && this.beta < 0) {
  15911. up = up.clone();
  15912. up = up.negate();
  15913. }
  15914. if (this.getScene().useRightHandedSystem) {
  15915. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  15916. }
  15917. else {
  15918. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  15919. }
  15920. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  15921. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  15922. }
  15923. this._currentTarget = target;
  15924. return this._viewMatrix;
  15925. };
  15926. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  15927. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15928. meshes = meshes || this.getScene().meshes;
  15929. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  15930. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  15931. this.radius = distance * this.zoomOnFactor;
  15932. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  15933. };
  15934. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  15935. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15936. var meshesOrMinMaxVector;
  15937. var distance;
  15938. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  15939. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  15940. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  15941. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  15942. }
  15943. else {
  15944. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  15945. distance = meshesOrMinMaxVectorAndDistance.distance;
  15946. }
  15947. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  15948. if (!doNotUpdateMaxZ) {
  15949. this.maxZ = distance * 2;
  15950. }
  15951. };
  15952. /**
  15953. * @override
  15954. * Override Camera.createRigCamera
  15955. */
  15956. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15957. var alphaShift;
  15958. switch (this.cameraRigMode) {
  15959. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15960. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15961. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15962. case BABYLON.Camera.RIG_MODE_VR:
  15963. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  15964. break;
  15965. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15966. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  15967. break;
  15968. }
  15969. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  15970. rigCam._cameraRigParams = {};
  15971. return rigCam;
  15972. };
  15973. /**
  15974. * @override
  15975. * Override Camera._updateRigCameras
  15976. */
  15977. ArcRotateCamera.prototype._updateRigCameras = function () {
  15978. var camLeft = this._rigCameras[0];
  15979. var camRight = this._rigCameras[1];
  15980. camLeft.beta = camRight.beta = this.beta;
  15981. camLeft.radius = camRight.radius = this.radius;
  15982. switch (this.cameraRigMode) {
  15983. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15984. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15985. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15986. case BABYLON.Camera.RIG_MODE_VR:
  15987. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15988. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15989. break;
  15990. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15991. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15992. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15993. break;
  15994. }
  15995. _super.prototype._updateRigCameras.call(this);
  15996. };
  15997. ArcRotateCamera.prototype.dispose = function () {
  15998. this.inputs.clear();
  15999. _super.prototype.dispose.call(this);
  16000. };
  16001. ArcRotateCamera.prototype.getClassName = function () {
  16002. return "ArcRotateCamera";
  16003. };
  16004. return ArcRotateCamera;
  16005. }(BABYLON.TargetCamera));
  16006. __decorate([
  16007. BABYLON.serialize()
  16008. ], ArcRotateCamera.prototype, "alpha", void 0);
  16009. __decorate([
  16010. BABYLON.serialize()
  16011. ], ArcRotateCamera.prototype, "beta", void 0);
  16012. __decorate([
  16013. BABYLON.serialize()
  16014. ], ArcRotateCamera.prototype, "radius", void 0);
  16015. __decorate([
  16016. BABYLON.serializeAsVector3()
  16017. ], ArcRotateCamera.prototype, "target", void 0);
  16018. __decorate([
  16019. BABYLON.serialize()
  16020. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  16021. __decorate([
  16022. BABYLON.serialize()
  16023. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  16024. __decorate([
  16025. BABYLON.serialize()
  16026. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  16027. __decorate([
  16028. BABYLON.serialize()
  16029. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  16030. __decorate([
  16031. BABYLON.serialize()
  16032. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  16033. __decorate([
  16034. BABYLON.serialize()
  16035. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  16036. __decorate([
  16037. BABYLON.serialize()
  16038. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  16039. __decorate([
  16040. BABYLON.serialize()
  16041. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  16042. __decorate([
  16043. BABYLON.serialize()
  16044. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  16045. __decorate([
  16046. BABYLON.serialize()
  16047. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  16048. __decorate([
  16049. BABYLON.serialize()
  16050. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  16051. __decorate([
  16052. BABYLON.serialize()
  16053. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  16054. __decorate([
  16055. BABYLON.serialize()
  16056. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  16057. BABYLON.ArcRotateCamera = ArcRotateCamera;
  16058. })(BABYLON || (BABYLON = {}));
  16059. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  16060. var BABYLON;
  16061. (function (BABYLON) {
  16062. var ArcRotateCameraInputsManager = (function (_super) {
  16063. __extends(ArcRotateCameraInputsManager, _super);
  16064. function ArcRotateCameraInputsManager(camera) {
  16065. return _super.call(this, camera) || this;
  16066. }
  16067. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  16068. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  16069. return this;
  16070. };
  16071. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  16072. this.add(new BABYLON.ArcRotateCameraPointersInput());
  16073. return this;
  16074. };
  16075. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  16076. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  16077. return this;
  16078. };
  16079. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  16080. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  16081. return this;
  16082. };
  16083. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  16084. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  16085. return this;
  16086. };
  16087. return ArcRotateCameraInputsManager;
  16088. }(BABYLON.CameraInputsManager));
  16089. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  16090. })(BABYLON || (BABYLON = {}));
  16091. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  16092. var BABYLON;
  16093. (function (BABYLON) {
  16094. var RenderingManager = (function () {
  16095. function RenderingManager(scene) {
  16096. this._renderingGroups = new Array();
  16097. this._autoClearDepthStencil = {};
  16098. this._customOpaqueSortCompareFn = {};
  16099. this._customAlphaTestSortCompareFn = {};
  16100. this._customTransparentSortCompareFn = {};
  16101. this._renderinGroupInfo = null;
  16102. this._scene = scene;
  16103. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16104. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16105. }
  16106. }
  16107. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16108. if (depth === void 0) { depth = true; }
  16109. if (stencil === void 0) { stencil = true; }
  16110. if (this._depthStencilBufferAlreadyCleaned) {
  16111. return;
  16112. }
  16113. this._scene.getEngine().clear(null, false, depth, stencil);
  16114. this._depthStencilBufferAlreadyCleaned = true;
  16115. };
  16116. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16117. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16118. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16119. var info = null;
  16120. if (observable) {
  16121. if (!this._renderinGroupInfo) {
  16122. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16123. }
  16124. info = this._renderinGroupInfo;
  16125. info.scene = this._scene;
  16126. info.camera = this._scene.activeCamera;
  16127. }
  16128. // Dispatch sprites
  16129. if (renderSprites) {
  16130. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  16131. var manager = this._scene.spriteManagers[index];
  16132. this.dispatchSprites(manager);
  16133. }
  16134. }
  16135. // Render
  16136. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16137. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16138. var renderingGroup = this._renderingGroups[index];
  16139. if (!renderingGroup && !observable)
  16140. continue;
  16141. this._currentIndex = index;
  16142. var renderingGroupMask = 0;
  16143. // Fire PRECLEAR stage
  16144. if (observable) {
  16145. renderingGroupMask = Math.pow(2, index);
  16146. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16147. info.renderingGroupId = index;
  16148. observable.notifyObservers(info, renderingGroupMask);
  16149. }
  16150. // Clear depth/stencil if needed
  16151. var autoClear = this._autoClearDepthStencil[index];
  16152. if (autoClear && autoClear.autoClear) {
  16153. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16154. }
  16155. if (observable) {
  16156. // Fire PREOPAQUE stage
  16157. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16158. observable.notifyObservers(info, renderingGroupMask);
  16159. // Fire PRETRANSPARENT stage
  16160. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16161. observable.notifyObservers(info, renderingGroupMask);
  16162. }
  16163. if (renderingGroup)
  16164. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16165. // Fire POSTTRANSPARENT stage
  16166. if (observable) {
  16167. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16168. observable.notifyObservers(info, renderingGroupMask);
  16169. }
  16170. }
  16171. };
  16172. RenderingManager.prototype.reset = function () {
  16173. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16174. var renderingGroup = this._renderingGroups[index];
  16175. if (renderingGroup) {
  16176. renderingGroup.prepare();
  16177. }
  16178. }
  16179. };
  16180. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16181. if (!this._renderingGroups[renderingGroupId]) {
  16182. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16183. }
  16184. };
  16185. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16186. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16187. this._prepareRenderingGroup(renderingGroupId);
  16188. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16189. };
  16190. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16191. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16192. this._prepareRenderingGroup(renderingGroupId);
  16193. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16194. };
  16195. RenderingManager.prototype.dispatch = function (subMesh) {
  16196. var mesh = subMesh.getMesh();
  16197. var renderingGroupId = mesh.renderingGroupId || 0;
  16198. this._prepareRenderingGroup(renderingGroupId);
  16199. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16200. };
  16201. /**
  16202. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16203. * This allowed control for front to back rendering or reversly depending of the special needs.
  16204. *
  16205. * @param renderingGroupId The rendering group id corresponding to its index
  16206. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16207. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16208. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16209. */
  16210. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16211. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16212. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16213. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16214. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16215. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16216. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16217. if (this._renderingGroups[renderingGroupId]) {
  16218. var group = this._renderingGroups[renderingGroupId];
  16219. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16220. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16221. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16222. }
  16223. };
  16224. /**
  16225. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16226. *
  16227. * @param renderingGroupId The rendering group id corresponding to its index
  16228. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16229. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16230. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16231. */
  16232. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16233. if (depth === void 0) { depth = true; }
  16234. if (stencil === void 0) { stencil = true; }
  16235. this._autoClearDepthStencil[renderingGroupId] = {
  16236. autoClear: autoClearDepthStencil,
  16237. depth: depth,
  16238. stencil: stencil
  16239. };
  16240. };
  16241. return RenderingManager;
  16242. }());
  16243. /**
  16244. * The max id used for rendering groups (not included)
  16245. */
  16246. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16247. /**
  16248. * The min id used for rendering groups (included)
  16249. */
  16250. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16251. BABYLON.RenderingManager = RenderingManager;
  16252. })(BABYLON || (BABYLON = {}));
  16253. //# sourceMappingURL=babylon.renderingManager.js.map
  16254. var BABYLON;
  16255. (function (BABYLON) {
  16256. var RenderingGroup = (function () {
  16257. /**
  16258. * Creates a new rendering group.
  16259. * @param index The rendering group index
  16260. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16261. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16262. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16263. */
  16264. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16265. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16266. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16267. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16268. this.index = index;
  16269. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16270. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16271. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16272. this._particleSystems = new BABYLON.SmartArray(256);
  16273. this._spriteManagers = new BABYLON.SmartArray(256);
  16274. this._scene = scene;
  16275. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16276. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16277. this.transparentSortCompareFn = transparentSortCompareFn;
  16278. }
  16279. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16280. /**
  16281. * Set the opaque sort comparison function.
  16282. * If null the sub meshes will be render in the order they were created
  16283. */
  16284. set: function (value) {
  16285. this._opaqueSortCompareFn = value;
  16286. if (value) {
  16287. this._renderOpaque = this.renderOpaqueSorted;
  16288. }
  16289. else {
  16290. this._renderOpaque = RenderingGroup.renderUnsorted;
  16291. }
  16292. },
  16293. enumerable: true,
  16294. configurable: true
  16295. });
  16296. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16297. /**
  16298. * Set the alpha test sort comparison function.
  16299. * If null the sub meshes will be render in the order they were created
  16300. */
  16301. set: function (value) {
  16302. this._alphaTestSortCompareFn = value;
  16303. if (value) {
  16304. this._renderAlphaTest = this.renderAlphaTestSorted;
  16305. }
  16306. else {
  16307. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16308. }
  16309. },
  16310. enumerable: true,
  16311. configurable: true
  16312. });
  16313. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16314. /**
  16315. * Set the transparent sort comparison function.
  16316. * If null the sub meshes will be render in the order they were created
  16317. */
  16318. set: function (value) {
  16319. if (value) {
  16320. this._transparentSortCompareFn = value;
  16321. }
  16322. else {
  16323. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16324. }
  16325. this._renderTransparent = this.renderTransparentSorted;
  16326. },
  16327. enumerable: true,
  16328. configurable: true
  16329. });
  16330. /**
  16331. * Render all the sub meshes contained in the group.
  16332. * @param customRenderFunction Used to override the default render behaviour of the group.
  16333. * @returns true if rendered some submeshes.
  16334. */
  16335. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16336. if (customRenderFunction) {
  16337. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  16338. return;
  16339. }
  16340. var engine = this._scene.getEngine();
  16341. // Opaque
  16342. if (this._opaqueSubMeshes.length !== 0) {
  16343. this._renderOpaque(this._opaqueSubMeshes);
  16344. }
  16345. // Alpha test
  16346. if (this._alphaTestSubMeshes.length !== 0) {
  16347. engine.setAlphaTesting(true);
  16348. this._renderAlphaTest(this._alphaTestSubMeshes);
  16349. engine.setAlphaTesting(false);
  16350. }
  16351. // Sprites
  16352. if (renderSprites) {
  16353. this._renderSprites();
  16354. }
  16355. // Particles
  16356. if (renderParticles) {
  16357. this._renderParticles(activeMeshes);
  16358. }
  16359. if (this.onBeforeTransparentRendering) {
  16360. this.onBeforeTransparentRendering();
  16361. }
  16362. // Transparent
  16363. if (this._transparentSubMeshes.length !== 0) {
  16364. this._renderTransparent(this._transparentSubMeshes);
  16365. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16366. }
  16367. };
  16368. /**
  16369. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16370. * @param subMeshes The submeshes to render
  16371. */
  16372. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16373. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16374. };
  16375. /**
  16376. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16377. * @param subMeshes The submeshes to render
  16378. */
  16379. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16380. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16381. };
  16382. /**
  16383. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16384. * @param subMeshes The submeshes to render
  16385. */
  16386. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16387. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16388. };
  16389. /**
  16390. * Renders the submeshes in a specified order.
  16391. * @param subMeshes The submeshes to sort before render
  16392. * @param sortCompareFn The comparison function use to sort
  16393. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16394. * @param transparent Specifies to activate blending if true
  16395. */
  16396. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16397. var subIndex = 0;
  16398. var subMesh;
  16399. for (; subIndex < subMeshes.length; subIndex++) {
  16400. subMesh = subMeshes.data[subIndex];
  16401. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16402. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16403. }
  16404. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16405. sortedArray.sort(sortCompareFn);
  16406. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16407. subMesh = sortedArray[subIndex];
  16408. subMesh.render(transparent);
  16409. }
  16410. };
  16411. /**
  16412. * Renders the submeshes in the order they were dispatched (no sort applied).
  16413. * @param subMeshes The submeshes to render
  16414. */
  16415. RenderingGroup.renderUnsorted = function (subMeshes) {
  16416. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16417. var submesh = subMeshes.data[subIndex];
  16418. submesh.render(false);
  16419. }
  16420. };
  16421. /**
  16422. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16423. * are rendered back to front if in the same alpha index.
  16424. *
  16425. * @param a The first submesh
  16426. * @param b The second submesh
  16427. * @returns The result of the comparison
  16428. */
  16429. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16430. // Alpha index first
  16431. if (a._alphaIndex > b._alphaIndex) {
  16432. return 1;
  16433. }
  16434. if (a._alphaIndex < b._alphaIndex) {
  16435. return -1;
  16436. }
  16437. // Then distance to camera
  16438. return RenderingGroup.backToFrontSortCompare(a, b);
  16439. };
  16440. /**
  16441. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16442. * are rendered back to front.
  16443. *
  16444. * @param a The first submesh
  16445. * @param b The second submesh
  16446. * @returns The result of the comparison
  16447. */
  16448. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16449. // Then distance to camera
  16450. if (a._distanceToCamera < b._distanceToCamera) {
  16451. return 1;
  16452. }
  16453. if (a._distanceToCamera > b._distanceToCamera) {
  16454. return -1;
  16455. }
  16456. return 0;
  16457. };
  16458. /**
  16459. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16460. * are rendered front to back (prevent overdraw).
  16461. *
  16462. * @param a The first submesh
  16463. * @param b The second submesh
  16464. * @returns The result of the comparison
  16465. */
  16466. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16467. // Then distance to camera
  16468. if (a._distanceToCamera < b._distanceToCamera) {
  16469. return -1;
  16470. }
  16471. if (a._distanceToCamera > b._distanceToCamera) {
  16472. return 1;
  16473. }
  16474. return 0;
  16475. };
  16476. /**
  16477. * Resets the different lists of submeshes to prepare a new frame.
  16478. */
  16479. RenderingGroup.prototype.prepare = function () {
  16480. this._opaqueSubMeshes.reset();
  16481. this._transparentSubMeshes.reset();
  16482. this._alphaTestSubMeshes.reset();
  16483. this._particleSystems.reset();
  16484. this._spriteManagers.reset();
  16485. };
  16486. /**
  16487. * Inserts the submesh in its correct queue depending on its material.
  16488. * @param subMesh The submesh to dispatch
  16489. */
  16490. RenderingGroup.prototype.dispatch = function (subMesh) {
  16491. var material = subMesh.getMaterial();
  16492. var mesh = subMesh.getMesh();
  16493. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16494. this._transparentSubMeshes.push(subMesh);
  16495. }
  16496. else if (material.needAlphaTesting()) {
  16497. this._alphaTestSubMeshes.push(subMesh);
  16498. }
  16499. else {
  16500. this._opaqueSubMeshes.push(subMesh); // Opaque
  16501. }
  16502. };
  16503. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  16504. this._spriteManagers.push(spriteManager);
  16505. };
  16506. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  16507. this._particleSystems.push(particleSystem);
  16508. };
  16509. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  16510. if (this._particleSystems.length === 0) {
  16511. return;
  16512. }
  16513. // Particles
  16514. var activeCamera = this._scene.activeCamera;
  16515. this._scene._particlesDuration.beginMonitoring();
  16516. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16517. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16518. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16519. continue;
  16520. }
  16521. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  16522. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16523. }
  16524. }
  16525. this._scene._particlesDuration.endMonitoring(false);
  16526. };
  16527. RenderingGroup.prototype._renderSprites = function () {
  16528. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16529. return;
  16530. }
  16531. // Sprites
  16532. var activeCamera = this._scene.activeCamera;
  16533. this._scene._spritesDuration.beginMonitoring();
  16534. for (var id = 0; id < this._spriteManagers.length; id++) {
  16535. var spriteManager = this._scene.spriteManagers[id];
  16536. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16537. spriteManager.render();
  16538. }
  16539. }
  16540. this._scene._spritesDuration.endMonitoring(false);
  16541. };
  16542. return RenderingGroup;
  16543. }());
  16544. BABYLON.RenderingGroup = RenderingGroup;
  16545. })(BABYLON || (BABYLON = {}));
  16546. //# sourceMappingURL=babylon.renderingGroup.js.map
  16547. var BABYLON;
  16548. (function (BABYLON) {
  16549. var PointerEventTypes = (function () {
  16550. function PointerEventTypes() {
  16551. }
  16552. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  16553. get: function () {
  16554. return PointerEventTypes._POINTERDOWN;
  16555. },
  16556. enumerable: true,
  16557. configurable: true
  16558. });
  16559. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  16560. get: function () {
  16561. return PointerEventTypes._POINTERUP;
  16562. },
  16563. enumerable: true,
  16564. configurable: true
  16565. });
  16566. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  16567. get: function () {
  16568. return PointerEventTypes._POINTERMOVE;
  16569. },
  16570. enumerable: true,
  16571. configurable: true
  16572. });
  16573. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  16574. get: function () {
  16575. return PointerEventTypes._POINTERWHEEL;
  16576. },
  16577. enumerable: true,
  16578. configurable: true
  16579. });
  16580. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  16581. get: function () {
  16582. return PointerEventTypes._POINTERPICK;
  16583. },
  16584. enumerable: true,
  16585. configurable: true
  16586. });
  16587. return PointerEventTypes;
  16588. }());
  16589. PointerEventTypes._POINTERDOWN = 0x01;
  16590. PointerEventTypes._POINTERUP = 0x02;
  16591. PointerEventTypes._POINTERMOVE = 0x04;
  16592. PointerEventTypes._POINTERWHEEL = 0x08;
  16593. PointerEventTypes._POINTERPICK = 0x10;
  16594. BABYLON.PointerEventTypes = PointerEventTypes;
  16595. var PointerInfoBase = (function () {
  16596. function PointerInfoBase(type, event) {
  16597. this.type = type;
  16598. this.event = event;
  16599. }
  16600. return PointerInfoBase;
  16601. }());
  16602. BABYLON.PointerInfoBase = PointerInfoBase;
  16603. /**
  16604. * This class is used to store pointer related info for the onPrePointerObservable event.
  16605. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  16606. */
  16607. var PointerInfoPre = (function (_super) {
  16608. __extends(PointerInfoPre, _super);
  16609. function PointerInfoPre(type, event, localX, localY) {
  16610. var _this = _super.call(this, type, event) || this;
  16611. _this.skipOnPointerObservable = false;
  16612. _this.localPosition = new BABYLON.Vector2(localX, localY);
  16613. return _this;
  16614. }
  16615. return PointerInfoPre;
  16616. }(PointerInfoBase));
  16617. BABYLON.PointerInfoPre = PointerInfoPre;
  16618. /**
  16619. * This type contains all the data related to a pointer event in Babylon.js.
  16620. * 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.
  16621. */
  16622. var PointerInfo = (function (_super) {
  16623. __extends(PointerInfo, _super);
  16624. function PointerInfo(type, event, pickInfo) {
  16625. var _this = _super.call(this, type, event) || this;
  16626. _this.pickInfo = pickInfo;
  16627. return _this;
  16628. }
  16629. return PointerInfo;
  16630. }(PointerInfoBase));
  16631. BABYLON.PointerInfo = PointerInfo;
  16632. /**
  16633. * This class is used by the onRenderingGroupObservable
  16634. */
  16635. var RenderingGroupInfo = (function () {
  16636. function RenderingGroupInfo() {
  16637. }
  16638. return RenderingGroupInfo;
  16639. }());
  16640. /**
  16641. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16642. * This stage will be fired no matter what
  16643. */
  16644. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16645. /**
  16646. * Called before opaque object are rendered.
  16647. * This stage will be fired only if there's 3D Opaque content to render
  16648. */
  16649. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16650. /**
  16651. * Called after the opaque objects are rendered and before the transparent ones
  16652. * This stage will be fired only if there's 3D transparent content to render
  16653. */
  16654. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16655. /**
  16656. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16657. * This stage will be fired no matter what
  16658. */
  16659. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16660. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16661. /**
  16662. * Represents a scene to be rendered by the engine.
  16663. * @see http://doc.babylonjs.com/page.php?p=21911
  16664. */
  16665. var Scene = (function () {
  16666. /**
  16667. * @constructor
  16668. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16669. */
  16670. function Scene(engine) {
  16671. // Members
  16672. this.autoClear = true;
  16673. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16674. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16675. this.forceWireframe = false;
  16676. this.forcePointsCloud = false;
  16677. this.forceShowBoundingBoxes = false;
  16678. this.animationsEnabled = true;
  16679. this.constantlyUpdateMeshUnderPointer = false;
  16680. this.useRightHandedSystem = false;
  16681. this.hoverCursor = "pointer";
  16682. // Metadata
  16683. this.metadata = null;
  16684. // Events
  16685. /**
  16686. * An event triggered when the scene is disposed.
  16687. * @type {BABYLON.Observable}
  16688. */
  16689. this.onDisposeObservable = new BABYLON.Observable();
  16690. /**
  16691. * An event triggered before rendering the scene
  16692. * @type {BABYLON.Observable}
  16693. */
  16694. this.onBeforeRenderObservable = new BABYLON.Observable();
  16695. /**
  16696. * An event triggered after rendering the scene
  16697. * @type {BABYLON.Observable}
  16698. */
  16699. this.onAfterRenderObservable = new BABYLON.Observable();
  16700. /**
  16701. * An event triggered when the scene is ready
  16702. * @type {BABYLON.Observable}
  16703. */
  16704. this.onReadyObservable = new BABYLON.Observable();
  16705. /**
  16706. * An event triggered before rendering a camera
  16707. * @type {BABYLON.Observable}
  16708. */
  16709. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16710. /**
  16711. * An event triggered after rendering a camera
  16712. * @type {BABYLON.Observable}
  16713. */
  16714. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16715. /**
  16716. * An event triggered when a camera is created
  16717. * @type {BABYLON.Observable}
  16718. */
  16719. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16720. /**
  16721. * An event triggered when a camera is removed
  16722. * @type {BABYLON.Observable}
  16723. */
  16724. this.onCameraRemovedObservable = new BABYLON.Observable();
  16725. /**
  16726. * An event triggered when a light is created
  16727. * @type {BABYLON.Observable}
  16728. */
  16729. this.onNewLightAddedObservable = new BABYLON.Observable();
  16730. /**
  16731. * An event triggered when a light is removed
  16732. * @type {BABYLON.Observable}
  16733. */
  16734. this.onLightRemovedObservable = new BABYLON.Observable();
  16735. /**
  16736. * An event triggered when a geometry is created
  16737. * @type {BABYLON.Observable}
  16738. */
  16739. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16740. /**
  16741. * An event triggered when a geometry is removed
  16742. * @type {BABYLON.Observable}
  16743. */
  16744. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16745. /**
  16746. * An event triggered when a mesh is created
  16747. * @type {BABYLON.Observable}
  16748. */
  16749. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16750. /**
  16751. * An event triggered when a mesh is removed
  16752. * @type {BABYLON.Observable}
  16753. */
  16754. this.onMeshRemovedObservable = new BABYLON.Observable();
  16755. /**
  16756. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16757. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16758. * 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)
  16759. */
  16760. this.onRenderingGroupObservable = new BABYLON.Observable();
  16761. // Animations
  16762. this.animations = [];
  16763. /**
  16764. * 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).
  16765. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16766. */
  16767. this.onPrePointerObservable = new BABYLON.Observable();
  16768. /**
  16769. * Observable event triggered each time an input event is received from the rendering canvas
  16770. */
  16771. this.onPointerObservable = new BABYLON.Observable();
  16772. 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
  16773. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16774. this._startingPointerTime = 0;
  16775. // Fog
  16776. /**
  16777. * is fog enabled on this scene.
  16778. * @type {boolean}
  16779. */
  16780. this.fogEnabled = true;
  16781. this.fogMode = Scene.FOGMODE_NONE;
  16782. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16783. this.fogDensity = 0.1;
  16784. this.fogStart = 0;
  16785. this.fogEnd = 1000.0;
  16786. // Lights
  16787. /**
  16788. * is shadow enabled on this scene.
  16789. * @type {boolean}
  16790. */
  16791. this.shadowsEnabled = true;
  16792. /**
  16793. * is light enabled on this scene.
  16794. * @type {boolean}
  16795. */
  16796. this.lightsEnabled = true;
  16797. /**
  16798. * All of the lights added to this scene.
  16799. * @see BABYLON.Light
  16800. * @type {BABYLON.Light[]}
  16801. */
  16802. this.lights = new Array();
  16803. // Cameras
  16804. /**
  16805. * All of the cameras added to this scene.
  16806. * @see BABYLON.Camera
  16807. * @type {BABYLON.Camera[]}
  16808. */
  16809. this.cameras = new Array();
  16810. this.activeCameras = new Array();
  16811. // Meshes
  16812. /**
  16813. * All of the (abstract) meshes added to this scene.
  16814. * @see BABYLON.AbstractMesh
  16815. * @type {BABYLON.AbstractMesh[]}
  16816. */
  16817. this.meshes = new Array();
  16818. // Geometries
  16819. this._geometries = new Array();
  16820. this.materials = new Array();
  16821. this.multiMaterials = new Array();
  16822. // Textures
  16823. this.texturesEnabled = true;
  16824. this.textures = new Array();
  16825. // Particles
  16826. this.particlesEnabled = true;
  16827. this.particleSystems = new Array();
  16828. // Sprites
  16829. this.spritesEnabled = true;
  16830. this.spriteManagers = new Array();
  16831. // Layers
  16832. this.layers = new Array();
  16833. this.highlightLayers = new Array();
  16834. // Skeletons
  16835. this.skeletonsEnabled = true;
  16836. this.skeletons = new Array();
  16837. // Lens flares
  16838. this.lensFlaresEnabled = true;
  16839. this.lensFlareSystems = new Array();
  16840. // Collisions
  16841. this.collisionsEnabled = true;
  16842. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16843. // Postprocesses
  16844. this.postProcessesEnabled = true;
  16845. // Customs render targets
  16846. this.renderTargetsEnabled = true;
  16847. this.dumpNextRenderTargets = false;
  16848. this.customRenderTargets = new Array();
  16849. // Imported meshes
  16850. this.importedMeshesFiles = new Array();
  16851. // Probes
  16852. this.probesEnabled = true;
  16853. this.reflectionProbes = new Array();
  16854. this._actionManagers = new Array();
  16855. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16856. // Procedural textures
  16857. this.proceduralTexturesEnabled = true;
  16858. this._proceduralTextures = new Array();
  16859. this.soundTracks = new Array();
  16860. this._audioEnabled = true;
  16861. this._headphone = false;
  16862. // Performance counters
  16863. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16864. this._totalLightsCounter = new BABYLON.PerfCounter();
  16865. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16866. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16867. this._totalVertices = new BABYLON.PerfCounter();
  16868. this._activeIndices = new BABYLON.PerfCounter();
  16869. this._activeParticles = new BABYLON.PerfCounter();
  16870. this._lastFrameDuration = new BABYLON.PerfCounter();
  16871. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16872. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16873. this._particlesDuration = new BABYLON.PerfCounter();
  16874. this._renderDuration = new BABYLON.PerfCounter();
  16875. this._spritesDuration = new BABYLON.PerfCounter();
  16876. this._activeBones = new BABYLON.PerfCounter();
  16877. this._animationTime = 0;
  16878. this.animationTimeScale = 1;
  16879. this._renderId = 0;
  16880. this._executeWhenReadyTimeoutId = -1;
  16881. this._intermediateRendering = false;
  16882. this._toBeDisposed = new BABYLON.SmartArray(256);
  16883. this._pendingData = []; //ANY
  16884. this._activeMeshes = new BABYLON.SmartArray(256);
  16885. this._processedMaterials = new BABYLON.SmartArray(256);
  16886. this._renderTargets = new BABYLON.SmartArray(256);
  16887. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16888. this._activeSkeletons = new BABYLON.SmartArray(32);
  16889. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16890. this._activeAnimatables = new Array();
  16891. this._transformMatrix = BABYLON.Matrix.Zero();
  16892. this._edgesRenderers = new BABYLON.SmartArray(16);
  16893. this._uniqueIdCounter = 0;
  16894. this._engine = engine;
  16895. engine.scenes.push(this);
  16896. this._externalData = new BABYLON.StringDictionary();
  16897. this._uid = null;
  16898. this._renderingManager = new BABYLON.RenderingManager(this);
  16899. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16900. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16901. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16902. if (BABYLON.OutlineRenderer) {
  16903. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16904. }
  16905. this.attachControl();
  16906. if (BABYLON.SoundTrack) {
  16907. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16908. }
  16909. //simplification queue
  16910. if (BABYLON.SimplificationQueue) {
  16911. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16912. }
  16913. //collision coordinator initialization. For now legacy per default.
  16914. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16915. }
  16916. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16917. get: function () {
  16918. return Scene._FOGMODE_NONE;
  16919. },
  16920. enumerable: true,
  16921. configurable: true
  16922. });
  16923. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16924. get: function () {
  16925. return Scene._FOGMODE_EXP;
  16926. },
  16927. enumerable: true,
  16928. configurable: true
  16929. });
  16930. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16931. get: function () {
  16932. return Scene._FOGMODE_EXP2;
  16933. },
  16934. enumerable: true,
  16935. configurable: true
  16936. });
  16937. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16938. get: function () {
  16939. return Scene._FOGMODE_LINEAR;
  16940. },
  16941. enumerable: true,
  16942. configurable: true
  16943. });
  16944. Object.defineProperty(Scene.prototype, "onDispose", {
  16945. set: function (callback) {
  16946. if (this._onDisposeObserver) {
  16947. this.onDisposeObservable.remove(this._onDisposeObserver);
  16948. }
  16949. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16950. },
  16951. enumerable: true,
  16952. configurable: true
  16953. });
  16954. Object.defineProperty(Scene.prototype, "beforeRender", {
  16955. set: function (callback) {
  16956. if (this._onBeforeRenderObserver) {
  16957. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16958. }
  16959. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16960. },
  16961. enumerable: true,
  16962. configurable: true
  16963. });
  16964. Object.defineProperty(Scene.prototype, "afterRender", {
  16965. set: function (callback) {
  16966. if (this._onAfterRenderObserver) {
  16967. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16968. }
  16969. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16970. },
  16971. enumerable: true,
  16972. configurable: true
  16973. });
  16974. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16975. set: function (callback) {
  16976. if (this._onBeforeCameraRenderObserver) {
  16977. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16978. }
  16979. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16980. },
  16981. enumerable: true,
  16982. configurable: true
  16983. });
  16984. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16985. set: function (callback) {
  16986. if (this._onAfterCameraRenderObserver) {
  16987. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16988. }
  16989. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16990. },
  16991. enumerable: true,
  16992. configurable: true
  16993. });
  16994. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16995. get: function () {
  16996. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16997. },
  16998. enumerable: true,
  16999. configurable: true
  17000. });
  17001. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  17002. get: function () {
  17003. if (!this._defaultMaterial) {
  17004. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  17005. }
  17006. return this._defaultMaterial;
  17007. },
  17008. enumerable: true,
  17009. configurable: true
  17010. });
  17011. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17012. get: function () {
  17013. return this._frustumPlanes;
  17014. },
  17015. enumerable: true,
  17016. configurable: true
  17017. });
  17018. Object.defineProperty(Scene.prototype, "debugLayer", {
  17019. // Properties
  17020. get: function () {
  17021. if (!this._debugLayer) {
  17022. this._debugLayer = new BABYLON.DebugLayer(this);
  17023. }
  17024. return this._debugLayer;
  17025. },
  17026. enumerable: true,
  17027. configurable: true
  17028. });
  17029. Object.defineProperty(Scene.prototype, "workerCollisions", {
  17030. get: function () {
  17031. return this._workerCollisions;
  17032. },
  17033. set: function (enabled) {
  17034. enabled = (enabled && !!Worker);
  17035. this._workerCollisions = enabled;
  17036. if (this.collisionCoordinator) {
  17037. this.collisionCoordinator.destroy();
  17038. }
  17039. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  17040. this.collisionCoordinator.init(this);
  17041. },
  17042. enumerable: true,
  17043. configurable: true
  17044. });
  17045. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  17046. get: function () {
  17047. return this._selectionOctree;
  17048. },
  17049. enumerable: true,
  17050. configurable: true
  17051. });
  17052. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  17053. /**
  17054. * The mesh that is currently under the pointer.
  17055. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  17056. */
  17057. get: function () {
  17058. return this._pointerOverMesh;
  17059. },
  17060. enumerable: true,
  17061. configurable: true
  17062. });
  17063. Object.defineProperty(Scene.prototype, "pointerX", {
  17064. /**
  17065. * Current on-screen X position of the pointer
  17066. * @return {number} X position of the pointer
  17067. */
  17068. get: function () {
  17069. return this._pointerX;
  17070. },
  17071. enumerable: true,
  17072. configurable: true
  17073. });
  17074. Object.defineProperty(Scene.prototype, "pointerY", {
  17075. /**
  17076. * Current on-screen Y position of the pointer
  17077. * @return {number} Y position of the pointer
  17078. */
  17079. get: function () {
  17080. return this._pointerY;
  17081. },
  17082. enumerable: true,
  17083. configurable: true
  17084. });
  17085. Scene.prototype.getCachedMaterial = function () {
  17086. return this._cachedMaterial;
  17087. };
  17088. Scene.prototype.getBoundingBoxRenderer = function () {
  17089. return this._boundingBoxRenderer;
  17090. };
  17091. Scene.prototype.getOutlineRenderer = function () {
  17092. return this._outlineRenderer;
  17093. };
  17094. Scene.prototype.getEngine = function () {
  17095. return this._engine;
  17096. };
  17097. Scene.prototype.getTotalVertices = function () {
  17098. return this._totalVertices.current;
  17099. };
  17100. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17101. get: function () {
  17102. return this._totalVertices;
  17103. },
  17104. enumerable: true,
  17105. configurable: true
  17106. });
  17107. Scene.prototype.getActiveIndices = function () {
  17108. return this._activeIndices.current;
  17109. };
  17110. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17111. get: function () {
  17112. return this._activeIndices;
  17113. },
  17114. enumerable: true,
  17115. configurable: true
  17116. });
  17117. Scene.prototype.getActiveParticles = function () {
  17118. return this._activeParticles.current;
  17119. };
  17120. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17121. get: function () {
  17122. return this._activeParticles;
  17123. },
  17124. enumerable: true,
  17125. configurable: true
  17126. });
  17127. Scene.prototype.getActiveBones = function () {
  17128. return this._activeBones.current;
  17129. };
  17130. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17131. get: function () {
  17132. return this._activeBones;
  17133. },
  17134. enumerable: true,
  17135. configurable: true
  17136. });
  17137. // Stats
  17138. Scene.prototype.getLastFrameDuration = function () {
  17139. return this._lastFrameDuration.current;
  17140. };
  17141. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17142. get: function () {
  17143. return this._lastFrameDuration;
  17144. },
  17145. enumerable: true,
  17146. configurable: true
  17147. });
  17148. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17149. return this._evaluateActiveMeshesDuration.current;
  17150. };
  17151. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17152. get: function () {
  17153. return this._evaluateActiveMeshesDuration;
  17154. },
  17155. enumerable: true,
  17156. configurable: true
  17157. });
  17158. Scene.prototype.getActiveMeshes = function () {
  17159. return this._activeMeshes;
  17160. };
  17161. Scene.prototype.getRenderTargetsDuration = function () {
  17162. return this._renderTargetsDuration.current;
  17163. };
  17164. Scene.prototype.getRenderDuration = function () {
  17165. return this._renderDuration.current;
  17166. };
  17167. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17168. get: function () {
  17169. return this._renderDuration;
  17170. },
  17171. enumerable: true,
  17172. configurable: true
  17173. });
  17174. Scene.prototype.getParticlesDuration = function () {
  17175. return this._particlesDuration.current;
  17176. };
  17177. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17178. get: function () {
  17179. return this._particlesDuration;
  17180. },
  17181. enumerable: true,
  17182. configurable: true
  17183. });
  17184. Scene.prototype.getSpritesDuration = function () {
  17185. return this._spritesDuration.current;
  17186. };
  17187. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17188. get: function () {
  17189. return this._spritesDuration;
  17190. },
  17191. enumerable: true,
  17192. configurable: true
  17193. });
  17194. Scene.prototype.getAnimationRatio = function () {
  17195. return this._animationRatio;
  17196. };
  17197. Scene.prototype.getRenderId = function () {
  17198. return this._renderId;
  17199. };
  17200. Scene.prototype.incrementRenderId = function () {
  17201. this._renderId++;
  17202. };
  17203. Scene.prototype._updatePointerPosition = function (evt) {
  17204. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17205. this._pointerX = evt.clientX - canvasRect.left;
  17206. this._pointerY = evt.clientY - canvasRect.top;
  17207. this._unTranslatedPointerX = this._pointerX;
  17208. this._unTranslatedPointerY = this._pointerY;
  17209. if (this.cameraToUseForPointers) {
  17210. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  17211. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  17212. }
  17213. };
  17214. // Pointers handling
  17215. /**
  17216. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17217. * @param attachUp defines if you want to attach events to pointerup
  17218. * @param attachDown defines if you want to attach events to pointerdown
  17219. * @param attachMove defines if you want to attach events to pointermove
  17220. */
  17221. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17222. var _this = this;
  17223. if (attachUp === void 0) { attachUp = true; }
  17224. if (attachDown === void 0) { attachDown = true; }
  17225. if (attachMove === void 0) { attachMove = true; }
  17226. var spritePredicate = function (sprite) {
  17227. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17228. };
  17229. this._onPointerMove = function (evt) {
  17230. _this._updatePointerPosition(evt);
  17231. // PreObservable support
  17232. if (_this.onPrePointerObservable.hasObservers()) {
  17233. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17234. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17235. _this.onPrePointerObservable.notifyObservers(pi, type);
  17236. if (pi.skipOnPointerObservable) {
  17237. return;
  17238. }
  17239. }
  17240. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17241. return;
  17242. }
  17243. var canvas = _this._engine.getRenderingCanvas();
  17244. if (!_this.pointerMovePredicate) {
  17245. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  17246. }
  17247. // Meshes
  17248. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17249. if (pickResult.hit && pickResult.pickedMesh) {
  17250. _this.setPointerOverSprite(null);
  17251. _this.setPointerOverMesh(pickResult.pickedMesh);
  17252. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17253. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  17254. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  17255. }
  17256. else {
  17257. canvas.style.cursor = _this.hoverCursor;
  17258. }
  17259. }
  17260. else {
  17261. canvas.style.cursor = "";
  17262. }
  17263. }
  17264. else {
  17265. _this.setPointerOverMesh(null);
  17266. // Sprites
  17267. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17268. if (pickResult.hit && pickResult.pickedSprite) {
  17269. _this.setPointerOverSprite(pickResult.pickedSprite);
  17270. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  17271. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  17272. }
  17273. else {
  17274. canvas.style.cursor = _this.hoverCursor;
  17275. }
  17276. }
  17277. else {
  17278. _this.setPointerOverSprite(null);
  17279. // Restore pointer
  17280. canvas.style.cursor = "";
  17281. }
  17282. }
  17283. if (_this.onPointerMove) {
  17284. _this.onPointerMove(evt, pickResult);
  17285. }
  17286. if (_this.onPointerObservable.hasObservers()) {
  17287. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17288. var pi = new PointerInfo(type, evt, pickResult);
  17289. _this.onPointerObservable.notifyObservers(pi, type);
  17290. }
  17291. };
  17292. this._onPointerDown = function (evt) {
  17293. _this._updatePointerPosition(evt);
  17294. // PreObservable support
  17295. if (_this.onPrePointerObservable.hasObservers()) {
  17296. var type = PointerEventTypes.POINTERDOWN;
  17297. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17298. _this.onPrePointerObservable.notifyObservers(pi, type);
  17299. if (pi.skipOnPointerObservable) {
  17300. return;
  17301. }
  17302. }
  17303. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17304. return;
  17305. }
  17306. _this._startingPointerPosition.x = _this._pointerX;
  17307. _this._startingPointerPosition.y = _this._pointerY;
  17308. _this._startingPointerTime = new Date().getTime();
  17309. if (!_this.pointerDownPredicate) {
  17310. _this.pointerDownPredicate = function (mesh) {
  17311. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  17312. };
  17313. }
  17314. // Meshes
  17315. _this._pickedDownMesh = null;
  17316. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17317. if (pickResult.hit && pickResult.pickedMesh) {
  17318. if (pickResult.pickedMesh.actionManager) {
  17319. _this._pickedDownMesh = pickResult.pickedMesh;
  17320. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  17321. switch (evt.button) {
  17322. case 0:
  17323. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17324. break;
  17325. case 1:
  17326. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17327. break;
  17328. case 2:
  17329. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17330. break;
  17331. }
  17332. if (pickResult.pickedMesh.actionManager) {
  17333. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17334. }
  17335. }
  17336. if (pickResult.pickedMesh.actionManager && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17337. var that = _this;
  17338. window.setTimeout(function () {
  17339. var pickResult = that.pick(that._unTranslatedPointerX, that._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger); }, false, that.cameraToUseForPointers);
  17340. if (pickResult.hit && pickResult.pickedMesh) {
  17341. if (pickResult.pickedMesh.actionManager) {
  17342. if (that._startingPointerTime !== 0 && ((new Date().getTime() - that._startingPointerTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(that._startingPointerPosition.x - that._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(that._startingPointerPosition.y - that._pointerY) < BABYLON.ActionManager.DragMovementThreshold)) {
  17343. that._startingPointerTime = 0;
  17344. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17345. }
  17346. }
  17347. }
  17348. }, BABYLON.ActionManager.LongPressDelay);
  17349. }
  17350. }
  17351. }
  17352. if (_this.onPointerDown) {
  17353. _this.onPointerDown(evt, pickResult);
  17354. }
  17355. if (_this.onPointerObservable.hasObservers()) {
  17356. var type = PointerEventTypes.POINTERDOWN;
  17357. var pi = new PointerInfo(type, evt, pickResult);
  17358. _this.onPointerObservable.notifyObservers(pi, type);
  17359. }
  17360. // Sprites
  17361. _this._pickedDownSprite = null;
  17362. if (_this.spriteManagers.length > 0) {
  17363. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17364. if (pickResult.hit && pickResult.pickedSprite) {
  17365. if (pickResult.pickedSprite.actionManager) {
  17366. _this._pickedDownSprite = pickResult.pickedSprite;
  17367. switch (evt.button) {
  17368. case 0:
  17369. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17370. break;
  17371. case 1:
  17372. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17373. break;
  17374. case 2:
  17375. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17376. break;
  17377. }
  17378. if (pickResult.pickedSprite.actionManager) {
  17379. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17380. }
  17381. }
  17382. }
  17383. }
  17384. };
  17385. this._onPointerUp = function (evt) {
  17386. _this._updatePointerPosition(evt);
  17387. // PreObservable support
  17388. if (_this.onPrePointerObservable.hasObservers()) {
  17389. var type = PointerEventTypes.POINTERUP;
  17390. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17391. _this.onPrePointerObservable.notifyObservers(pi, type);
  17392. if (pi.skipOnPointerObservable) {
  17393. return;
  17394. }
  17395. }
  17396. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17397. return;
  17398. }
  17399. if (!_this.pointerUpPredicate) {
  17400. _this.pointerUpPredicate = function (mesh) {
  17401. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  17402. };
  17403. }
  17404. // Meshes
  17405. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  17406. if (pickResult.hit && pickResult.pickedMesh) {
  17407. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  17408. if (_this.onPointerPick) {
  17409. _this.onPointerPick(evt, pickResult);
  17410. }
  17411. if (_this.onPointerObservable.hasObservers()) {
  17412. var type = PointerEventTypes.POINTERPICK;
  17413. var pi = new PointerInfo(type, evt, pickResult);
  17414. _this.onPointerObservable.notifyObservers(pi, type);
  17415. }
  17416. }
  17417. if (pickResult.pickedMesh.actionManager) {
  17418. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17419. if (pickResult.pickedMesh.actionManager) {
  17420. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  17421. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17422. }
  17423. }
  17424. }
  17425. }
  17426. if (_this._pickedDownMesh && _this._pickedDownMesh.actionManager && _this._pickedDownMesh !== pickResult.pickedMesh) {
  17427. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  17428. }
  17429. if (_this.onPointerUp) {
  17430. _this.onPointerUp(evt, pickResult);
  17431. }
  17432. if (_this.onPointerObservable.hasObservers()) {
  17433. var type = PointerEventTypes.POINTERUP;
  17434. var pi = new PointerInfo(type, evt, pickResult);
  17435. _this.onPointerObservable.notifyObservers(pi, type);
  17436. }
  17437. _this._startingPointerTime = 0;
  17438. // Sprites
  17439. if (_this.spriteManagers.length > 0) {
  17440. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17441. if (pickResult.hit && pickResult.pickedSprite) {
  17442. if (pickResult.pickedSprite.actionManager) {
  17443. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17444. if (pickResult.pickedSprite.actionManager) {
  17445. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  17446. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17447. }
  17448. }
  17449. }
  17450. }
  17451. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== pickResult.pickedSprite) {
  17452. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  17453. }
  17454. }
  17455. };
  17456. this._onKeyDown = function (evt) {
  17457. if (_this.actionManager) {
  17458. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17459. }
  17460. };
  17461. this._onKeyUp = function (evt) {
  17462. if (_this.actionManager) {
  17463. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17464. }
  17465. };
  17466. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17467. var canvas = this._engine.getRenderingCanvas();
  17468. if (attachMove) {
  17469. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17470. // Wheel
  17471. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17472. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17473. }
  17474. if (attachDown) {
  17475. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17476. }
  17477. if (attachUp) {
  17478. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17479. }
  17480. canvas.tabIndex = 1;
  17481. canvas.addEventListener("keydown", this._onKeyDown, false);
  17482. canvas.addEventListener("keyup", this._onKeyUp, false);
  17483. };
  17484. Scene.prototype.detachControl = function () {
  17485. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17486. var canvas = this._engine.getRenderingCanvas();
  17487. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17488. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17489. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17490. // Wheel
  17491. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17492. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17493. canvas.removeEventListener("keydown", this._onKeyDown);
  17494. canvas.removeEventListener("keyup", this._onKeyUp);
  17495. };
  17496. // Ready
  17497. Scene.prototype.isReady = function () {
  17498. if (this._pendingData.length > 0) {
  17499. return false;
  17500. }
  17501. var index;
  17502. for (index = 0; index < this._geometries.length; index++) {
  17503. var geometry = this._geometries[index];
  17504. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17505. return false;
  17506. }
  17507. }
  17508. for (index = 0; index < this.meshes.length; index++) {
  17509. var mesh = this.meshes[index];
  17510. if (!mesh.isReady()) {
  17511. return false;
  17512. }
  17513. var mat = mesh.material;
  17514. if (mat) {
  17515. if (!mat.isReady(mesh)) {
  17516. return false;
  17517. }
  17518. }
  17519. }
  17520. return true;
  17521. };
  17522. Scene.prototype.resetCachedMaterial = function () {
  17523. this._cachedMaterial = null;
  17524. };
  17525. Scene.prototype.registerBeforeRender = function (func) {
  17526. this.onBeforeRenderObservable.add(func);
  17527. };
  17528. Scene.prototype.unregisterBeforeRender = function (func) {
  17529. this.onBeforeRenderObservable.removeCallback(func);
  17530. };
  17531. Scene.prototype.registerAfterRender = function (func) {
  17532. this.onAfterRenderObservable.add(func);
  17533. };
  17534. Scene.prototype.unregisterAfterRender = function (func) {
  17535. this.onAfterRenderObservable.removeCallback(func);
  17536. };
  17537. Scene.prototype._addPendingData = function (data) {
  17538. this._pendingData.push(data);
  17539. };
  17540. Scene.prototype._removePendingData = function (data) {
  17541. var index = this._pendingData.indexOf(data);
  17542. if (index !== -1) {
  17543. this._pendingData.splice(index, 1);
  17544. }
  17545. };
  17546. Scene.prototype.getWaitingItemsCount = function () {
  17547. return this._pendingData.length;
  17548. };
  17549. /**
  17550. * Registers a function to be executed when the scene is ready.
  17551. * @param {Function} func - the function to be executed.
  17552. */
  17553. Scene.prototype.executeWhenReady = function (func) {
  17554. var _this = this;
  17555. this.onReadyObservable.add(func);
  17556. if (this._executeWhenReadyTimeoutId !== -1) {
  17557. return;
  17558. }
  17559. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17560. _this._checkIsReady();
  17561. }, 150);
  17562. };
  17563. Scene.prototype._checkIsReady = function () {
  17564. var _this = this;
  17565. if (this.isReady()) {
  17566. this.onReadyObservable.notifyObservers(this);
  17567. this.onReadyObservable.clear();
  17568. this._executeWhenReadyTimeoutId = -1;
  17569. return;
  17570. }
  17571. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17572. _this._checkIsReady();
  17573. }, 150);
  17574. };
  17575. // Animations
  17576. /**
  17577. * Will start the animation sequence of a given target
  17578. * @param target - the target
  17579. * @param {number} from - from which frame should animation start
  17580. * @param {number} to - till which frame should animation run.
  17581. * @param {boolean} [loop] - should the animation loop
  17582. * @param {number} [speedRatio] - the speed in which to run the animation
  17583. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17584. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17585. * @return {BABYLON.Animatable} the animatable object created for this animation
  17586. * @see BABYLON.Animatable
  17587. * @see http://doc.babylonjs.com/page.php?p=22081
  17588. */
  17589. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17590. if (speedRatio === void 0) { speedRatio = 1.0; }
  17591. this.stopAnimation(target);
  17592. if (!animatable) {
  17593. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17594. }
  17595. // Local animations
  17596. if (target.animations) {
  17597. animatable.appendAnimations(target, target.animations);
  17598. }
  17599. // Children animations
  17600. if (target.getAnimatables) {
  17601. var animatables = target.getAnimatables();
  17602. for (var index = 0; index < animatables.length; index++) {
  17603. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17604. }
  17605. }
  17606. animatable.reset();
  17607. return animatable;
  17608. };
  17609. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17610. if (speedRatio === undefined) {
  17611. speedRatio = 1.0;
  17612. }
  17613. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17614. return animatable;
  17615. };
  17616. Scene.prototype.getAnimatableByTarget = function (target) {
  17617. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17618. if (this._activeAnimatables[index].target === target) {
  17619. return this._activeAnimatables[index];
  17620. }
  17621. }
  17622. return null;
  17623. };
  17624. Object.defineProperty(Scene.prototype, "Animatables", {
  17625. get: function () {
  17626. return this._activeAnimatables;
  17627. },
  17628. enumerable: true,
  17629. configurable: true
  17630. });
  17631. /**
  17632. * Will stop the animation of the given target
  17633. * @param target - the target
  17634. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17635. * @see beginAnimation
  17636. */
  17637. Scene.prototype.stopAnimation = function (target, animationName) {
  17638. var animatable = this.getAnimatableByTarget(target);
  17639. if (animatable) {
  17640. animatable.stop(animationName);
  17641. }
  17642. };
  17643. Scene.prototype._animate = function () {
  17644. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17645. return;
  17646. }
  17647. // Getting time
  17648. var now = BABYLON.Tools.Now;
  17649. if (!this._animationTimeLast) {
  17650. if (this._pendingData.length > 0) {
  17651. return;
  17652. }
  17653. this._animationTimeLast = now;
  17654. }
  17655. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  17656. this._animationTime += deltaTime;
  17657. this._animationTimeLast = now;
  17658. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17659. this._activeAnimatables[index]._animate(this._animationTime);
  17660. }
  17661. };
  17662. // Matrix
  17663. Scene.prototype.getViewMatrix = function () {
  17664. return this._viewMatrix;
  17665. };
  17666. Scene.prototype.getProjectionMatrix = function () {
  17667. return this._projectionMatrix;
  17668. };
  17669. Scene.prototype.getTransformMatrix = function () {
  17670. return this._transformMatrix;
  17671. };
  17672. Scene.prototype.setTransformMatrix = function (view, projection) {
  17673. this._viewMatrix = view;
  17674. this._projectionMatrix = projection;
  17675. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17676. // Update frustum
  17677. if (!this._frustumPlanes) {
  17678. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17679. }
  17680. else {
  17681. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17682. }
  17683. };
  17684. // Methods
  17685. Scene.prototype.addMesh = function (newMesh) {
  17686. newMesh.uniqueId = this._uniqueIdCounter++;
  17687. var position = this.meshes.push(newMesh);
  17688. //notify the collision coordinator
  17689. this.collisionCoordinator.onMeshAdded(newMesh);
  17690. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17691. };
  17692. Scene.prototype.removeMesh = function (toRemove) {
  17693. var index = this.meshes.indexOf(toRemove);
  17694. if (index !== -1) {
  17695. // Remove from the scene if mesh found
  17696. this.meshes.splice(index, 1);
  17697. }
  17698. //notify the collision coordinator
  17699. this.collisionCoordinator.onMeshRemoved(toRemove);
  17700. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17701. return index;
  17702. };
  17703. Scene.prototype.removeSkeleton = function (toRemove) {
  17704. var index = this.skeletons.indexOf(toRemove);
  17705. if (index !== -1) {
  17706. // Remove from the scene if mesh found
  17707. this.skeletons.splice(index, 1);
  17708. }
  17709. return index;
  17710. };
  17711. Scene.prototype.removeLight = function (toRemove) {
  17712. var index = this.lights.indexOf(toRemove);
  17713. if (index !== -1) {
  17714. // Remove from the scene if mesh found
  17715. this.lights.splice(index, 1);
  17716. }
  17717. this.onLightRemovedObservable.notifyObservers(toRemove);
  17718. return index;
  17719. };
  17720. Scene.prototype.removeCamera = function (toRemove) {
  17721. var index = this.cameras.indexOf(toRemove);
  17722. if (index !== -1) {
  17723. // Remove from the scene if mesh found
  17724. this.cameras.splice(index, 1);
  17725. }
  17726. // Remove from activeCameras
  17727. var index2 = this.activeCameras.indexOf(toRemove);
  17728. if (index2 !== -1) {
  17729. // Remove from the scene if mesh found
  17730. this.activeCameras.splice(index2, 1);
  17731. }
  17732. // Reset the activeCamera
  17733. if (this.activeCamera === toRemove) {
  17734. if (this.cameras.length > 0) {
  17735. this.activeCamera = this.cameras[0];
  17736. }
  17737. else {
  17738. this.activeCamera = null;
  17739. }
  17740. }
  17741. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17742. return index;
  17743. };
  17744. Scene.prototype.addLight = function (newLight) {
  17745. newLight.uniqueId = this._uniqueIdCounter++;
  17746. var position = this.lights.push(newLight);
  17747. this.onNewLightAddedObservable.notifyObservers(newLight);
  17748. };
  17749. Scene.prototype.addCamera = function (newCamera) {
  17750. newCamera.uniqueId = this._uniqueIdCounter++;
  17751. var position = this.cameras.push(newCamera);
  17752. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17753. };
  17754. /**
  17755. * Switch active camera
  17756. * @param {Camera} newCamera - new active camera
  17757. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17758. */
  17759. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17760. if (attachControl === void 0) { attachControl = true; }
  17761. var canvas = this._engine.getRenderingCanvas();
  17762. this.activeCamera.detachControl(canvas);
  17763. this.activeCamera = newCamera;
  17764. if (attachControl) {
  17765. newCamera.attachControl(canvas);
  17766. }
  17767. };
  17768. /**
  17769. * sets the active camera of the scene using its ID
  17770. * @param {string} id - the camera's ID
  17771. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17772. * @see activeCamera
  17773. */
  17774. Scene.prototype.setActiveCameraByID = function (id) {
  17775. var camera = this.getCameraByID(id);
  17776. if (camera) {
  17777. this.activeCamera = camera;
  17778. return camera;
  17779. }
  17780. return null;
  17781. };
  17782. /**
  17783. * sets the active camera of the scene using its name
  17784. * @param {string} name - the camera's name
  17785. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17786. * @see activeCamera
  17787. */
  17788. Scene.prototype.setActiveCameraByName = function (name) {
  17789. var camera = this.getCameraByName(name);
  17790. if (camera) {
  17791. this.activeCamera = camera;
  17792. return camera;
  17793. }
  17794. return null;
  17795. };
  17796. /**
  17797. * get a material using its id
  17798. * @param {string} the material's ID
  17799. * @return {BABYLON.Material|null} the material or null if none found.
  17800. */
  17801. Scene.prototype.getMaterialByID = function (id) {
  17802. for (var index = 0; index < this.materials.length; index++) {
  17803. if (this.materials[index].id === id) {
  17804. return this.materials[index];
  17805. }
  17806. }
  17807. return null;
  17808. };
  17809. /**
  17810. * get a material using its name
  17811. * @param {string} the material's name
  17812. * @return {BABYLON.Material|null} the material or null if none found.
  17813. */
  17814. Scene.prototype.getMaterialByName = function (name) {
  17815. for (var index = 0; index < this.materials.length; index++) {
  17816. if (this.materials[index].name === name) {
  17817. return this.materials[index];
  17818. }
  17819. }
  17820. return null;
  17821. };
  17822. Scene.prototype.getLensFlareSystemByName = function (name) {
  17823. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17824. if (this.lensFlareSystems[index].name === name) {
  17825. return this.lensFlareSystems[index];
  17826. }
  17827. }
  17828. return null;
  17829. };
  17830. Scene.prototype.getLensFlareSystemByID = function (id) {
  17831. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17832. if (this.lensFlareSystems[index].id === id) {
  17833. return this.lensFlareSystems[index];
  17834. }
  17835. }
  17836. return null;
  17837. };
  17838. Scene.prototype.getCameraByID = function (id) {
  17839. for (var index = 0; index < this.cameras.length; index++) {
  17840. if (this.cameras[index].id === id) {
  17841. return this.cameras[index];
  17842. }
  17843. }
  17844. return null;
  17845. };
  17846. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17847. for (var index = 0; index < this.cameras.length; index++) {
  17848. if (this.cameras[index].uniqueId === uniqueId) {
  17849. return this.cameras[index];
  17850. }
  17851. }
  17852. return null;
  17853. };
  17854. /**
  17855. * get a camera using its name
  17856. * @param {string} the camera's name
  17857. * @return {BABYLON.Camera|null} the camera or null if none found.
  17858. */
  17859. Scene.prototype.getCameraByName = function (name) {
  17860. for (var index = 0; index < this.cameras.length; index++) {
  17861. if (this.cameras[index].name === name) {
  17862. return this.cameras[index];
  17863. }
  17864. }
  17865. return null;
  17866. };
  17867. /**
  17868. * get a bone using its id
  17869. * @param {string} the bone's id
  17870. * @return {BABYLON.Bone|null} the bone or null if not found
  17871. */
  17872. Scene.prototype.getBoneByID = function (id) {
  17873. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17874. var skeleton = this.skeletons[skeletonIndex];
  17875. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17876. if (skeleton.bones[boneIndex].id === id) {
  17877. return skeleton.bones[boneIndex];
  17878. }
  17879. }
  17880. }
  17881. return null;
  17882. };
  17883. /**
  17884. * get a bone using its id
  17885. * @param {string} the bone's name
  17886. * @return {BABYLON.Bone|null} the bone or null if not found
  17887. */
  17888. Scene.prototype.getBoneByName = function (name) {
  17889. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17890. var skeleton = this.skeletons[skeletonIndex];
  17891. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17892. if (skeleton.bones[boneIndex].name === name) {
  17893. return skeleton.bones[boneIndex];
  17894. }
  17895. }
  17896. }
  17897. return null;
  17898. };
  17899. /**
  17900. * get a light node using its name
  17901. * @param {string} the light's name
  17902. * @return {BABYLON.Light|null} the light or null if none found.
  17903. */
  17904. Scene.prototype.getLightByName = function (name) {
  17905. for (var index = 0; index < this.lights.length; index++) {
  17906. if (this.lights[index].name === name) {
  17907. return this.lights[index];
  17908. }
  17909. }
  17910. return null;
  17911. };
  17912. /**
  17913. * get a light node using its ID
  17914. * @param {string} the light's id
  17915. * @return {BABYLON.Light|null} the light or null if none found.
  17916. */
  17917. Scene.prototype.getLightByID = function (id) {
  17918. for (var index = 0; index < this.lights.length; index++) {
  17919. if (this.lights[index].id === id) {
  17920. return this.lights[index];
  17921. }
  17922. }
  17923. return null;
  17924. };
  17925. /**
  17926. * get a light node using its scene-generated unique ID
  17927. * @param {number} the light's unique id
  17928. * @return {BABYLON.Light|null} the light or null if none found.
  17929. */
  17930. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17931. for (var index = 0; index < this.lights.length; index++) {
  17932. if (this.lights[index].uniqueId === uniqueId) {
  17933. return this.lights[index];
  17934. }
  17935. }
  17936. return null;
  17937. };
  17938. /**
  17939. * get a particle system by id
  17940. * @param id {number} the particle system id
  17941. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17942. */
  17943. Scene.prototype.getParticleSystemByID = function (id) {
  17944. for (var index = 0; index < this.particleSystems.length; index++) {
  17945. if (this.particleSystems[index].id === id) {
  17946. return this.particleSystems[index];
  17947. }
  17948. }
  17949. return null;
  17950. };
  17951. /**
  17952. * get a geometry using its ID
  17953. * @param {string} the geometry's id
  17954. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17955. */
  17956. Scene.prototype.getGeometryByID = function (id) {
  17957. for (var index = 0; index < this._geometries.length; index++) {
  17958. if (this._geometries[index].id === id) {
  17959. return this._geometries[index];
  17960. }
  17961. }
  17962. return null;
  17963. };
  17964. /**
  17965. * add a new geometry to this scene.
  17966. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17967. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17968. * @return {boolean} was the geometry added or not
  17969. */
  17970. Scene.prototype.pushGeometry = function (geometry, force) {
  17971. if (!force && this.getGeometryByID(geometry.id)) {
  17972. return false;
  17973. }
  17974. this._geometries.push(geometry);
  17975. //notify the collision coordinator
  17976. this.collisionCoordinator.onGeometryAdded(geometry);
  17977. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17978. return true;
  17979. };
  17980. /**
  17981. * Removes an existing geometry
  17982. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17983. * @return {boolean} was the geometry removed or not
  17984. */
  17985. Scene.prototype.removeGeometry = function (geometry) {
  17986. var index = this._geometries.indexOf(geometry);
  17987. if (index > -1) {
  17988. this._geometries.splice(index, 1);
  17989. //notify the collision coordinator
  17990. this.collisionCoordinator.onGeometryDeleted(geometry);
  17991. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17992. return true;
  17993. }
  17994. return false;
  17995. };
  17996. Scene.prototype.getGeometries = function () {
  17997. return this._geometries;
  17998. };
  17999. /**
  18000. * Get the first added mesh found of a given ID
  18001. * @param {string} id - the id to search for
  18002. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18003. */
  18004. Scene.prototype.getMeshByID = function (id) {
  18005. for (var index = 0; index < this.meshes.length; index++) {
  18006. if (this.meshes[index].id === id) {
  18007. return this.meshes[index];
  18008. }
  18009. }
  18010. return null;
  18011. };
  18012. Scene.prototype.getMeshesByID = function (id) {
  18013. return this.meshes.filter(function (m) {
  18014. return m.id === id;
  18015. });
  18016. };
  18017. /**
  18018. * Get a mesh with its auto-generated unique id
  18019. * @param {number} uniqueId - the unique id to search for
  18020. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18021. */
  18022. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18023. for (var index = 0; index < this.meshes.length; index++) {
  18024. if (this.meshes[index].uniqueId === uniqueId) {
  18025. return this.meshes[index];
  18026. }
  18027. }
  18028. return null;
  18029. };
  18030. /**
  18031. * Get a the last added mesh found of a given ID
  18032. * @param {string} id - the id to search for
  18033. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18034. */
  18035. Scene.prototype.getLastMeshByID = function (id) {
  18036. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18037. if (this.meshes[index].id === id) {
  18038. return this.meshes[index];
  18039. }
  18040. }
  18041. return null;
  18042. };
  18043. /**
  18044. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18045. * @param {string} id - the id to search for
  18046. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18047. */
  18048. Scene.prototype.getLastEntryByID = function (id) {
  18049. var index;
  18050. for (index = this.meshes.length - 1; index >= 0; index--) {
  18051. if (this.meshes[index].id === id) {
  18052. return this.meshes[index];
  18053. }
  18054. }
  18055. for (index = this.cameras.length - 1; index >= 0; index--) {
  18056. if (this.cameras[index].id === id) {
  18057. return this.cameras[index];
  18058. }
  18059. }
  18060. for (index = this.lights.length - 1; index >= 0; index--) {
  18061. if (this.lights[index].id === id) {
  18062. return this.lights[index];
  18063. }
  18064. }
  18065. return null;
  18066. };
  18067. Scene.prototype.getNodeByID = function (id) {
  18068. var mesh = this.getMeshByID(id);
  18069. if (mesh) {
  18070. return mesh;
  18071. }
  18072. var light = this.getLightByID(id);
  18073. if (light) {
  18074. return light;
  18075. }
  18076. var camera = this.getCameraByID(id);
  18077. if (camera) {
  18078. return camera;
  18079. }
  18080. var bone = this.getBoneByID(id);
  18081. return bone;
  18082. };
  18083. Scene.prototype.getNodeByName = function (name) {
  18084. var mesh = this.getMeshByName(name);
  18085. if (mesh) {
  18086. return mesh;
  18087. }
  18088. var light = this.getLightByName(name);
  18089. if (light) {
  18090. return light;
  18091. }
  18092. var camera = this.getCameraByName(name);
  18093. if (camera) {
  18094. return camera;
  18095. }
  18096. var bone = this.getBoneByName(name);
  18097. return bone;
  18098. };
  18099. Scene.prototype.getMeshByName = function (name) {
  18100. for (var index = 0; index < this.meshes.length; index++) {
  18101. if (this.meshes[index].name === name) {
  18102. return this.meshes[index];
  18103. }
  18104. }
  18105. return null;
  18106. };
  18107. Scene.prototype.getSoundByName = function (name) {
  18108. var index;
  18109. if (BABYLON.AudioEngine) {
  18110. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18111. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18112. return this.mainSoundTrack.soundCollection[index];
  18113. }
  18114. }
  18115. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18116. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18117. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18118. return this.soundTracks[sdIndex].soundCollection[index];
  18119. }
  18120. }
  18121. }
  18122. }
  18123. return null;
  18124. };
  18125. Scene.prototype.getLastSkeletonByID = function (id) {
  18126. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18127. if (this.skeletons[index].id === id) {
  18128. return this.skeletons[index];
  18129. }
  18130. }
  18131. return null;
  18132. };
  18133. Scene.prototype.getSkeletonById = function (id) {
  18134. for (var index = 0; index < this.skeletons.length; index++) {
  18135. if (this.skeletons[index].id === id) {
  18136. return this.skeletons[index];
  18137. }
  18138. }
  18139. return null;
  18140. };
  18141. Scene.prototype.getSkeletonByName = function (name) {
  18142. for (var index = 0; index < this.skeletons.length; index++) {
  18143. if (this.skeletons[index].name === name) {
  18144. return this.skeletons[index];
  18145. }
  18146. }
  18147. return null;
  18148. };
  18149. Scene.prototype.isActiveMesh = function (mesh) {
  18150. return (this._activeMeshes.indexOf(mesh) !== -1);
  18151. };
  18152. Object.defineProperty(Scene.prototype, "uid", {
  18153. /**
  18154. * Return a unique id as a string which can serve as an identifier for the scene
  18155. */
  18156. get: function () {
  18157. if (!this._uid) {
  18158. this._uid = BABYLON.Tools.RandomId();
  18159. }
  18160. return this._uid;
  18161. },
  18162. enumerable: true,
  18163. configurable: true
  18164. });
  18165. /**
  18166. * Add an externaly attached data from its key.
  18167. * This method call will fail and return false, if such key already exists.
  18168. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18169. * @param key the unique key that identifies the data
  18170. * @param data the data object to associate to the key for this Engine instance
  18171. * @return true if no such key were already present and the data was added successfully, false otherwise
  18172. */
  18173. Scene.prototype.addExternalData = function (key, data) {
  18174. return this._externalData.add(key, data);
  18175. };
  18176. /**
  18177. * Get an externaly attached data from its key
  18178. * @param key the unique key that identifies the data
  18179. * @return the associated data, if present (can be null), or undefined if not present
  18180. */
  18181. Scene.prototype.getExternalData = function (key) {
  18182. return this._externalData.get(key);
  18183. };
  18184. /**
  18185. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18186. * @param key the unique key that identifies the data
  18187. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18188. * @return the associated data, can be null if the factory returned null.
  18189. */
  18190. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18191. return this._externalData.getOrAddWithFactory(key, factory);
  18192. };
  18193. /**
  18194. * Remove an externaly attached data from the Engine instance
  18195. * @param key the unique key that identifies the data
  18196. * @return true if the data was successfully removed, false if it doesn't exist
  18197. */
  18198. Scene.prototype.removeExternalData = function (key) {
  18199. return this._externalData.remove(key);
  18200. };
  18201. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18202. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18203. var material = subMesh.getMaterial();
  18204. if (mesh.showSubMeshesBoundingBox) {
  18205. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  18206. }
  18207. if (material) {
  18208. // Render targets
  18209. if (material.getRenderTargetTextures) {
  18210. if (this._processedMaterials.indexOf(material) === -1) {
  18211. this._processedMaterials.push(material);
  18212. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18213. }
  18214. }
  18215. // Dispatch
  18216. this._activeIndices.addCount(subMesh.indexCount, false);
  18217. this._renderingManager.dispatch(subMesh);
  18218. }
  18219. }
  18220. };
  18221. Scene.prototype._isInIntermediateRendering = function () {
  18222. return this._intermediateRendering;
  18223. };
  18224. Scene.prototype._evaluateActiveMeshes = function () {
  18225. this.activeCamera._activeMeshes.reset();
  18226. this._activeMeshes.reset();
  18227. this._renderingManager.reset();
  18228. this._processedMaterials.reset();
  18229. this._activeParticleSystems.reset();
  18230. this._activeSkeletons.reset();
  18231. this._softwareSkinnedMeshes.reset();
  18232. this._boundingBoxRenderer.reset();
  18233. this._edgesRenderers.reset();
  18234. // Meshes
  18235. var meshes;
  18236. var len;
  18237. if (this._selectionOctree) {
  18238. var selection = this._selectionOctree.select(this._frustumPlanes);
  18239. meshes = selection.data;
  18240. len = selection.length;
  18241. }
  18242. else {
  18243. len = this.meshes.length;
  18244. meshes = this.meshes;
  18245. }
  18246. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18247. var mesh = meshes[meshIndex];
  18248. if (mesh.isBlocked) {
  18249. continue;
  18250. }
  18251. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18252. if (!mesh.isReady() || !mesh.isEnabled()) {
  18253. continue;
  18254. }
  18255. mesh.computeWorldMatrix();
  18256. // Intersections
  18257. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18258. this._meshesForIntersections.pushNoDuplicate(mesh);
  18259. }
  18260. // Switch to current LOD
  18261. var meshLOD = mesh.getLOD(this.activeCamera);
  18262. if (!meshLOD) {
  18263. continue;
  18264. }
  18265. mesh._preActivate();
  18266. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18267. this._activeMeshes.push(mesh);
  18268. this.activeCamera._activeMeshes.push(mesh);
  18269. mesh._activate(this._renderId);
  18270. this._activeMesh(mesh, meshLOD);
  18271. }
  18272. }
  18273. // Particle systems
  18274. this._particlesDuration.beginMonitoring();
  18275. var beforeParticlesDate = BABYLON.Tools.Now;
  18276. if (this.particlesEnabled) {
  18277. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18278. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18279. var particleSystem = this.particleSystems[particleIndex];
  18280. if (!particleSystem.isStarted()) {
  18281. continue;
  18282. }
  18283. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  18284. this._activeParticleSystems.push(particleSystem);
  18285. particleSystem.animate();
  18286. this._renderingManager.dispatchParticles(particleSystem);
  18287. }
  18288. }
  18289. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18290. }
  18291. this._particlesDuration.endMonitoring(false);
  18292. };
  18293. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18294. if (mesh.skeleton && this.skeletonsEnabled) {
  18295. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18296. mesh.skeleton.prepare();
  18297. }
  18298. if (!mesh.computeBonesUsingShaders) {
  18299. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18300. }
  18301. }
  18302. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18303. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18304. }
  18305. if (sourceMesh._edgesRenderer) {
  18306. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  18307. }
  18308. if (mesh && mesh.subMeshes) {
  18309. // Submeshes Octrees
  18310. var len;
  18311. var subMeshes;
  18312. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18313. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18314. len = intersections.length;
  18315. subMeshes = intersections.data;
  18316. }
  18317. else {
  18318. subMeshes = mesh.subMeshes;
  18319. len = subMeshes.length;
  18320. }
  18321. for (var subIndex = 0; subIndex < len; subIndex++) {
  18322. var subMesh = subMeshes[subIndex];
  18323. this._evaluateSubMesh(subMesh, mesh);
  18324. }
  18325. }
  18326. };
  18327. Scene.prototype.updateTransformMatrix = function (force) {
  18328. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18329. };
  18330. Scene.prototype._renderForCamera = function (camera) {
  18331. var engine = this._engine;
  18332. var startTime = BABYLON.Tools.Now;
  18333. this.activeCamera = camera;
  18334. if (!this.activeCamera)
  18335. throw new Error("Active camera not set");
  18336. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18337. // Viewport
  18338. engine.setViewport(this.activeCamera.viewport);
  18339. // Camera
  18340. this.resetCachedMaterial();
  18341. this._renderId++;
  18342. this.updateTransformMatrix();
  18343. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18344. // Meshes
  18345. this._evaluateActiveMeshesDuration.beginMonitoring();
  18346. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18347. this._evaluateActiveMeshes();
  18348. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18349. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18350. // Software skinning
  18351. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18352. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18353. mesh.applySkeleton(mesh.skeleton);
  18354. }
  18355. // Render targets
  18356. this._renderTargetsDuration.beginMonitoring();
  18357. var needsRestoreFrameBuffer = false;
  18358. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18359. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18360. this._intermediateRendering = true;
  18361. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18362. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18363. var renderTarget = this._renderTargets.data[renderIndex];
  18364. if (renderTarget._shouldRender()) {
  18365. this._renderId++;
  18366. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18367. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18368. }
  18369. }
  18370. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18371. this._intermediateRendering = false;
  18372. this._renderId++;
  18373. needsRestoreFrameBuffer = true; // Restore back buffer
  18374. }
  18375. // Render HighlightLayer Texture
  18376. var stencilState = this._engine.getStencilBuffer();
  18377. var renderhighlights = false;
  18378. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18379. this._intermediateRendering = true;
  18380. for (var i = 0; i < this.highlightLayers.length; i++) {
  18381. var highlightLayer = this.highlightLayers[i];
  18382. if (highlightLayer.shouldRender() &&
  18383. (!highlightLayer.camera ||
  18384. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18385. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18386. renderhighlights = true;
  18387. var renderTarget = highlightLayer._mainTexture;
  18388. if (renderTarget._shouldRender()) {
  18389. this._renderId++;
  18390. renderTarget.render(false, false);
  18391. needsRestoreFrameBuffer = true;
  18392. }
  18393. }
  18394. }
  18395. this._intermediateRendering = false;
  18396. this._renderId++;
  18397. }
  18398. if (needsRestoreFrameBuffer) {
  18399. engine.restoreDefaultFramebuffer();
  18400. }
  18401. this._renderTargetsDuration.endMonitoring(false);
  18402. // Prepare Frame
  18403. this.postProcessManager._prepareFrame();
  18404. this._renderDuration.beginMonitoring();
  18405. // Backgrounds
  18406. var layerIndex;
  18407. var layer;
  18408. if (this.layers.length) {
  18409. engine.setDepthBuffer(false);
  18410. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18411. layer = this.layers[layerIndex];
  18412. if (layer.isBackground) {
  18413. layer.render();
  18414. }
  18415. }
  18416. engine.setDepthBuffer(true);
  18417. }
  18418. // Render
  18419. BABYLON.Tools.StartPerformanceCounter("Main render");
  18420. // Activate HighlightLayer stencil
  18421. if (renderhighlights) {
  18422. this._engine.setStencilBuffer(true);
  18423. }
  18424. this._renderingManager.render(null, null, true, true);
  18425. // Restore HighlightLayer stencil
  18426. if (renderhighlights) {
  18427. this._engine.setStencilBuffer(stencilState);
  18428. }
  18429. BABYLON.Tools.EndPerformanceCounter("Main render");
  18430. // Bounding boxes
  18431. this._boundingBoxRenderer.render();
  18432. // Edges
  18433. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18434. this._edgesRenderers.data[edgesRendererIndex].render();
  18435. }
  18436. // Lens flares
  18437. if (this.lensFlaresEnabled) {
  18438. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18439. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18440. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18441. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18442. lensFlareSystem.render();
  18443. }
  18444. }
  18445. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18446. }
  18447. // Foregrounds
  18448. if (this.layers.length) {
  18449. engine.setDepthBuffer(false);
  18450. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18451. layer = this.layers[layerIndex];
  18452. if (!layer.isBackground) {
  18453. layer.render();
  18454. }
  18455. }
  18456. engine.setDepthBuffer(true);
  18457. }
  18458. // Highlight Layer
  18459. if (renderhighlights) {
  18460. engine.setDepthBuffer(false);
  18461. for (var i = 0; i < this.highlightLayers.length; i++) {
  18462. if (this.highlightLayers[i].shouldRender()) {
  18463. this.highlightLayers[i].render();
  18464. }
  18465. }
  18466. engine.setDepthBuffer(true);
  18467. }
  18468. this._renderDuration.endMonitoring(false);
  18469. // Finalize frame
  18470. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18471. // Update camera
  18472. this.activeCamera._updateFromScene();
  18473. // Reset some special arrays
  18474. this._renderTargets.reset();
  18475. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18476. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18477. };
  18478. Scene.prototype._processSubCameras = function (camera) {
  18479. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18480. this._renderForCamera(camera);
  18481. return;
  18482. }
  18483. // rig cameras
  18484. for (var index = 0; index < camera._rigCameras.length; index++) {
  18485. this._renderForCamera(camera._rigCameras[index]);
  18486. }
  18487. this.activeCamera = camera;
  18488. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18489. // Update camera
  18490. this.activeCamera._updateFromScene();
  18491. };
  18492. Scene.prototype._checkIntersections = function () {
  18493. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18494. var sourceMesh = this._meshesForIntersections.data[index];
  18495. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18496. var action = sourceMesh.actionManager.actions[actionIndex];
  18497. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18498. var parameters = action.getTriggerParameter();
  18499. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18500. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18501. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18502. if (areIntersecting && currentIntersectionInProgress === -1) {
  18503. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18504. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18505. sourceMesh._intersectionsInProgress.push(otherMesh);
  18506. }
  18507. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18508. sourceMesh._intersectionsInProgress.push(otherMesh);
  18509. }
  18510. }
  18511. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18512. //They intersected, and now they don't.
  18513. //is this trigger an exit trigger? execute an event.
  18514. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18515. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18516. }
  18517. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18518. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18519. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18520. }
  18521. }
  18522. }
  18523. }
  18524. }
  18525. };
  18526. Scene.prototype.render = function () {
  18527. this._lastFrameDuration.beginMonitoring();
  18528. this._particlesDuration.fetchNewFrame();
  18529. this._spritesDuration.fetchNewFrame();
  18530. this._activeParticles.fetchNewFrame();
  18531. this._renderDuration.fetchNewFrame();
  18532. this._renderTargetsDuration.fetchNewFrame();
  18533. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18534. this._totalVertices.fetchNewFrame();
  18535. this._activeIndices.fetchNewFrame();
  18536. this._activeBones.fetchNewFrame();
  18537. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18538. this._meshesForIntersections.reset();
  18539. this.resetCachedMaterial();
  18540. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18541. // Actions
  18542. if (this.actionManager) {
  18543. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18544. }
  18545. //Simplification Queue
  18546. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18547. this.simplificationQueue.executeNext();
  18548. }
  18549. // Animations
  18550. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18551. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18552. this._animate();
  18553. // Physics
  18554. if (this._physicsEngine) {
  18555. BABYLON.Tools.StartPerformanceCounter("Physics");
  18556. this._physicsEngine._step(deltaTime / 1000.0);
  18557. BABYLON.Tools.EndPerformanceCounter("Physics");
  18558. }
  18559. // Before render
  18560. this.onBeforeRenderObservable.notifyObservers(this);
  18561. // Customs render targets
  18562. this._renderTargetsDuration.beginMonitoring();
  18563. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18564. var engine = this.getEngine();
  18565. var currentActiveCamera = this.activeCamera;
  18566. if (this.renderTargetsEnabled) {
  18567. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18568. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18569. var renderTarget = this.customRenderTargets[customIndex];
  18570. if (renderTarget._shouldRender()) {
  18571. this._renderId++;
  18572. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18573. if (!this.activeCamera)
  18574. throw new Error("Active camera not set");
  18575. // Viewport
  18576. engine.setViewport(this.activeCamera.viewport);
  18577. // Camera
  18578. this.updateTransformMatrix();
  18579. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18580. }
  18581. }
  18582. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18583. this._renderId++;
  18584. }
  18585. if (this.customRenderTargets.length > 0) {
  18586. engine.restoreDefaultFramebuffer();
  18587. }
  18588. this._renderTargetsDuration.endMonitoring();
  18589. this.activeCamera = currentActiveCamera;
  18590. // Procedural textures
  18591. if (this.proceduralTexturesEnabled) {
  18592. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18593. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18594. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18595. if (proceduralTexture._shouldRender()) {
  18596. proceduralTexture.render();
  18597. }
  18598. }
  18599. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18600. }
  18601. // Clear
  18602. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  18603. // Shadows
  18604. if (this.shadowsEnabled) {
  18605. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18606. var light = this.lights[lightIndex];
  18607. var shadowGenerator = light.getShadowGenerator();
  18608. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  18609. this._renderTargets.push(shadowGenerator.getShadowMap());
  18610. }
  18611. }
  18612. }
  18613. // Depth renderer
  18614. if (this._depthRenderer) {
  18615. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18616. }
  18617. // RenderPipeline
  18618. this.postProcessRenderPipelineManager.update();
  18619. // Multi-cameras?
  18620. if (this.activeCameras.length > 0) {
  18621. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18622. if (cameraIndex > 0) {
  18623. this._engine.clear(null, false, true, true);
  18624. }
  18625. this._processSubCameras(this.activeCameras[cameraIndex]);
  18626. }
  18627. }
  18628. else {
  18629. if (!this.activeCamera) {
  18630. throw new Error("No camera defined");
  18631. }
  18632. this._processSubCameras(this.activeCamera);
  18633. }
  18634. // Intersection checks
  18635. this._checkIntersections();
  18636. // Update the audio listener attached to the camera
  18637. if (BABYLON.AudioEngine) {
  18638. this._updateAudioParameters();
  18639. }
  18640. // After render
  18641. if (this.afterRender) {
  18642. this.afterRender();
  18643. }
  18644. this.onAfterRenderObservable.notifyObservers(this);
  18645. // Cleaning
  18646. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18647. this._toBeDisposed.data[index].dispose();
  18648. this._toBeDisposed[index] = null;
  18649. }
  18650. this._toBeDisposed.reset();
  18651. if (this.dumpNextRenderTargets) {
  18652. this.dumpNextRenderTargets = false;
  18653. }
  18654. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18655. this._lastFrameDuration.endMonitoring();
  18656. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18657. this._totalLightsCounter.addCount(this.lights.length, true);
  18658. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18659. this._totalTexturesCounter.addCount(this.textures.length, true);
  18660. this._activeBones.addCount(0, true);
  18661. this._activeIndices.addCount(0, true);
  18662. this._activeParticles.addCount(0, true);
  18663. };
  18664. Scene.prototype._updateAudioParameters = function () {
  18665. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18666. return;
  18667. }
  18668. var listeningCamera;
  18669. var audioEngine = BABYLON.Engine.audioEngine;
  18670. if (this.activeCameras.length > 0) {
  18671. listeningCamera = this.activeCameras[0];
  18672. }
  18673. else {
  18674. listeningCamera = this.activeCamera;
  18675. }
  18676. if (listeningCamera && audioEngine.canUseWebAudio) {
  18677. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18678. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18679. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18680. cameraDirection.normalize();
  18681. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18682. var i;
  18683. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18684. var sound = this.mainSoundTrack.soundCollection[i];
  18685. if (sound.useCustomAttenuation) {
  18686. sound.updateDistanceFromListener();
  18687. }
  18688. }
  18689. for (i = 0; i < this.soundTracks.length; i++) {
  18690. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18691. sound = this.soundTracks[i].soundCollection[j];
  18692. if (sound.useCustomAttenuation) {
  18693. sound.updateDistanceFromListener();
  18694. }
  18695. }
  18696. }
  18697. }
  18698. };
  18699. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18700. // Audio
  18701. get: function () {
  18702. return this._audioEnabled;
  18703. },
  18704. set: function (value) {
  18705. this._audioEnabled = value;
  18706. if (BABYLON.AudioEngine) {
  18707. if (this._audioEnabled) {
  18708. this._enableAudio();
  18709. }
  18710. else {
  18711. this._disableAudio();
  18712. }
  18713. }
  18714. },
  18715. enumerable: true,
  18716. configurable: true
  18717. });
  18718. Scene.prototype._disableAudio = function () {
  18719. var i;
  18720. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18721. this.mainSoundTrack.soundCollection[i].pause();
  18722. }
  18723. for (i = 0; i < this.soundTracks.length; i++) {
  18724. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18725. this.soundTracks[i].soundCollection[j].pause();
  18726. }
  18727. }
  18728. };
  18729. Scene.prototype._enableAudio = function () {
  18730. var i;
  18731. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18732. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18733. this.mainSoundTrack.soundCollection[i].play();
  18734. }
  18735. }
  18736. for (i = 0; i < this.soundTracks.length; i++) {
  18737. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18738. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18739. this.soundTracks[i].soundCollection[j].play();
  18740. }
  18741. }
  18742. }
  18743. };
  18744. Object.defineProperty(Scene.prototype, "headphone", {
  18745. get: function () {
  18746. return this._headphone;
  18747. },
  18748. set: function (value) {
  18749. this._headphone = value;
  18750. if (BABYLON.AudioEngine) {
  18751. if (this._headphone) {
  18752. this._switchAudioModeForHeadphones();
  18753. }
  18754. else {
  18755. this._switchAudioModeForNormalSpeakers();
  18756. }
  18757. }
  18758. },
  18759. enumerable: true,
  18760. configurable: true
  18761. });
  18762. Scene.prototype._switchAudioModeForHeadphones = function () {
  18763. this.mainSoundTrack.switchPanningModelToHRTF();
  18764. for (var i = 0; i < this.soundTracks.length; i++) {
  18765. this.soundTracks[i].switchPanningModelToHRTF();
  18766. }
  18767. };
  18768. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18769. this.mainSoundTrack.switchPanningModelToEqualPower();
  18770. for (var i = 0; i < this.soundTracks.length; i++) {
  18771. this.soundTracks[i].switchPanningModelToEqualPower();
  18772. }
  18773. };
  18774. Scene.prototype.enableDepthRenderer = function () {
  18775. if (this._depthRenderer) {
  18776. return this._depthRenderer;
  18777. }
  18778. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18779. return this._depthRenderer;
  18780. };
  18781. Scene.prototype.disableDepthRenderer = function () {
  18782. if (!this._depthRenderer) {
  18783. return;
  18784. }
  18785. this._depthRenderer.dispose();
  18786. this._depthRenderer = null;
  18787. };
  18788. Scene.prototype.freezeMaterials = function () {
  18789. for (var i = 0; i < this.materials.length; i++) {
  18790. this.materials[i].freeze();
  18791. }
  18792. };
  18793. Scene.prototype.unfreezeMaterials = function () {
  18794. for (var i = 0; i < this.materials.length; i++) {
  18795. this.materials[i].unfreeze();
  18796. }
  18797. };
  18798. Scene.prototype.dispose = function () {
  18799. this.beforeRender = null;
  18800. this.afterRender = null;
  18801. this.skeletons = [];
  18802. this._boundingBoxRenderer.dispose();
  18803. if (this._depthRenderer) {
  18804. this._depthRenderer.dispose();
  18805. }
  18806. // Debug layer
  18807. if (this._debugLayer) {
  18808. this._debugLayer.hide();
  18809. }
  18810. // Events
  18811. this.onDisposeObservable.notifyObservers(this);
  18812. this.onDisposeObservable.clear();
  18813. this.onBeforeRenderObservable.clear();
  18814. this.onAfterRenderObservable.clear();
  18815. this.detachControl();
  18816. // Release sounds & sounds tracks
  18817. if (BABYLON.AudioEngine) {
  18818. this.disposeSounds();
  18819. }
  18820. // Detach cameras
  18821. var canvas = this._engine.getRenderingCanvas();
  18822. var index;
  18823. for (index = 0; index < this.cameras.length; index++) {
  18824. this.cameras[index].detachControl(canvas);
  18825. }
  18826. // Release lights
  18827. while (this.lights.length) {
  18828. this.lights[0].dispose();
  18829. }
  18830. // Release meshes
  18831. while (this.meshes.length) {
  18832. this.meshes[0].dispose(true);
  18833. }
  18834. // Release cameras
  18835. while (this.cameras.length) {
  18836. this.cameras[0].dispose();
  18837. }
  18838. // Release materials
  18839. while (this.materials.length) {
  18840. this.materials[0].dispose();
  18841. }
  18842. // Release particles
  18843. while (this.particleSystems.length) {
  18844. this.particleSystems[0].dispose();
  18845. }
  18846. // Release sprites
  18847. while (this.spriteManagers.length) {
  18848. this.spriteManagers[0].dispose();
  18849. }
  18850. // Release layers
  18851. while (this.layers.length) {
  18852. this.layers[0].dispose();
  18853. }
  18854. while (this.highlightLayers.length) {
  18855. this.highlightLayers[0].dispose();
  18856. }
  18857. // Release textures
  18858. while (this.textures.length) {
  18859. this.textures[0].dispose();
  18860. }
  18861. // Post-processes
  18862. this.postProcessManager.dispose();
  18863. // Physics
  18864. if (this._physicsEngine) {
  18865. this.disablePhysicsEngine();
  18866. }
  18867. // Remove from engine
  18868. index = this._engine.scenes.indexOf(this);
  18869. if (index > -1) {
  18870. this._engine.scenes.splice(index, 1);
  18871. }
  18872. this._engine.wipeCaches();
  18873. };
  18874. // Release sounds & sounds tracks
  18875. Scene.prototype.disposeSounds = function () {
  18876. this.mainSoundTrack.dispose();
  18877. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18878. this.soundTracks[scIndex].dispose();
  18879. }
  18880. };
  18881. // Octrees
  18882. Scene.prototype.getWorldExtends = function () {
  18883. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18884. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18885. for (var index = 0; index < this.meshes.length; index++) {
  18886. var mesh = this.meshes[index];
  18887. mesh.computeWorldMatrix(true);
  18888. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18889. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18890. BABYLON.Tools.CheckExtends(minBox, min, max);
  18891. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18892. }
  18893. return {
  18894. min: min,
  18895. max: max
  18896. };
  18897. };
  18898. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18899. if (maxCapacity === void 0) { maxCapacity = 64; }
  18900. if (maxDepth === void 0) { maxDepth = 2; }
  18901. if (!this._selectionOctree) {
  18902. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18903. }
  18904. var worldExtends = this.getWorldExtends();
  18905. // Update octree
  18906. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18907. return this._selectionOctree;
  18908. };
  18909. // Picking
  18910. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18911. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18912. var engine = this._engine;
  18913. if (!camera) {
  18914. if (!this.activeCamera)
  18915. throw new Error("Active camera not set");
  18916. camera = this.activeCamera;
  18917. }
  18918. var cameraViewport = camera.viewport;
  18919. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18920. // Moving coordinates to local viewport world
  18921. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18922. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18923. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18924. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18925. };
  18926. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18927. var engine = this._engine;
  18928. if (!camera) {
  18929. if (!this.activeCamera)
  18930. throw new Error("Active camera not set");
  18931. camera = this.activeCamera;
  18932. }
  18933. var cameraViewport = camera.viewport;
  18934. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18935. var identity = BABYLON.Matrix.Identity();
  18936. // Moving coordinates to local viewport world
  18937. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18938. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18939. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18940. };
  18941. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18942. var pickingInfo = null;
  18943. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18944. var mesh = this.meshes[meshIndex];
  18945. if (predicate) {
  18946. if (!predicate(mesh)) {
  18947. continue;
  18948. }
  18949. }
  18950. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18951. continue;
  18952. }
  18953. var world = mesh.getWorldMatrix();
  18954. var ray = rayFunction(world);
  18955. var result = mesh.intersects(ray, fastCheck);
  18956. if (!result || !result.hit)
  18957. continue;
  18958. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18959. continue;
  18960. pickingInfo = result;
  18961. if (fastCheck) {
  18962. break;
  18963. }
  18964. }
  18965. return pickingInfo || new BABYLON.PickingInfo();
  18966. };
  18967. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18968. var pickingInfos = new Array();
  18969. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18970. var mesh = this.meshes[meshIndex];
  18971. if (predicate) {
  18972. if (!predicate(mesh)) {
  18973. continue;
  18974. }
  18975. }
  18976. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18977. continue;
  18978. }
  18979. var world = mesh.getWorldMatrix();
  18980. var ray = rayFunction(world);
  18981. var result = mesh.intersects(ray, false);
  18982. if (!result || !result.hit)
  18983. continue;
  18984. pickingInfos.push(result);
  18985. }
  18986. return pickingInfos;
  18987. };
  18988. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18989. var pickingInfo = null;
  18990. camera = camera || this.activeCamera;
  18991. if (this.spriteManagers.length > 0) {
  18992. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18993. var spriteManager = this.spriteManagers[spriteIndex];
  18994. if (!spriteManager.isPickable) {
  18995. continue;
  18996. }
  18997. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18998. if (!result || !result.hit)
  18999. continue;
  19000. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19001. continue;
  19002. pickingInfo = result;
  19003. if (fastCheck) {
  19004. break;
  19005. }
  19006. }
  19007. }
  19008. return pickingInfo || new BABYLON.PickingInfo();
  19009. };
  19010. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  19011. /// <param name="x">X position on screen</param>
  19012. /// <param name="y">Y position on screen</param>
  19013. /// <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>
  19014. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  19015. /// <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>
  19016. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19017. var _this = this;
  19018. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19019. };
  19020. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  19021. /// <param name="x">X position on screen</param>
  19022. /// <param name="y">Y position on screen</param>
  19023. /// <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>
  19024. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  19025. /// <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>
  19026. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19027. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19028. };
  19029. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19030. var _this = this;
  19031. return this._internalPick(function (world) {
  19032. if (!_this._pickWithRayInverseMatrix) {
  19033. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19034. }
  19035. world.invertToRef(_this._pickWithRayInverseMatrix);
  19036. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19037. }, predicate, fastCheck);
  19038. };
  19039. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  19040. /// <param name="x">X position on screen</param>
  19041. /// <param name="y">Y position on screen</param>
  19042. /// <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>
  19043. /// <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>
  19044. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19045. var _this = this;
  19046. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19047. };
  19048. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  19049. /// <param name="ray">Ray to use</param>
  19050. /// <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>
  19051. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19052. var _this = this;
  19053. return this._internalMultiPick(function (world) {
  19054. if (!_this._pickWithRayInverseMatrix) {
  19055. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19056. }
  19057. world.invertToRef(_this._pickWithRayInverseMatrix);
  19058. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19059. }, predicate);
  19060. };
  19061. Scene.prototype.setPointerOverMesh = function (mesh) {
  19062. if (this._pointerOverMesh === mesh) {
  19063. return;
  19064. }
  19065. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19066. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19067. }
  19068. this._pointerOverMesh = mesh;
  19069. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19070. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19071. }
  19072. };
  19073. Scene.prototype.getPointerOverMesh = function () {
  19074. return this._pointerOverMesh;
  19075. };
  19076. Scene.prototype.setPointerOverSprite = function (sprite) {
  19077. if (this._pointerOverSprite === sprite) {
  19078. return;
  19079. }
  19080. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19081. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19082. }
  19083. this._pointerOverSprite = sprite;
  19084. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19085. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19086. }
  19087. };
  19088. Scene.prototype.getPointerOverSprite = function () {
  19089. return this._pointerOverSprite;
  19090. };
  19091. // Physics
  19092. Scene.prototype.getPhysicsEngine = function () {
  19093. return this._physicsEngine;
  19094. };
  19095. /**
  19096. * Enables physics to the current scene
  19097. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19098. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19099. * @return {boolean} was the physics engine initialized
  19100. */
  19101. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19102. if (this._physicsEngine) {
  19103. return true;
  19104. }
  19105. try {
  19106. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19107. return true;
  19108. }
  19109. catch (e) {
  19110. BABYLON.Tools.Error(e.message);
  19111. return false;
  19112. }
  19113. };
  19114. Scene.prototype.disablePhysicsEngine = function () {
  19115. if (!this._physicsEngine) {
  19116. return;
  19117. }
  19118. this._physicsEngine.dispose();
  19119. this._physicsEngine = undefined;
  19120. };
  19121. Scene.prototype.isPhysicsEnabled = function () {
  19122. return this._physicsEngine !== undefined;
  19123. };
  19124. /**
  19125. *
  19126. * Sets the gravity of the physics engine (and NOT of the scene)
  19127. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  19128. */
  19129. Scene.prototype.setGravity = function (gravity) {
  19130. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  19131. if (!this._physicsEngine) {
  19132. return;
  19133. }
  19134. this._physicsEngine.setGravity(gravity);
  19135. };
  19136. /**
  19137. * Legacy support, using the new API
  19138. * @Deprecated
  19139. */
  19140. Scene.prototype.createCompoundImpostor = function (parts, options) {
  19141. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  19142. if (parts.parts) {
  19143. options = parts;
  19144. parts = parts.parts;
  19145. }
  19146. var mainMesh = parts[0].mesh;
  19147. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  19148. for (var index = 1; index < parts.length; index++) {
  19149. var mesh = parts[index].mesh;
  19150. if (mesh.parent !== mainMesh) {
  19151. mesh.position = mesh.position.subtract(mainMesh.position);
  19152. mesh.parent = mainMesh;
  19153. }
  19154. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  19155. }
  19156. mainMesh.physicsImpostor.forceUpdate();
  19157. };
  19158. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19159. var mesh = compound.parts[0].mesh;
  19160. mesh.physicsImpostor.dispose();
  19161. mesh.physicsImpostor = null;
  19162. };
  19163. // Misc.
  19164. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  19165. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19166. // Light
  19167. if (this.lights.length === 0) {
  19168. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19169. }
  19170. // Camera
  19171. if (!this.activeCamera) {
  19172. // Compute position
  19173. var worldExtends = this.getWorldExtends();
  19174. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  19175. var camera;
  19176. if (createArcRotateCamera) {
  19177. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  19178. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  19179. camera.setTarget(worldCenter);
  19180. }
  19181. else {
  19182. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  19183. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  19184. camera.setTarget(worldCenter);
  19185. }
  19186. this.activeCamera = camera;
  19187. }
  19188. };
  19189. // Tags
  19190. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19191. if (tagsQuery === undefined) {
  19192. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19193. return list;
  19194. }
  19195. var listByTags = [];
  19196. forEach = forEach || (function (item) { return; });
  19197. for (var i in list) {
  19198. var item = list[i];
  19199. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19200. listByTags.push(item);
  19201. forEach(item);
  19202. }
  19203. }
  19204. return listByTags;
  19205. };
  19206. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19207. return this._getByTags(this.meshes, tagsQuery, forEach);
  19208. };
  19209. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19210. return this._getByTags(this.cameras, tagsQuery, forEach);
  19211. };
  19212. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19213. return this._getByTags(this.lights, tagsQuery, forEach);
  19214. };
  19215. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19216. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19217. };
  19218. /**
  19219. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19220. * This allowed control for front to back rendering or reversly depending of the special needs.
  19221. *
  19222. * @param renderingGroupId The rendering group id corresponding to its index
  19223. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19224. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19225. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19226. */
  19227. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19228. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19229. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19230. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19231. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19232. };
  19233. /**
  19234. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19235. *
  19236. * @param renderingGroupId The rendering group id corresponding to its index
  19237. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19238. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19239. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19240. */
  19241. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19242. if (depth === void 0) { depth = true; }
  19243. if (stencil === void 0) { stencil = true; }
  19244. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19245. };
  19246. return Scene;
  19247. }());
  19248. // Statics
  19249. Scene._FOGMODE_NONE = 0;
  19250. Scene._FOGMODE_EXP = 1;
  19251. Scene._FOGMODE_EXP2 = 2;
  19252. Scene._FOGMODE_LINEAR = 3;
  19253. Scene.MinDeltaTime = 1.0;
  19254. Scene.MaxDeltaTime = 1000.0;
  19255. BABYLON.Scene = Scene;
  19256. })(BABYLON || (BABYLON = {}));
  19257. //# sourceMappingURL=babylon.scene.js.map
  19258. var BABYLON;
  19259. (function (BABYLON) {
  19260. var Buffer = (function () {
  19261. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19262. if (engine instanceof BABYLON.Mesh) {
  19263. this._engine = engine.getScene().getEngine();
  19264. }
  19265. else {
  19266. this._engine = engine;
  19267. }
  19268. this._updatable = updatable;
  19269. this._data = data;
  19270. this._strideSize = stride;
  19271. if (!postponeInternalCreation) {
  19272. this.create();
  19273. }
  19274. this._instanced = instanced;
  19275. }
  19276. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19277. // a lot of these parameters are ignored as they are overriden by the buffer
  19278. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19279. };
  19280. // Properties
  19281. Buffer.prototype.isUpdatable = function () {
  19282. return this._updatable;
  19283. };
  19284. Buffer.prototype.getData = function () {
  19285. return this._data;
  19286. };
  19287. Buffer.prototype.getBuffer = function () {
  19288. return this._buffer;
  19289. };
  19290. Buffer.prototype.getStrideSize = function () {
  19291. return this._strideSize;
  19292. };
  19293. Buffer.prototype.getIsInstanced = function () {
  19294. return this._instanced;
  19295. };
  19296. // Methods
  19297. Buffer.prototype.create = function (data) {
  19298. if (!data && this._buffer) {
  19299. return; // nothing to do
  19300. }
  19301. data = data || this._data;
  19302. if (!this._buffer) {
  19303. if (this._updatable) {
  19304. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19305. this._data = data;
  19306. }
  19307. else {
  19308. this._buffer = this._engine.createVertexBuffer(data);
  19309. }
  19310. }
  19311. else if (this._updatable) {
  19312. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19313. this._data = data;
  19314. }
  19315. };
  19316. Buffer.prototype.update = function (data) {
  19317. this.create(data);
  19318. };
  19319. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19320. if (!this._buffer) {
  19321. return;
  19322. }
  19323. if (this._updatable) {
  19324. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19325. this._data = null;
  19326. }
  19327. };
  19328. Buffer.prototype.dispose = function () {
  19329. if (!this._buffer) {
  19330. return;
  19331. }
  19332. if (this._engine._releaseBuffer(this._buffer)) {
  19333. this._buffer = null;
  19334. }
  19335. };
  19336. return Buffer;
  19337. }());
  19338. BABYLON.Buffer = Buffer;
  19339. })(BABYLON || (BABYLON = {}));
  19340. //# sourceMappingURL=babylon.buffer.js.map
  19341. var BABYLON;
  19342. (function (BABYLON) {
  19343. var VertexBuffer = (function () {
  19344. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19345. if (!stride) {
  19346. // Deduce stride from kind
  19347. switch (kind) {
  19348. case VertexBuffer.PositionKind:
  19349. stride = 3;
  19350. break;
  19351. case VertexBuffer.NormalKind:
  19352. stride = 3;
  19353. break;
  19354. case VertexBuffer.UVKind:
  19355. case VertexBuffer.UV2Kind:
  19356. case VertexBuffer.UV3Kind:
  19357. case VertexBuffer.UV4Kind:
  19358. case VertexBuffer.UV5Kind:
  19359. case VertexBuffer.UV6Kind:
  19360. stride = 2;
  19361. break;
  19362. case VertexBuffer.ColorKind:
  19363. stride = 4;
  19364. break;
  19365. case VertexBuffer.MatricesIndicesKind:
  19366. case VertexBuffer.MatricesIndicesExtraKind:
  19367. stride = 4;
  19368. break;
  19369. case VertexBuffer.MatricesWeightsKind:
  19370. case VertexBuffer.MatricesWeightsExtraKind:
  19371. stride = 4;
  19372. break;
  19373. }
  19374. }
  19375. if (data instanceof BABYLON.Buffer) {
  19376. if (!stride) {
  19377. stride = data.getStrideSize();
  19378. }
  19379. this._buffer = data;
  19380. this._ownsBuffer = false;
  19381. }
  19382. else {
  19383. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19384. this._ownsBuffer = true;
  19385. }
  19386. this._stride = stride;
  19387. this._offset = offset ? offset : 0;
  19388. this._size = size ? size : stride;
  19389. this._kind = kind;
  19390. }
  19391. VertexBuffer.prototype.getKind = function () {
  19392. return this._kind;
  19393. };
  19394. // Properties
  19395. VertexBuffer.prototype.isUpdatable = function () {
  19396. return this._buffer.isUpdatable();
  19397. };
  19398. VertexBuffer.prototype.getData = function () {
  19399. return this._buffer.getData();
  19400. };
  19401. VertexBuffer.prototype.getBuffer = function () {
  19402. return this._buffer.getBuffer();
  19403. };
  19404. VertexBuffer.prototype.getStrideSize = function () {
  19405. return this._stride;
  19406. };
  19407. VertexBuffer.prototype.getOffset = function () {
  19408. return this._offset;
  19409. };
  19410. VertexBuffer.prototype.getSize = function () {
  19411. return this._size;
  19412. };
  19413. VertexBuffer.prototype.getIsInstanced = function () {
  19414. return this._buffer.getIsInstanced();
  19415. };
  19416. // Methods
  19417. VertexBuffer.prototype.create = function (data) {
  19418. return this._buffer.create(data);
  19419. };
  19420. VertexBuffer.prototype.update = function (data) {
  19421. return this._buffer.update(data);
  19422. };
  19423. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19424. return this._buffer.updateDirectly(data, offset);
  19425. };
  19426. VertexBuffer.prototype.dispose = function () {
  19427. if (this._ownsBuffer) {
  19428. this._buffer.dispose();
  19429. }
  19430. };
  19431. Object.defineProperty(VertexBuffer, "PositionKind", {
  19432. get: function () {
  19433. return VertexBuffer._PositionKind;
  19434. },
  19435. enumerable: true,
  19436. configurable: true
  19437. });
  19438. Object.defineProperty(VertexBuffer, "NormalKind", {
  19439. get: function () {
  19440. return VertexBuffer._NormalKind;
  19441. },
  19442. enumerable: true,
  19443. configurable: true
  19444. });
  19445. Object.defineProperty(VertexBuffer, "UVKind", {
  19446. get: function () {
  19447. return VertexBuffer._UVKind;
  19448. },
  19449. enumerable: true,
  19450. configurable: true
  19451. });
  19452. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19453. get: function () {
  19454. return VertexBuffer._UV2Kind;
  19455. },
  19456. enumerable: true,
  19457. configurable: true
  19458. });
  19459. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19460. get: function () {
  19461. return VertexBuffer._UV3Kind;
  19462. },
  19463. enumerable: true,
  19464. configurable: true
  19465. });
  19466. Object.defineProperty(VertexBuffer, "UV4Kind", {
  19467. get: function () {
  19468. return VertexBuffer._UV4Kind;
  19469. },
  19470. enumerable: true,
  19471. configurable: true
  19472. });
  19473. Object.defineProperty(VertexBuffer, "UV5Kind", {
  19474. get: function () {
  19475. return VertexBuffer._UV5Kind;
  19476. },
  19477. enumerable: true,
  19478. configurable: true
  19479. });
  19480. Object.defineProperty(VertexBuffer, "UV6Kind", {
  19481. get: function () {
  19482. return VertexBuffer._UV6Kind;
  19483. },
  19484. enumerable: true,
  19485. configurable: true
  19486. });
  19487. Object.defineProperty(VertexBuffer, "ColorKind", {
  19488. get: function () {
  19489. return VertexBuffer._ColorKind;
  19490. },
  19491. enumerable: true,
  19492. configurable: true
  19493. });
  19494. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  19495. get: function () {
  19496. return VertexBuffer._MatricesIndicesKind;
  19497. },
  19498. enumerable: true,
  19499. configurable: true
  19500. });
  19501. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  19502. get: function () {
  19503. return VertexBuffer._MatricesWeightsKind;
  19504. },
  19505. enumerable: true,
  19506. configurable: true
  19507. });
  19508. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  19509. get: function () {
  19510. return VertexBuffer._MatricesIndicesExtraKind;
  19511. },
  19512. enumerable: true,
  19513. configurable: true
  19514. });
  19515. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  19516. get: function () {
  19517. return VertexBuffer._MatricesWeightsExtraKind;
  19518. },
  19519. enumerable: true,
  19520. configurable: true
  19521. });
  19522. return VertexBuffer;
  19523. }());
  19524. // Enums
  19525. VertexBuffer._PositionKind = "position";
  19526. VertexBuffer._NormalKind = "normal";
  19527. VertexBuffer._UVKind = "uv";
  19528. VertexBuffer._UV2Kind = "uv2";
  19529. VertexBuffer._UV3Kind = "uv3";
  19530. VertexBuffer._UV4Kind = "uv4";
  19531. VertexBuffer._UV5Kind = "uv5";
  19532. VertexBuffer._UV6Kind = "uv6";
  19533. VertexBuffer._ColorKind = "color";
  19534. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  19535. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  19536. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  19537. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  19538. BABYLON.VertexBuffer = VertexBuffer;
  19539. })(BABYLON || (BABYLON = {}));
  19540. //# sourceMappingURL=babylon.vertexBuffer.js.map
  19541. var BABYLON;
  19542. (function (BABYLON) {
  19543. /**
  19544. * Creates an instance based on a source mesh.
  19545. */
  19546. var InstancedMesh = (function (_super) {
  19547. __extends(InstancedMesh, _super);
  19548. function InstancedMesh(name, source) {
  19549. var _this = _super.call(this, name, source.getScene()) || this;
  19550. source.instances.push(_this);
  19551. _this._sourceMesh = source;
  19552. _this.position.copyFrom(source.position);
  19553. _this.rotation.copyFrom(source.rotation);
  19554. _this.scaling.copyFrom(source.scaling);
  19555. if (source.rotationQuaternion) {
  19556. _this.rotationQuaternion = source.rotationQuaternion.clone();
  19557. }
  19558. _this.infiniteDistance = source.infiniteDistance;
  19559. _this.setPivotMatrix(source.getPivotMatrix());
  19560. _this.refreshBoundingInfo();
  19561. _this._syncSubMeshes();
  19562. return _this;
  19563. }
  19564. InstancedMesh.prototype.getClassName = function () {
  19565. return "InstancedMesh";
  19566. };
  19567. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  19568. // Methods
  19569. get: function () {
  19570. return this._sourceMesh.receiveShadows;
  19571. },
  19572. enumerable: true,
  19573. configurable: true
  19574. });
  19575. Object.defineProperty(InstancedMesh.prototype, "material", {
  19576. get: function () {
  19577. return this._sourceMesh.material;
  19578. },
  19579. enumerable: true,
  19580. configurable: true
  19581. });
  19582. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  19583. get: function () {
  19584. return this._sourceMesh.visibility;
  19585. },
  19586. enumerable: true,
  19587. configurable: true
  19588. });
  19589. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  19590. get: function () {
  19591. return this._sourceMesh.skeleton;
  19592. },
  19593. enumerable: true,
  19594. configurable: true
  19595. });
  19596. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  19597. get: function () {
  19598. return this._sourceMesh.renderingGroupId;
  19599. },
  19600. enumerable: true,
  19601. configurable: true
  19602. });
  19603. InstancedMesh.prototype.getTotalVertices = function () {
  19604. return this._sourceMesh.getTotalVertices();
  19605. };
  19606. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  19607. get: function () {
  19608. return this._sourceMesh;
  19609. },
  19610. enumerable: true,
  19611. configurable: true
  19612. });
  19613. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19614. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  19615. };
  19616. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  19617. return this._sourceMesh.isVerticesDataPresent(kind);
  19618. };
  19619. InstancedMesh.prototype.getIndices = function () {
  19620. return this._sourceMesh.getIndices();
  19621. };
  19622. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  19623. get: function () {
  19624. return this._sourceMesh._positions;
  19625. },
  19626. enumerable: true,
  19627. configurable: true
  19628. });
  19629. InstancedMesh.prototype.refreshBoundingInfo = function () {
  19630. var meshBB = this._sourceMesh.getBoundingInfo();
  19631. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  19632. this._updateBoundingInfo();
  19633. };
  19634. InstancedMesh.prototype._preActivate = function () {
  19635. if (this._currentLOD) {
  19636. this._currentLOD._preActivate();
  19637. }
  19638. };
  19639. InstancedMesh.prototype._activate = function (renderId) {
  19640. if (this._currentLOD) {
  19641. this._currentLOD._registerInstanceForRenderId(this, renderId);
  19642. }
  19643. };
  19644. InstancedMesh.prototype.getLOD = function (camera) {
  19645. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  19646. if (this._currentLOD === this.sourceMesh) {
  19647. return this;
  19648. }
  19649. return this._currentLOD;
  19650. };
  19651. InstancedMesh.prototype._syncSubMeshes = function () {
  19652. this.releaseSubMeshes();
  19653. if (this._sourceMesh.subMeshes) {
  19654. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  19655. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  19656. }
  19657. }
  19658. };
  19659. InstancedMesh.prototype._generatePointsArray = function () {
  19660. return this._sourceMesh._generatePointsArray();
  19661. };
  19662. // Clone
  19663. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19664. var result = this._sourceMesh.createInstance(name);
  19665. // Deep copy
  19666. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  19667. // Bounding info
  19668. this.refreshBoundingInfo();
  19669. // Parent
  19670. if (newParent) {
  19671. result.parent = newParent;
  19672. }
  19673. if (!doNotCloneChildren) {
  19674. // Children
  19675. for (var index = 0; index < this.getScene().meshes.length; index++) {
  19676. var mesh = this.getScene().meshes[index];
  19677. if (mesh.parent === this) {
  19678. mesh.clone(mesh.name, result);
  19679. }
  19680. }
  19681. }
  19682. result.computeWorldMatrix(true);
  19683. return result;
  19684. };
  19685. // Dispoe
  19686. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  19687. // Remove from mesh
  19688. var index = this._sourceMesh.instances.indexOf(this);
  19689. this._sourceMesh.instances.splice(index, 1);
  19690. _super.prototype.dispose.call(this, doNotRecurse);
  19691. };
  19692. return InstancedMesh;
  19693. }(BABYLON.AbstractMesh));
  19694. BABYLON.InstancedMesh = InstancedMesh;
  19695. })(BABYLON || (BABYLON = {}));
  19696. //# sourceMappingURL=babylon.instancedMesh.js.map
  19697. var BABYLON;
  19698. (function (BABYLON) {
  19699. var _InstancesBatch = (function () {
  19700. function _InstancesBatch() {
  19701. this.mustReturn = false;
  19702. this.visibleInstances = new Array();
  19703. this.renderSelf = new Array();
  19704. }
  19705. return _InstancesBatch;
  19706. }());
  19707. BABYLON._InstancesBatch = _InstancesBatch;
  19708. var Mesh = (function (_super) {
  19709. __extends(Mesh, _super);
  19710. /**
  19711. * @constructor
  19712. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19713. * @param {Scene} scene The scene to add this mesh to.
  19714. * @param {Node} parent The parent of this mesh, if it has one
  19715. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19716. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19717. * When false, achieved by calling a clone(), also passing False.
  19718. * This will make creation of children, recursive.
  19719. */
  19720. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19721. if (parent === void 0) { parent = null; }
  19722. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19723. var _this = _super.call(this, name, scene) || this;
  19724. // Events
  19725. /**
  19726. * An event triggered before rendering the mesh
  19727. * @type {BABYLON.Observable}
  19728. */
  19729. _this.onBeforeRenderObservable = new BABYLON.Observable();
  19730. /**
  19731. * An event triggered after rendering the mesh
  19732. * @type {BABYLON.Observable}
  19733. */
  19734. _this.onAfterRenderObservable = new BABYLON.Observable();
  19735. /**
  19736. * An event triggered before drawing the mesh
  19737. * @type {BABYLON.Observable}
  19738. */
  19739. _this.onBeforeDrawObservable = new BABYLON.Observable();
  19740. // Members
  19741. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19742. _this.instances = new Array();
  19743. _this._LODLevels = new Array();
  19744. _this._visibleInstances = {};
  19745. _this._renderIdForInstances = new Array();
  19746. _this._batchCache = new _InstancesBatch();
  19747. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19748. _this._sideOrientation = Mesh._DEFAULTSIDE;
  19749. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19750. if (source) {
  19751. // Geometry
  19752. if (source._geometry) {
  19753. source._geometry.applyToMesh(_this);
  19754. }
  19755. // Deep copy
  19756. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent"], ["_poseMatrix"]);
  19757. // Parent
  19758. _this.parent = source.parent;
  19759. // Pivot
  19760. _this.setPivotMatrix(source.getPivotMatrix());
  19761. _this.id = name + "." + source.id;
  19762. // Material
  19763. _this.material = source.material;
  19764. var index;
  19765. if (!doNotCloneChildren) {
  19766. // Children
  19767. for (index = 0; index < scene.meshes.length; index++) {
  19768. var mesh = scene.meshes[index];
  19769. if (mesh.parent === source) {
  19770. // doNotCloneChildren is always going to be False
  19771. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  19772. }
  19773. }
  19774. }
  19775. // Physics clone
  19776. var physicsEngine = _this.getScene().getPhysicsEngine();
  19777. if (clonePhysicsImpostor && physicsEngine) {
  19778. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19779. if (impostor) {
  19780. _this.physicsImpostor = impostor.clone(_this);
  19781. }
  19782. }
  19783. // Particles
  19784. for (index = 0; index < scene.particleSystems.length; index++) {
  19785. var system = scene.particleSystems[index];
  19786. if (system.emitter === source) {
  19787. system.clone(system.name, _this);
  19788. }
  19789. }
  19790. _this.computeWorldMatrix(true);
  19791. }
  19792. // Parent
  19793. if (parent !== null) {
  19794. _this.parent = parent;
  19795. }
  19796. return _this;
  19797. }
  19798. Object.defineProperty(Mesh, "FRONTSIDE", {
  19799. /**
  19800. * Mesh side orientation : usually the external or front surface
  19801. */
  19802. get: function () {
  19803. return Mesh._FRONTSIDE;
  19804. },
  19805. enumerable: true,
  19806. configurable: true
  19807. });
  19808. Object.defineProperty(Mesh, "BACKSIDE", {
  19809. /**
  19810. * Mesh side orientation : usually the internal or back surface
  19811. */
  19812. get: function () {
  19813. return Mesh._BACKSIDE;
  19814. },
  19815. enumerable: true,
  19816. configurable: true
  19817. });
  19818. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19819. /**
  19820. * Mesh side orientation : both internal and external or front and back surfaces
  19821. */
  19822. get: function () {
  19823. return Mesh._DOUBLESIDE;
  19824. },
  19825. enumerable: true,
  19826. configurable: true
  19827. });
  19828. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19829. /**
  19830. * Mesh side orientation : by default, `FRONTSIDE`
  19831. */
  19832. get: function () {
  19833. return Mesh._DEFAULTSIDE;
  19834. },
  19835. enumerable: true,
  19836. configurable: true
  19837. });
  19838. Object.defineProperty(Mesh, "NO_CAP", {
  19839. /**
  19840. * Mesh cap setting : no cap
  19841. */
  19842. get: function () {
  19843. return Mesh._NO_CAP;
  19844. },
  19845. enumerable: true,
  19846. configurable: true
  19847. });
  19848. Object.defineProperty(Mesh, "CAP_START", {
  19849. /**
  19850. * Mesh cap setting : one cap at the beginning of the mesh
  19851. */
  19852. get: function () {
  19853. return Mesh._CAP_START;
  19854. },
  19855. enumerable: true,
  19856. configurable: true
  19857. });
  19858. Object.defineProperty(Mesh, "CAP_END", {
  19859. /**
  19860. * Mesh cap setting : one cap at the end of the mesh
  19861. */
  19862. get: function () {
  19863. return Mesh._CAP_END;
  19864. },
  19865. enumerable: true,
  19866. configurable: true
  19867. });
  19868. Object.defineProperty(Mesh, "CAP_ALL", {
  19869. /**
  19870. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19871. */
  19872. get: function () {
  19873. return Mesh._CAP_ALL;
  19874. },
  19875. enumerable: true,
  19876. configurable: true
  19877. });
  19878. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19879. set: function (callback) {
  19880. if (this._onBeforeDrawObserver) {
  19881. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19882. }
  19883. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19884. },
  19885. enumerable: true,
  19886. configurable: true
  19887. });
  19888. // Methods
  19889. Mesh.prototype.getClassName = function () {
  19890. return "Mesh";
  19891. };
  19892. /**
  19893. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19894. */
  19895. Mesh.prototype.toString = function (fullDetails) {
  19896. var ret = _super.prototype.toString.call(this, fullDetails);
  19897. ret += ", n vertices: " + this.getTotalVertices();
  19898. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19899. if (this.animations) {
  19900. for (var i = 0; i < this.animations.length; i++) {
  19901. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19902. }
  19903. }
  19904. if (fullDetails) {
  19905. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19906. }
  19907. return ret;
  19908. };
  19909. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19910. get: function () {
  19911. return this._LODLevels.length > 0;
  19912. },
  19913. enumerable: true,
  19914. configurable: true
  19915. });
  19916. Mesh.prototype._sortLODLevels = function () {
  19917. this._LODLevels.sort(function (a, b) {
  19918. if (a.distance < b.distance) {
  19919. return 1;
  19920. }
  19921. if (a.distance > b.distance) {
  19922. return -1;
  19923. }
  19924. return 0;
  19925. });
  19926. };
  19927. /**
  19928. * Add a mesh as LOD level triggered at the given distance.
  19929. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19930. * @param {number} distance The distance from the center of the object to show this level
  19931. * @param {Mesh} mesh The mesh to be added as LOD level
  19932. * @return {Mesh} This mesh (for chaining)
  19933. */
  19934. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19935. if (mesh && mesh._masterMesh) {
  19936. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19937. return this;
  19938. }
  19939. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19940. this._LODLevels.push(level);
  19941. if (mesh) {
  19942. mesh._masterMesh = this;
  19943. }
  19944. this._sortLODLevels();
  19945. return this;
  19946. };
  19947. /**
  19948. * Returns the LOD level mesh at the passed distance or null if not found.
  19949. * It is related to the method `addLODLevel(distance, mesh)`.
  19950. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19951. */
  19952. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19953. for (var index = 0; index < this._LODLevels.length; index++) {
  19954. var level = this._LODLevels[index];
  19955. if (level.distance === distance) {
  19956. return level.mesh;
  19957. }
  19958. }
  19959. return null;
  19960. };
  19961. /**
  19962. * Remove a mesh from the LOD array
  19963. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19964. * @param {Mesh} mesh The mesh to be removed.
  19965. * @return {Mesh} This mesh (for chaining)
  19966. */
  19967. Mesh.prototype.removeLODLevel = function (mesh) {
  19968. for (var index = 0; index < this._LODLevels.length; index++) {
  19969. if (this._LODLevels[index].mesh === mesh) {
  19970. this._LODLevels.splice(index, 1);
  19971. if (mesh) {
  19972. mesh._masterMesh = null;
  19973. }
  19974. }
  19975. }
  19976. this._sortLODLevels();
  19977. return this;
  19978. };
  19979. /**
  19980. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19981. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19982. */
  19983. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19984. if (!this._LODLevels || this._LODLevels.length === 0) {
  19985. return this;
  19986. }
  19987. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19988. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19989. if (this.onLODLevelSelection) {
  19990. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19991. }
  19992. return this;
  19993. }
  19994. for (var index = 0; index < this._LODLevels.length; index++) {
  19995. var level = this._LODLevels[index];
  19996. if (level.distance < distanceToCamera) {
  19997. if (level.mesh) {
  19998. level.mesh._preActivate();
  19999. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20000. }
  20001. if (this.onLODLevelSelection) {
  20002. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  20003. }
  20004. return level.mesh;
  20005. }
  20006. }
  20007. if (this.onLODLevelSelection) {
  20008. this.onLODLevelSelection(distanceToCamera, this, this);
  20009. }
  20010. return this;
  20011. };
  20012. Object.defineProperty(Mesh.prototype, "geometry", {
  20013. /**
  20014. * Returns the mesh internal Geometry object.
  20015. */
  20016. get: function () {
  20017. return this._geometry;
  20018. },
  20019. enumerable: true,
  20020. configurable: true
  20021. });
  20022. /**
  20023. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  20024. */
  20025. Mesh.prototype.getTotalVertices = function () {
  20026. if (!this._geometry) {
  20027. return 0;
  20028. }
  20029. return this._geometry.getTotalVertices();
  20030. };
  20031. /**
  20032. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  20033. * 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.
  20034. * Returns null if the mesh has no geometry or no vertex buffer.
  20035. * Possible `kind` values :
  20036. * - BABYLON.VertexBuffer.PositionKind
  20037. * - BABYLON.VertexBuffer.UVKind
  20038. * - BABYLON.VertexBuffer.UV2Kind
  20039. * - BABYLON.VertexBuffer.UV3Kind
  20040. * - BABYLON.VertexBuffer.UV4Kind
  20041. * - BABYLON.VertexBuffer.UV5Kind
  20042. * - BABYLON.VertexBuffer.UV6Kind
  20043. * - BABYLON.VertexBuffer.ColorKind
  20044. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20045. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20046. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20047. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20048. */
  20049. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  20050. if (!this._geometry) {
  20051. return null;
  20052. }
  20053. return this._geometry.getVerticesData(kind, copyWhenShared);
  20054. };
  20055. /**
  20056. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  20057. * Returns `undefined` if the mesh has no geometry.
  20058. * Possible `kind` values :
  20059. * - BABYLON.VertexBuffer.PositionKind
  20060. * - BABYLON.VertexBuffer.UVKind
  20061. * - BABYLON.VertexBuffer.UV2Kind
  20062. * - BABYLON.VertexBuffer.UV3Kind
  20063. * - BABYLON.VertexBuffer.UV4Kind
  20064. * - BABYLON.VertexBuffer.UV5Kind
  20065. * - BABYLON.VertexBuffer.UV6Kind
  20066. * - BABYLON.VertexBuffer.ColorKind
  20067. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20068. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20069. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20070. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20071. */
  20072. Mesh.prototype.getVertexBuffer = function (kind) {
  20073. if (!this._geometry) {
  20074. return undefined;
  20075. }
  20076. return this._geometry.getVertexBuffer(kind);
  20077. };
  20078. /**
  20079. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  20080. * Possible `kind` values :
  20081. * - BABYLON.VertexBuffer.PositionKind
  20082. * - BABYLON.VertexBuffer.UVKind
  20083. * - BABYLON.VertexBuffer.UV2Kind
  20084. * - BABYLON.VertexBuffer.UV3Kind
  20085. * - BABYLON.VertexBuffer.UV4Kind
  20086. * - BABYLON.VertexBuffer.UV5Kind
  20087. * - BABYLON.VertexBuffer.UV6Kind
  20088. * - BABYLON.VertexBuffer.ColorKind
  20089. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20090. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20091. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20092. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20093. */
  20094. Mesh.prototype.isVerticesDataPresent = function (kind) {
  20095. if (!this._geometry) {
  20096. if (this._delayInfo) {
  20097. return this._delayInfo.indexOf(kind) !== -1;
  20098. }
  20099. return false;
  20100. }
  20101. return this._geometry.isVerticesDataPresent(kind);
  20102. };
  20103. /**
  20104. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  20105. * Possible `kind` values :
  20106. * - BABYLON.VertexBuffer.PositionKind
  20107. * - BABYLON.VertexBuffer.UVKind
  20108. * - BABYLON.VertexBuffer.UV2Kind
  20109. * - BABYLON.VertexBuffer.UV3Kind
  20110. * - BABYLON.VertexBuffer.UV4Kind
  20111. * - BABYLON.VertexBuffer.UV5Kind
  20112. * - BABYLON.VertexBuffer.UV6Kind
  20113. * - BABYLON.VertexBuffer.ColorKind
  20114. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20115. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20116. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20117. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20118. */
  20119. Mesh.prototype.getVerticesDataKinds = function () {
  20120. if (!this._geometry) {
  20121. var result = [];
  20122. if (this._delayInfo) {
  20123. this._delayInfo.forEach(function (kind, index, array) {
  20124. result.push(kind);
  20125. });
  20126. }
  20127. return result;
  20128. }
  20129. return this._geometry.getVerticesDataKinds();
  20130. };
  20131. /**
  20132. * Returns a positive integer : the total number of indices in this mesh geometry.
  20133. * Returns zero if the mesh has no geometry.
  20134. */
  20135. Mesh.prototype.getTotalIndices = function () {
  20136. if (!this._geometry) {
  20137. return 0;
  20138. }
  20139. return this._geometry.getTotalIndices();
  20140. };
  20141. /**
  20142. * Returns an array of integers or a Int32Array populated with the mesh indices.
  20143. * 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.
  20144. * Returns an empty array if the mesh has no geometry.
  20145. */
  20146. Mesh.prototype.getIndices = function (copyWhenShared) {
  20147. if (!this._geometry) {
  20148. return [];
  20149. }
  20150. return this._geometry.getIndices(copyWhenShared);
  20151. };
  20152. Object.defineProperty(Mesh.prototype, "isBlocked", {
  20153. get: function () {
  20154. return this._masterMesh !== null && this._masterMesh !== undefined;
  20155. },
  20156. enumerable: true,
  20157. configurable: true
  20158. });
  20159. /**
  20160. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  20161. */
  20162. Mesh.prototype.isReady = function () {
  20163. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20164. return false;
  20165. }
  20166. return _super.prototype.isReady.call(this);
  20167. };
  20168. /**
  20169. * Boolean : true if the mesh has been disposed.
  20170. */
  20171. Mesh.prototype.isDisposed = function () {
  20172. return this._isDisposed;
  20173. };
  20174. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  20175. get: function () {
  20176. return this._sideOrientation;
  20177. },
  20178. /**
  20179. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  20180. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  20181. */
  20182. set: function (sideO) {
  20183. this._sideOrientation = sideO;
  20184. },
  20185. enumerable: true,
  20186. configurable: true
  20187. });
  20188. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  20189. /**
  20190. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  20191. * This property is pertinent only for updatable parametric shapes.
  20192. */
  20193. get: function () {
  20194. return this._areNormalsFrozen;
  20195. },
  20196. enumerable: true,
  20197. configurable: true
  20198. });
  20199. /**
  20200. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20201. * It has no effect at all on other shapes.
  20202. * It prevents the mesh normals from being recomputed on next `positions` array update.
  20203. */
  20204. Mesh.prototype.freezeNormals = function () {
  20205. this._areNormalsFrozen = true;
  20206. };
  20207. /**
  20208. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20209. * It has no effect at all on other shapes.
  20210. * It reactivates the mesh normals computation if it was previously frozen.
  20211. */
  20212. Mesh.prototype.unfreezeNormals = function () {
  20213. this._areNormalsFrozen = false;
  20214. };
  20215. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  20216. /**
  20217. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  20218. */
  20219. set: function (count) {
  20220. this._overridenInstanceCount = count;
  20221. },
  20222. enumerable: true,
  20223. configurable: true
  20224. });
  20225. // Methods
  20226. Mesh.prototype._preActivate = function () {
  20227. var sceneRenderId = this.getScene().getRenderId();
  20228. if (this._preActivateId === sceneRenderId) {
  20229. return;
  20230. }
  20231. this._preActivateId = sceneRenderId;
  20232. this._visibleInstances = null;
  20233. };
  20234. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20235. if (this._visibleInstances) {
  20236. this._visibleInstances.intermediateDefaultRenderId = renderId;
  20237. }
  20238. };
  20239. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  20240. if (!this._visibleInstances) {
  20241. this._visibleInstances = {};
  20242. this._visibleInstances.defaultRenderId = renderId;
  20243. this._visibleInstances.selfDefaultRenderId = this._renderId;
  20244. }
  20245. if (!this._visibleInstances[renderId]) {
  20246. this._visibleInstances[renderId] = new Array();
  20247. }
  20248. this._visibleInstances[renderId].push(instance);
  20249. };
  20250. /**
  20251. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  20252. * This means the mesh underlying bounding box and sphere are recomputed.
  20253. */
  20254. Mesh.prototype.refreshBoundingInfo = function () {
  20255. if (this._boundingInfo.isLocked) {
  20256. return;
  20257. }
  20258. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20259. if (data) {
  20260. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  20261. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20262. }
  20263. if (this.subMeshes) {
  20264. for (var index = 0; index < this.subMeshes.length; index++) {
  20265. this.subMeshes[index].refreshBoundingInfo();
  20266. }
  20267. }
  20268. this._updateBoundingInfo();
  20269. };
  20270. Mesh.prototype._createGlobalSubMesh = function () {
  20271. var totalVertices = this.getTotalVertices();
  20272. if (!totalVertices || !this.getIndices()) {
  20273. return null;
  20274. }
  20275. this.releaseSubMeshes();
  20276. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  20277. };
  20278. Mesh.prototype.subdivide = function (count) {
  20279. if (count < 1) {
  20280. return;
  20281. }
  20282. var totalIndices = this.getTotalIndices();
  20283. var subdivisionSize = (totalIndices / count) | 0;
  20284. var offset = 0;
  20285. // Ensure that subdivisionSize is a multiple of 3
  20286. while (subdivisionSize % 3 !== 0) {
  20287. subdivisionSize++;
  20288. }
  20289. this.releaseSubMeshes();
  20290. for (var index = 0; index < count; index++) {
  20291. if (offset >= totalIndices) {
  20292. break;
  20293. }
  20294. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20295. offset += subdivisionSize;
  20296. }
  20297. this.synchronizeInstances();
  20298. };
  20299. /**
  20300. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20301. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20302. * The `data` are either a numeric array either a Float32Array.
  20303. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20304. * 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).
  20305. * Note that a new underlying VertexBuffer object is created each call.
  20306. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20307. *
  20308. * Possible `kind` values :
  20309. * - BABYLON.VertexBuffer.PositionKind
  20310. * - BABYLON.VertexBuffer.UVKind
  20311. * - BABYLON.VertexBuffer.UV2Kind
  20312. * - BABYLON.VertexBuffer.UV3Kind
  20313. * - BABYLON.VertexBuffer.UV4Kind
  20314. * - BABYLON.VertexBuffer.UV5Kind
  20315. * - BABYLON.VertexBuffer.UV6Kind
  20316. * - BABYLON.VertexBuffer.ColorKind
  20317. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20318. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20319. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20320. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20321. */
  20322. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20323. if (!this._geometry) {
  20324. var vertexData = new BABYLON.VertexData();
  20325. vertexData.set(data, kind);
  20326. var scene = this.getScene();
  20327. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20328. }
  20329. else {
  20330. this._geometry.setVerticesData(kind, data, updatable, stride);
  20331. }
  20332. };
  20333. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20334. if (!this._geometry) {
  20335. var scene = this.getScene();
  20336. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20337. }
  20338. this._geometry.setVerticesBuffer(buffer);
  20339. };
  20340. /**
  20341. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20342. * If the mesh has no geometry, it is simply returned as it is.
  20343. * The `data` are either a numeric array either a Float32Array.
  20344. * No new underlying VertexBuffer object is created.
  20345. * 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.
  20346. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20347. *
  20348. * Possible `kind` values :
  20349. * - BABYLON.VertexBuffer.PositionKind
  20350. * - BABYLON.VertexBuffer.UVKind
  20351. * - BABYLON.VertexBuffer.UV2Kind
  20352. * - BABYLON.VertexBuffer.UV3Kind
  20353. * - BABYLON.VertexBuffer.UV4Kind
  20354. * - BABYLON.VertexBuffer.UV5Kind
  20355. * - BABYLON.VertexBuffer.UV6Kind
  20356. * - BABYLON.VertexBuffer.ColorKind
  20357. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20358. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20359. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20360. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20361. */
  20362. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20363. if (!this._geometry) {
  20364. return;
  20365. }
  20366. if (!makeItUnique) {
  20367. this._geometry.updateVerticesData(kind, data, updateExtends);
  20368. }
  20369. else {
  20370. this.makeGeometryUnique();
  20371. this.updateVerticesData(kind, data, updateExtends, false);
  20372. }
  20373. };
  20374. /**
  20375. * Deprecated since BabylonJS v2.3
  20376. */
  20377. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  20378. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  20379. if (!this._geometry) {
  20380. return;
  20381. }
  20382. if (!makeItUnique) {
  20383. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  20384. }
  20385. else {
  20386. this.makeGeometryUnique();
  20387. this.updateVerticesDataDirectly(kind, data, offset, false);
  20388. }
  20389. };
  20390. /**
  20391. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20392. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20393. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20394. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20395. */
  20396. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20397. if (computeNormals === void 0) { computeNormals = true; }
  20398. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20399. positionFunction(positions);
  20400. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20401. if (computeNormals) {
  20402. var indices = this.getIndices();
  20403. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20404. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20405. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20406. }
  20407. };
  20408. Mesh.prototype.makeGeometryUnique = function () {
  20409. if (!this._geometry) {
  20410. return;
  20411. }
  20412. var oldGeometry = this._geometry;
  20413. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20414. oldGeometry.releaseForMesh(this, true);
  20415. geometry.applyToMesh(this);
  20416. };
  20417. /**
  20418. * Sets the mesh indices.
  20419. * Expects an array populated with integers or a Int32Array.
  20420. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20421. * This method creates a new index buffer each call.
  20422. */
  20423. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20424. if (!this._geometry) {
  20425. var vertexData = new BABYLON.VertexData();
  20426. vertexData.indices = indices;
  20427. var scene = this.getScene();
  20428. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20429. }
  20430. else {
  20431. this._geometry.setIndices(indices, totalVertices);
  20432. }
  20433. };
  20434. /**
  20435. * Invert the geometry to move from a right handed system to a left handed one.
  20436. */
  20437. Mesh.prototype.toLeftHanded = function () {
  20438. if (!this._geometry) {
  20439. return;
  20440. }
  20441. this._geometry.toLeftHanded();
  20442. };
  20443. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20444. var engine = this.getScene().getEngine();
  20445. // Wireframe
  20446. var indexToBind;
  20447. if (this._unIndexed) {
  20448. indexToBind = null;
  20449. }
  20450. else {
  20451. switch (fillMode) {
  20452. case BABYLON.Material.PointFillMode:
  20453. indexToBind = null;
  20454. break;
  20455. case BABYLON.Material.WireFrameFillMode:
  20456. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20457. break;
  20458. default:
  20459. case BABYLON.Material.TriangleFillMode:
  20460. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20461. break;
  20462. }
  20463. }
  20464. // VBOs
  20465. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  20466. };
  20467. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20468. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20469. return;
  20470. }
  20471. this.onBeforeDrawObservable.notifyObservers(this);
  20472. var engine = this.getScene().getEngine();
  20473. // Draw order
  20474. switch (fillMode) {
  20475. case BABYLON.Material.PointFillMode:
  20476. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20477. break;
  20478. case BABYLON.Material.WireFrameFillMode:
  20479. if (this._unIndexed) {
  20480. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20481. }
  20482. else {
  20483. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20484. }
  20485. break;
  20486. default:
  20487. if (this._unIndexed) {
  20488. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20489. }
  20490. else {
  20491. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20492. }
  20493. }
  20494. };
  20495. /**
  20496. * Registers for this mesh a javascript function called just before the rendering process.
  20497. * This function is passed the current mesh and doesn't return anything.
  20498. */
  20499. Mesh.prototype.registerBeforeRender = function (func) {
  20500. this.onBeforeRenderObservable.add(func);
  20501. };
  20502. /**
  20503. * Disposes a previously registered javascript function called before the rendering.
  20504. * This function is passed the current mesh and doesn't return anything.
  20505. */
  20506. Mesh.prototype.unregisterBeforeRender = function (func) {
  20507. this.onBeforeRenderObservable.removeCallback(func);
  20508. };
  20509. /**
  20510. * Registers for this mesh a javascript function called just after the rendering is complete.
  20511. * This function is passed the current mesh and doesn't return anything.
  20512. */
  20513. Mesh.prototype.registerAfterRender = function (func) {
  20514. this.onAfterRenderObservable.add(func);
  20515. };
  20516. /**
  20517. * Disposes a previously registered javascript function called after the rendering.
  20518. * This function is passed the current mesh and doesn't return anything.
  20519. */
  20520. Mesh.prototype.unregisterAfterRender = function (func) {
  20521. this.onAfterRenderObservable.removeCallback(func);
  20522. };
  20523. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20524. var scene = this.getScene();
  20525. this._batchCache.mustReturn = false;
  20526. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20527. this._batchCache.visibleInstances[subMeshId] = null;
  20528. if (this._visibleInstances) {
  20529. var currentRenderId = scene.getRenderId();
  20530. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20531. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20532. var selfRenderId = this._renderId;
  20533. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20534. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20535. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20536. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20537. }
  20538. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20539. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20540. this._batchCache.mustReturn = true;
  20541. return this._batchCache;
  20542. }
  20543. if (currentRenderId !== selfRenderId) {
  20544. this._batchCache.renderSelf[subMeshId] = false;
  20545. }
  20546. }
  20547. this._renderIdForInstances[subMeshId] = currentRenderId;
  20548. }
  20549. return this._batchCache;
  20550. };
  20551. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20552. var visibleInstances = batch.visibleInstances[subMesh._id];
  20553. var matricesCount = visibleInstances.length + 1;
  20554. var bufferSize = matricesCount * 16 * 4;
  20555. var currentInstancesBufferSize = this._instancesBufferSize;
  20556. var instancesBuffer = this._instancesBuffer;
  20557. while (this._instancesBufferSize < bufferSize) {
  20558. this._instancesBufferSize *= 2;
  20559. }
  20560. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20561. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20562. }
  20563. var offset = 0;
  20564. var instancesCount = 0;
  20565. var world = this.getWorldMatrix();
  20566. if (batch.renderSelf[subMesh._id]) {
  20567. world.copyToArray(this._instancesData, offset);
  20568. offset += 16;
  20569. instancesCount++;
  20570. }
  20571. if (visibleInstances) {
  20572. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20573. var instance = visibleInstances[instanceIndex];
  20574. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20575. offset += 16;
  20576. instancesCount++;
  20577. }
  20578. }
  20579. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20580. if (instancesBuffer) {
  20581. instancesBuffer.dispose();
  20582. }
  20583. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20584. this._instancesBuffer = instancesBuffer;
  20585. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20586. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20587. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20588. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20589. }
  20590. else {
  20591. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20592. }
  20593. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  20594. this._draw(subMesh, fillMode, instancesCount);
  20595. engine.unbindInstanceAttributes();
  20596. };
  20597. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20598. var scene = this.getScene();
  20599. var engine = scene.getEngine();
  20600. if (hardwareInstancedRendering) {
  20601. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20602. }
  20603. else {
  20604. if (batch.renderSelf[subMesh._id]) {
  20605. // Draw
  20606. if (onBeforeDraw) {
  20607. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20608. }
  20609. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20610. }
  20611. if (batch.visibleInstances[subMesh._id]) {
  20612. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20613. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20614. // World
  20615. var world = instance.getWorldMatrix();
  20616. if (onBeforeDraw) {
  20617. onBeforeDraw(true, world, effectiveMaterial);
  20618. }
  20619. // Draw
  20620. this._draw(subMesh, fillMode);
  20621. }
  20622. }
  20623. }
  20624. };
  20625. /**
  20626. * Triggers the draw call for the mesh.
  20627. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20628. */
  20629. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20630. var scene = this.getScene();
  20631. // Managing instances
  20632. var batch = this._getInstancesRenderList(subMesh._id);
  20633. if (batch.mustReturn) {
  20634. return;
  20635. }
  20636. // Checking geometry state
  20637. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20638. return;
  20639. }
  20640. var callbackIndex;
  20641. this.onBeforeRenderObservable.notifyObservers(this);
  20642. var engine = scene.getEngine();
  20643. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20644. // Material
  20645. var effectiveMaterial = subMesh.getMaterial();
  20646. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20647. return;
  20648. }
  20649. // Outline - step 1
  20650. var savedDepthWrite = engine.getDepthWrite();
  20651. if (this.renderOutline) {
  20652. engine.setDepthWrite(false);
  20653. scene.getOutlineRenderer().render(subMesh, batch);
  20654. engine.setDepthWrite(savedDepthWrite);
  20655. }
  20656. effectiveMaterial._preBind();
  20657. var effect = effectiveMaterial.getEffect();
  20658. // Bind
  20659. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20660. this._bind(subMesh, effect, fillMode);
  20661. var world = this.getWorldMatrix();
  20662. effectiveMaterial.bind(world, this);
  20663. // Alpha mode
  20664. if (enableAlphaMode) {
  20665. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20666. }
  20667. // Draw
  20668. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20669. // Unbind
  20670. effectiveMaterial.unbind();
  20671. // Outline - step 2
  20672. if (this.renderOutline && savedDepthWrite) {
  20673. engine.setDepthWrite(true);
  20674. engine.setColorWrite(false);
  20675. scene.getOutlineRenderer().render(subMesh, batch);
  20676. engine.setColorWrite(true);
  20677. }
  20678. // Overlay
  20679. if (this.renderOverlay) {
  20680. var currentMode = engine.getAlphaMode();
  20681. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20682. scene.getOutlineRenderer().render(subMesh, batch, true);
  20683. engine.setAlphaMode(currentMode);
  20684. }
  20685. this.onAfterRenderObservable.notifyObservers(this);
  20686. };
  20687. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20688. if (isInstance) {
  20689. effectiveMaterial.bindOnlyWorldMatrix(world);
  20690. }
  20691. };
  20692. /**
  20693. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20694. */
  20695. Mesh.prototype.getEmittedParticleSystems = function () {
  20696. var results = new Array();
  20697. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20698. var particleSystem = this.getScene().particleSystems[index];
  20699. if (particleSystem.emitter === this) {
  20700. results.push(particleSystem);
  20701. }
  20702. }
  20703. return results;
  20704. };
  20705. /**
  20706. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20707. */
  20708. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20709. var results = new Array();
  20710. var descendants = this.getDescendants();
  20711. descendants.push(this);
  20712. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20713. var particleSystem = this.getScene().particleSystems[index];
  20714. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20715. results.push(particleSystem);
  20716. }
  20717. }
  20718. return results;
  20719. };
  20720. Mesh.prototype._checkDelayState = function () {
  20721. var scene = this.getScene();
  20722. if (this._geometry) {
  20723. this._geometry.load(scene);
  20724. }
  20725. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20726. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20727. this._queueLoad(this, scene);
  20728. }
  20729. };
  20730. Mesh.prototype._queueLoad = function (mesh, scene) {
  20731. var _this = this;
  20732. scene._addPendingData(mesh);
  20733. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20734. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20735. if (data instanceof ArrayBuffer) {
  20736. _this._delayLoadingFunction(data, _this);
  20737. }
  20738. else {
  20739. _this._delayLoadingFunction(JSON.parse(data), _this);
  20740. }
  20741. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20742. scene._removePendingData(_this);
  20743. }, function () { }, scene.database, getBinaryData);
  20744. };
  20745. /**
  20746. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20747. */
  20748. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20749. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20750. return false;
  20751. }
  20752. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20753. return false;
  20754. }
  20755. this._checkDelayState();
  20756. return true;
  20757. };
  20758. /**
  20759. * Sets the mesh material by the material or multiMaterial `id` property.
  20760. * The material `id` is a string identifying the material or the multiMaterial.
  20761. * This method returns nothing.
  20762. */
  20763. Mesh.prototype.setMaterialByID = function (id) {
  20764. var materials = this.getScene().materials;
  20765. var index;
  20766. for (index = 0; index < materials.length; index++) {
  20767. if (materials[index].id === id) {
  20768. this.material = materials[index];
  20769. return;
  20770. }
  20771. }
  20772. // Multi
  20773. var multiMaterials = this.getScene().multiMaterials;
  20774. for (index = 0; index < multiMaterials.length; index++) {
  20775. if (multiMaterials[index].id === id) {
  20776. this.material = multiMaterials[index];
  20777. return;
  20778. }
  20779. }
  20780. };
  20781. /**
  20782. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20783. */
  20784. Mesh.prototype.getAnimatables = function () {
  20785. var results = [];
  20786. if (this.material) {
  20787. results.push(this.material);
  20788. }
  20789. if (this.skeleton) {
  20790. results.push(this.skeleton);
  20791. }
  20792. return results;
  20793. };
  20794. /**
  20795. * Modifies the mesh geometry according to the passed transformation matrix.
  20796. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20797. * The mesh normals are modified accordingly the same transformation.
  20798. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20799. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20800. */
  20801. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20802. // Position
  20803. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20804. return;
  20805. }
  20806. var submeshes = this.subMeshes.splice(0);
  20807. this._resetPointsArrayCache();
  20808. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20809. var temp = [];
  20810. var index;
  20811. for (index = 0; index < data.length; index += 3) {
  20812. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20813. }
  20814. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20815. // Normals
  20816. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20817. return;
  20818. }
  20819. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20820. temp = [];
  20821. for (index = 0; index < data.length; index += 3) {
  20822. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20823. }
  20824. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20825. // flip faces?
  20826. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20827. this.flipFaces();
  20828. }
  20829. // Restore submeshes
  20830. this.releaseSubMeshes();
  20831. this.subMeshes = submeshes;
  20832. };
  20833. /**
  20834. * Modifies the mesh geometry according to its own current World Matrix.
  20835. * The mesh World Matrix is then reset.
  20836. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20837. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20838. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20839. */
  20840. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20841. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20842. this.scaling.copyFromFloats(1, 1, 1);
  20843. this.position.copyFromFloats(0, 0, 0);
  20844. this.rotation.copyFromFloats(0, 0, 0);
  20845. //only if quaternion is already set
  20846. if (this.rotationQuaternion) {
  20847. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20848. }
  20849. this._worldMatrix = BABYLON.Matrix.Identity();
  20850. };
  20851. // Cache
  20852. Mesh.prototype._resetPointsArrayCache = function () {
  20853. this._positions = null;
  20854. };
  20855. Mesh.prototype._generatePointsArray = function () {
  20856. if (this._positions)
  20857. return true;
  20858. this._positions = [];
  20859. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20860. if (!data) {
  20861. return false;
  20862. }
  20863. for (var index = 0; index < data.length; index += 3) {
  20864. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  20865. }
  20866. return true;
  20867. };
  20868. /**
  20869. * Returns a new Mesh object generated from the current mesh properties.
  20870. * This method must not get confused with createInstance().
  20871. * The parameter `name` is a string, the name given to the new mesh.
  20872. * The optional parameter `newParent` can be any Node object (default `null`).
  20873. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20874. * 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.
  20875. */
  20876. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20877. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20878. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20879. };
  20880. /**
  20881. * Disposes the mesh.
  20882. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20883. */
  20884. Mesh.prototype.dispose = function (doNotRecurse) {
  20885. if (this._geometry) {
  20886. this._geometry.releaseForMesh(this, true);
  20887. }
  20888. // Instances
  20889. if (this._instancesBuffer) {
  20890. this._instancesBuffer.dispose();
  20891. this._instancesBuffer = null;
  20892. }
  20893. while (this.instances.length) {
  20894. this.instances[0].dispose();
  20895. }
  20896. // Highlight layers.
  20897. var highlightLayers = this.getScene().highlightLayers;
  20898. for (var i = 0; i < highlightLayers.length; i++) {
  20899. var highlightLayer = highlightLayers[i];
  20900. if (highlightLayer) {
  20901. highlightLayer.removeMesh(this);
  20902. highlightLayer.removeExcludedMesh(this);
  20903. }
  20904. }
  20905. _super.prototype.dispose.call(this, doNotRecurse);
  20906. };
  20907. /**
  20908. * Modifies the mesh geometry according to a displacement map.
  20909. * 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.
  20910. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20911. * This method returns nothing.
  20912. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20913. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20914. * 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.
  20915. */
  20916. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  20917. var _this = this;
  20918. var scene = this.getScene();
  20919. var onload = function (img) {
  20920. // Getting height map data
  20921. var canvas = document.createElement("canvas");
  20922. var context = canvas.getContext("2d");
  20923. var heightMapWidth = img.width;
  20924. var heightMapHeight = img.height;
  20925. canvas.width = heightMapWidth;
  20926. canvas.height = heightMapHeight;
  20927. context.drawImage(img, 0, 0);
  20928. // Create VertexData from map data
  20929. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20930. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20931. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  20932. //execute success callback, if set
  20933. if (onSuccess) {
  20934. onSuccess(_this);
  20935. }
  20936. };
  20937. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20938. };
  20939. /**
  20940. * Modifies the mesh geometry according to a displacementMap buffer.
  20941. * 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.
  20942. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20943. * This method returns nothing.
  20944. * 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.
  20945. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20946. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20947. */
  20948. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  20949. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20950. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20951. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20952. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20953. return;
  20954. }
  20955. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20956. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20957. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20958. var position = BABYLON.Vector3.Zero();
  20959. var normal = BABYLON.Vector3.Zero();
  20960. var uv = BABYLON.Vector2.Zero();
  20961. for (var index = 0; index < positions.length; index += 3) {
  20962. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20963. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20964. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20965. // Compute height
  20966. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  20967. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  20968. var pos = (u + v * heightMapWidth) * 4;
  20969. var r = buffer[pos] / 255.0;
  20970. var g = buffer[pos + 1] / 255.0;
  20971. var b = buffer[pos + 2] / 255.0;
  20972. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20973. normal.normalize();
  20974. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20975. position = position.add(normal);
  20976. position.toArray(positions, index);
  20977. }
  20978. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20979. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20980. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20981. };
  20982. /**
  20983. * Modify the mesh to get a flat shading rendering.
  20984. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20985. * This method returns nothing.
  20986. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20987. */
  20988. Mesh.prototype.convertToFlatShadedMesh = function () {
  20989. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20990. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20991. var kinds = this.getVerticesDataKinds();
  20992. var vbs = [];
  20993. var data = [];
  20994. var newdata = [];
  20995. var updatableNormals = false;
  20996. var kindIndex;
  20997. var kind;
  20998. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20999. kind = kinds[kindIndex];
  21000. var vertexBuffer = this.getVertexBuffer(kind);
  21001. if (kind === BABYLON.VertexBuffer.NormalKind) {
  21002. updatableNormals = vertexBuffer.isUpdatable();
  21003. kinds.splice(kindIndex, 1);
  21004. kindIndex--;
  21005. continue;
  21006. }
  21007. vbs[kind] = vertexBuffer;
  21008. data[kind] = vbs[kind].getData();
  21009. newdata[kind] = [];
  21010. }
  21011. // Save previous submeshes
  21012. var previousSubmeshes = this.subMeshes.slice(0);
  21013. var indices = this.getIndices();
  21014. var totalIndices = this.getTotalIndices();
  21015. // Generating unique vertices per face
  21016. var index;
  21017. for (index = 0; index < totalIndices; index++) {
  21018. var vertexIndex = indices[index];
  21019. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21020. kind = kinds[kindIndex];
  21021. var stride = vbs[kind].getStrideSize();
  21022. for (var offset = 0; offset < stride; offset++) {
  21023. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21024. }
  21025. }
  21026. }
  21027. // Updating faces & normal
  21028. var normals = [];
  21029. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  21030. for (index = 0; index < totalIndices; index += 3) {
  21031. indices[index] = index;
  21032. indices[index + 1] = index + 1;
  21033. indices[index + 2] = index + 2;
  21034. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  21035. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  21036. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  21037. var p1p2 = p1.subtract(p2);
  21038. var p3p2 = p3.subtract(p2);
  21039. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21040. // Store same normals for every vertex
  21041. for (var localIndex = 0; localIndex < 3; localIndex++) {
  21042. normals.push(normal.x);
  21043. normals.push(normal.y);
  21044. normals.push(normal.z);
  21045. }
  21046. }
  21047. this.setIndices(indices);
  21048. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  21049. // Updating vertex buffers
  21050. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21051. kind = kinds[kindIndex];
  21052. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21053. }
  21054. // Updating submeshes
  21055. this.releaseSubMeshes();
  21056. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21057. var previousOne = previousSubmeshes[submeshIndex];
  21058. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21059. }
  21060. this.synchronizeInstances();
  21061. };
  21062. /**
  21063. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  21064. * In other words, more vertices, no more indices and a single bigger VBO.
  21065. * This method returns nothing.
  21066. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  21067. *
  21068. */
  21069. Mesh.prototype.convertToUnIndexedMesh = function () {
  21070. /// <summary>Remove indices by unfolding faces into buffers</summary>
  21071. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21072. var kinds = this.getVerticesDataKinds();
  21073. var vbs = [];
  21074. var data = [];
  21075. var newdata = [];
  21076. var updatableNormals = false;
  21077. var kindIndex;
  21078. var kind;
  21079. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21080. kind = kinds[kindIndex];
  21081. var vertexBuffer = this.getVertexBuffer(kind);
  21082. vbs[kind] = vertexBuffer;
  21083. data[kind] = vbs[kind].getData();
  21084. newdata[kind] = [];
  21085. }
  21086. // Save previous submeshes
  21087. var previousSubmeshes = this.subMeshes.slice(0);
  21088. var indices = this.getIndices();
  21089. var totalIndices = this.getTotalIndices();
  21090. // Generating unique vertices per face
  21091. var index;
  21092. for (index = 0; index < totalIndices; index++) {
  21093. var vertexIndex = indices[index];
  21094. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21095. kind = kinds[kindIndex];
  21096. var stride = vbs[kind].getStrideSize();
  21097. for (var offset = 0; offset < stride; offset++) {
  21098. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21099. }
  21100. }
  21101. }
  21102. // Updating indices
  21103. for (index = 0; index < totalIndices; index += 3) {
  21104. indices[index] = index;
  21105. indices[index + 1] = index + 1;
  21106. indices[index + 2] = index + 2;
  21107. }
  21108. this.setIndices(indices);
  21109. // Updating vertex buffers
  21110. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21111. kind = kinds[kindIndex];
  21112. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21113. }
  21114. // Updating submeshes
  21115. this.releaseSubMeshes();
  21116. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21117. var previousOne = previousSubmeshes[submeshIndex];
  21118. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21119. }
  21120. this._unIndexed = true;
  21121. this.synchronizeInstances();
  21122. };
  21123. /**
  21124. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  21125. * This method returns nothing.
  21126. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  21127. */
  21128. Mesh.prototype.flipFaces = function (flipNormals) {
  21129. if (flipNormals === void 0) { flipNormals = false; }
  21130. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  21131. var i;
  21132. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21133. for (i = 0; i < vertex_data.normals.length; i++) {
  21134. vertex_data.normals[i] *= -1;
  21135. }
  21136. }
  21137. var temp;
  21138. for (i = 0; i < vertex_data.indices.length; i += 3) {
  21139. // reassign indices
  21140. temp = vertex_data.indices[i + 1];
  21141. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  21142. vertex_data.indices[i + 2] = temp;
  21143. }
  21144. vertex_data.applyToMesh(this);
  21145. };
  21146. // Instances
  21147. /**
  21148. * Creates a new InstancedMesh object from the mesh model.
  21149. * An instance shares the same properties and the same material than its model.
  21150. * Only these properties of each instance can then be set individually :
  21151. * - position
  21152. * - rotation
  21153. * - rotationQuaternion
  21154. * - setPivotMatrix
  21155. * - scaling
  21156. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  21157. * Warning : this method is not supported for Line mesh and LineSystem
  21158. */
  21159. Mesh.prototype.createInstance = function (name) {
  21160. return new BABYLON.InstancedMesh(name, this);
  21161. };
  21162. /**
  21163. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  21164. * After this call, all the mesh instances have the same submeshes than the current mesh.
  21165. * This method returns nothing.
  21166. */
  21167. Mesh.prototype.synchronizeInstances = function () {
  21168. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  21169. var instance = this.instances[instanceIndex];
  21170. instance._syncSubMeshes();
  21171. }
  21172. };
  21173. /**
  21174. * Simplify the mesh according to the given array of settings.
  21175. * Function will return immediately and will simplify async. It returns nothing.
  21176. * @param settings a collection of simplification settings.
  21177. * @param parallelProcessing should all levels calculate parallel or one after the other.
  21178. * @param type the type of simplification to run.
  21179. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  21180. */
  21181. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  21182. if (parallelProcessing === void 0) { parallelProcessing = true; }
  21183. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  21184. this.getScene().simplificationQueue.addTask({
  21185. settings: settings,
  21186. parallelProcessing: parallelProcessing,
  21187. mesh: this,
  21188. simplificationType: simplificationType,
  21189. successCallback: successCallback
  21190. });
  21191. };
  21192. /**
  21193. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  21194. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  21195. * This should be used together with the simplification to avoid disappearing triangles.
  21196. * @param successCallback an optional success callback to be called after the optimization finished.
  21197. */
  21198. Mesh.prototype.optimizeIndices = function (successCallback) {
  21199. var _this = this;
  21200. var indices = this.getIndices();
  21201. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21202. var vectorPositions = [];
  21203. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  21204. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  21205. }
  21206. var dupes = [];
  21207. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21208. var realPos = vectorPositions.length - 1 - iteration;
  21209. var testedPosition = vectorPositions[realPos];
  21210. for (var j = 0; j < realPos; ++j) {
  21211. var againstPosition = vectorPositions[j];
  21212. if (testedPosition.equals(againstPosition)) {
  21213. dupes[realPos] = j;
  21214. break;
  21215. }
  21216. }
  21217. }, function () {
  21218. for (var i = 0; i < indices.length; ++i) {
  21219. indices[i] = dupes[indices[i]] || indices[i];
  21220. }
  21221. //indices are now reordered
  21222. var originalSubMeshes = _this.subMeshes.slice(0);
  21223. _this.setIndices(indices);
  21224. _this.subMeshes = originalSubMeshes;
  21225. if (successCallback) {
  21226. successCallback(_this);
  21227. }
  21228. });
  21229. };
  21230. // Statics
  21231. /**
  21232. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21233. * The parameter `parsedMesh` is the mesh to be copied.
  21234. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21235. */
  21236. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21237. var mesh = new Mesh(parsedMesh.name, scene);
  21238. mesh.id = parsedMesh.id;
  21239. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21240. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21241. if (parsedMesh.metadata !== undefined) {
  21242. mesh.metadata = parsedMesh.metadata;
  21243. }
  21244. if (parsedMesh.rotationQuaternion) {
  21245. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21246. }
  21247. else if (parsedMesh.rotation) {
  21248. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21249. }
  21250. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21251. if (parsedMesh.localMatrix) {
  21252. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21253. }
  21254. else if (parsedMesh.pivotMatrix) {
  21255. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21256. }
  21257. mesh.setEnabled(parsedMesh.isEnabled);
  21258. mesh.isVisible = parsedMesh.isVisible;
  21259. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21260. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21261. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21262. if (parsedMesh.applyFog !== undefined) {
  21263. mesh.applyFog = parsedMesh.applyFog;
  21264. }
  21265. if (parsedMesh.pickable !== undefined) {
  21266. mesh.isPickable = parsedMesh.pickable;
  21267. }
  21268. if (parsedMesh.alphaIndex !== undefined) {
  21269. mesh.alphaIndex = parsedMesh.alphaIndex;
  21270. }
  21271. mesh.receiveShadows = parsedMesh.receiveShadows;
  21272. mesh.billboardMode = parsedMesh.billboardMode;
  21273. if (parsedMesh.visibility !== undefined) {
  21274. mesh.visibility = parsedMesh.visibility;
  21275. }
  21276. mesh.checkCollisions = parsedMesh.checkCollisions;
  21277. if (parsedMesh.isBlocker !== undefined) {
  21278. mesh.isBlocker = parsedMesh.isBlocker;
  21279. }
  21280. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21281. // freezeWorldMatrix
  21282. if (parsedMesh.freezeWorldMatrix) {
  21283. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21284. }
  21285. // Parent
  21286. if (parsedMesh.parentId) {
  21287. mesh._waitingParentId = parsedMesh.parentId;
  21288. }
  21289. // Actions
  21290. if (parsedMesh.actions !== undefined) {
  21291. mesh._waitingActions = parsedMesh.actions;
  21292. }
  21293. // Overlay
  21294. if (parsedMesh.overlayAlpha !== undefined) {
  21295. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21296. }
  21297. if (parsedMesh.overlayColor !== undefined) {
  21298. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21299. }
  21300. if (parsedMesh.renderOverlay !== undefined) {
  21301. mesh.renderOverlay = parsedMesh.renderOverlay;
  21302. }
  21303. // Geometry
  21304. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21305. if (parsedMesh.delayLoadingFile) {
  21306. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21307. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21308. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21309. if (parsedMesh._binaryInfo) {
  21310. mesh._binaryInfo = parsedMesh._binaryInfo;
  21311. }
  21312. mesh._delayInfo = [];
  21313. if (parsedMesh.hasUVs) {
  21314. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21315. }
  21316. if (parsedMesh.hasUVs2) {
  21317. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21318. }
  21319. if (parsedMesh.hasUVs3) {
  21320. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21321. }
  21322. if (parsedMesh.hasUVs4) {
  21323. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21324. }
  21325. if (parsedMesh.hasUVs5) {
  21326. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21327. }
  21328. if (parsedMesh.hasUVs6) {
  21329. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21330. }
  21331. if (parsedMesh.hasColors) {
  21332. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21333. }
  21334. if (parsedMesh.hasMatricesIndices) {
  21335. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21336. }
  21337. if (parsedMesh.hasMatricesWeights) {
  21338. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21339. }
  21340. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21341. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21342. mesh._checkDelayState();
  21343. }
  21344. }
  21345. else {
  21346. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21347. }
  21348. // Material
  21349. if (parsedMesh.materialId) {
  21350. mesh.setMaterialByID(parsedMesh.materialId);
  21351. }
  21352. else {
  21353. mesh.material = null;
  21354. }
  21355. // Skeleton
  21356. if (parsedMesh.skeletonId > -1) {
  21357. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21358. if (parsedMesh.numBoneInfluencers) {
  21359. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21360. }
  21361. }
  21362. // Animations
  21363. if (parsedMesh.animations) {
  21364. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21365. var parsedAnimation = parsedMesh.animations[animationIndex];
  21366. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21367. }
  21368. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21369. }
  21370. if (parsedMesh.autoAnimate) {
  21371. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21372. }
  21373. // Layer Mask
  21374. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21375. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21376. }
  21377. else {
  21378. mesh.layerMask = 0x0FFFFFFF;
  21379. }
  21380. //(Deprecated) physics
  21381. if (parsedMesh.physicsImpostor) {
  21382. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21383. mass: parsedMesh.physicsMass,
  21384. friction: parsedMesh.physicsFriction,
  21385. restitution: parsedMesh.physicsRestitution
  21386. }, scene);
  21387. }
  21388. // Instances
  21389. if (parsedMesh.instances) {
  21390. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21391. var parsedInstance = parsedMesh.instances[index];
  21392. var instance = mesh.createInstance(parsedInstance.name);
  21393. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21394. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21395. if (parsedInstance.parentId) {
  21396. instance._waitingParentId = parsedInstance.parentId;
  21397. }
  21398. if (parsedInstance.rotationQuaternion) {
  21399. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21400. }
  21401. else if (parsedInstance.rotation) {
  21402. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21403. }
  21404. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21405. instance.checkCollisions = mesh.checkCollisions;
  21406. if (parsedMesh.animations) {
  21407. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21408. parsedAnimation = parsedMesh.animations[animationIndex];
  21409. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21410. }
  21411. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21412. }
  21413. }
  21414. }
  21415. return mesh;
  21416. };
  21417. /**
  21418. * Creates a ribbon mesh.
  21419. * Please consider using the same method from the MeshBuilder class instead.
  21420. * 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.
  21421. *
  21422. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21423. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21424. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21425. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21426. * 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.
  21427. * 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.
  21428. * 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
  21429. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21430. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21431. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21432. */
  21433. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21434. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21435. pathArray: pathArray,
  21436. closeArray: closeArray,
  21437. closePath: closePath,
  21438. offset: offset,
  21439. updatable: updatable,
  21440. sideOrientation: sideOrientation,
  21441. instance: instance
  21442. }, scene);
  21443. };
  21444. /**
  21445. * Creates a plane polygonal mesh. By default, this is a disc.
  21446. * Please consider using the same method from the MeshBuilder class instead.
  21447. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21448. * 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.
  21449. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21450. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21451. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21452. */
  21453. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21454. var options = {
  21455. radius: radius,
  21456. tessellation: tessellation,
  21457. sideOrientation: sideOrientation,
  21458. updatable: updatable
  21459. };
  21460. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21461. };
  21462. /**
  21463. * Creates a box mesh.
  21464. * Please consider using the same method from the MeshBuilder class instead.
  21465. * The parameter `size` sets the size (float) of each box side (default 1).
  21466. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21467. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21468. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21469. */
  21470. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21471. var options = {
  21472. size: size,
  21473. sideOrientation: sideOrientation,
  21474. updatable: updatable
  21475. };
  21476. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21477. };
  21478. /**
  21479. * Creates a sphere mesh.
  21480. * Please consider using the same method from the MeshBuilder class instead.
  21481. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21482. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21483. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21484. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21485. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21486. */
  21487. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21488. var options = {
  21489. segments: segments,
  21490. diameterX: diameter,
  21491. diameterY: diameter,
  21492. diameterZ: diameter,
  21493. sideOrientation: sideOrientation,
  21494. updatable: updatable
  21495. };
  21496. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21497. };
  21498. /**
  21499. * Creates a cylinder or a cone mesh.
  21500. * Please consider using the same method from the MeshBuilder class instead.
  21501. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21502. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21503. * 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.
  21504. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21505. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21506. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21507. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21508. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21509. */
  21510. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21511. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21512. if (scene !== undefined) {
  21513. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21514. updatable = scene;
  21515. }
  21516. scene = subdivisions;
  21517. subdivisions = 1;
  21518. }
  21519. var options = {
  21520. height: height,
  21521. diameterTop: diameterTop,
  21522. diameterBottom: diameterBottom,
  21523. tessellation: tessellation,
  21524. subdivisions: subdivisions,
  21525. sideOrientation: sideOrientation,
  21526. updatable: updatable
  21527. };
  21528. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21529. };
  21530. // Torus (Code from SharpDX.org)
  21531. /**
  21532. * Creates a torus mesh.
  21533. * Please consider using the same method from the MeshBuilder class instead.
  21534. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21535. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21536. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21537. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21538. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21539. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21540. */
  21541. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21542. var options = {
  21543. diameter: diameter,
  21544. thickness: thickness,
  21545. tessellation: tessellation,
  21546. sideOrientation: sideOrientation,
  21547. updatable: updatable
  21548. };
  21549. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21550. };
  21551. /**
  21552. * Creates a torus knot mesh.
  21553. * Please consider using the same method from the MeshBuilder class instead.
  21554. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21555. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21556. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21557. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21558. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21559. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21560. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21561. */
  21562. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21563. var options = {
  21564. radius: radius,
  21565. tube: tube,
  21566. radialSegments: radialSegments,
  21567. tubularSegments: tubularSegments,
  21568. p: p,
  21569. q: q,
  21570. sideOrientation: sideOrientation,
  21571. updatable: updatable
  21572. };
  21573. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21574. };
  21575. /**
  21576. * Creates a line mesh.
  21577. * Please consider using the same method from the MeshBuilder class instead.
  21578. * 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.
  21579. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21580. * The parameter `points` is an array successive Vector3.
  21581. * 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
  21582. * When updating an instance, remember that only point positions can change, not the number of points.
  21583. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21584. */
  21585. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21586. var options = {
  21587. points: points,
  21588. updatable: updatable,
  21589. instance: instance
  21590. };
  21591. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21592. };
  21593. /**
  21594. * Creates a dashed line mesh.
  21595. * Please consider using the same method from the MeshBuilder class instead.
  21596. * 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.
  21597. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21598. * The parameter `points` is an array successive Vector3.
  21599. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21600. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21601. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21602. * 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
  21603. * When updating an instance, remember that only point positions can change, not the number of points.
  21604. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21605. */
  21606. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21607. var options = {
  21608. points: points,
  21609. dashSize: dashSize,
  21610. gapSize: gapSize,
  21611. dashNb: dashNb,
  21612. updatable: updatable,
  21613. instance: instance
  21614. };
  21615. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21616. };
  21617. /**
  21618. * Creates an extruded shape mesh.
  21619. * 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.
  21620. * Please consider using the same method from the MeshBuilder class instead.
  21621. *
  21622. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21623. * 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
  21624. * extruded along the Z axis.
  21625. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21626. * 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.
  21627. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21628. * 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
  21629. * 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
  21630. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21631. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21632. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21633. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21634. */
  21635. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21636. var options = {
  21637. shape: shape,
  21638. path: path,
  21639. scale: scale,
  21640. rotation: rotation,
  21641. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21642. sideOrientation: sideOrientation,
  21643. instance: instance,
  21644. updatable: updatable
  21645. };
  21646. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21647. };
  21648. /**
  21649. * Creates an custom extruded shape mesh.
  21650. * 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.
  21651. * Please consider using the same method from the MeshBuilder class instead.
  21652. *
  21653. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21654. * 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
  21655. * extruded along the Z axis.
  21656. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21657. * 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
  21658. * and the distance of this point from the begining of the path :
  21659. * ```javascript
  21660. * var rotationFunction = function(i, distance) {
  21661. * // do things
  21662. * return rotationValue; }
  21663. * ```
  21664. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21665. * 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
  21666. * and the distance of this point from the begining of the path :
  21667. * ```javascript
  21668. * var scaleFunction = function(i, distance) {
  21669. * // do things
  21670. * return scaleValue;}
  21671. * ```
  21672. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21673. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21674. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21675. * 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
  21676. * 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
  21677. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21678. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21679. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21680. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21681. */
  21682. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21683. var options = {
  21684. shape: shape,
  21685. path: path,
  21686. scaleFunction: scaleFunction,
  21687. rotationFunction: rotationFunction,
  21688. ribbonCloseArray: ribbonCloseArray,
  21689. ribbonClosePath: ribbonClosePath,
  21690. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21691. sideOrientation: sideOrientation,
  21692. instance: instance,
  21693. updatable: updatable
  21694. };
  21695. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21696. };
  21697. /**
  21698. * Creates lathe mesh.
  21699. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21700. * Please consider using the same method from the MeshBuilder class instead.
  21701. * 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
  21702. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21703. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21704. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21705. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21706. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21707. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21708. */
  21709. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21710. var options = {
  21711. shape: shape,
  21712. radius: radius,
  21713. tessellation: tessellation,
  21714. sideOrientation: sideOrientation,
  21715. updatable: updatable
  21716. };
  21717. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21718. };
  21719. /**
  21720. * Creates a plane mesh.
  21721. * Please consider using the same method from the MeshBuilder class instead.
  21722. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21723. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21724. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21725. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21726. */
  21727. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21728. var options = {
  21729. size: size,
  21730. width: size,
  21731. height: size,
  21732. sideOrientation: sideOrientation,
  21733. updatable: updatable
  21734. };
  21735. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21736. };
  21737. /**
  21738. * Creates a ground mesh.
  21739. * Please consider using the same method from the MeshBuilder class instead.
  21740. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21741. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21742. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21743. */
  21744. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21745. var options = {
  21746. width: width,
  21747. height: height,
  21748. subdivisions: subdivisions,
  21749. updatable: updatable
  21750. };
  21751. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21752. };
  21753. /**
  21754. * Creates a tiled ground mesh.
  21755. * Please consider using the same method from the MeshBuilder class instead.
  21756. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21757. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21758. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21759. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21760. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21761. * numbers of subdivisions on the ground width and height of each tile.
  21762. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21763. */
  21764. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21765. var options = {
  21766. xmin: xmin,
  21767. zmin: zmin,
  21768. xmax: xmax,
  21769. zmax: zmax,
  21770. subdivisions: subdivisions,
  21771. precision: precision,
  21772. updatable: updatable
  21773. };
  21774. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21775. };
  21776. /**
  21777. * Creates a ground mesh from a height map.
  21778. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21779. * Please consider using the same method from the MeshBuilder class instead.
  21780. * The parameter `url` sets the URL of the height map image resource.
  21781. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21782. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21783. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21784. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21785. * 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).
  21786. * This function is passed the newly built mesh :
  21787. * ```javascript
  21788. * function(mesh) { // do things
  21789. * return; }
  21790. * ```
  21791. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21792. */
  21793. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21794. var options = {
  21795. width: width,
  21796. height: height,
  21797. subdivisions: subdivisions,
  21798. minHeight: minHeight,
  21799. maxHeight: maxHeight,
  21800. updatable: updatable,
  21801. onReady: onReady
  21802. };
  21803. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21804. };
  21805. /**
  21806. * Creates a tube mesh.
  21807. * 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.
  21808. * Please consider using the same method from the MeshBuilder class instead.
  21809. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21810. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21811. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21812. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21813. * 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.
  21814. * It must return a radius value (positive float) :
  21815. * ```javascript
  21816. * var radiusFunction = function(i, distance) {
  21817. * // do things
  21818. * return radius; }
  21819. * ```
  21820. * 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
  21821. * 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
  21822. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21823. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21824. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21825. */
  21826. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21827. var options = {
  21828. path: path,
  21829. radius: radius,
  21830. tessellation: tessellation,
  21831. radiusFunction: radiusFunction,
  21832. arc: 1,
  21833. cap: cap,
  21834. updatable: updatable,
  21835. sideOrientation: sideOrientation,
  21836. instance: instance
  21837. };
  21838. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21839. };
  21840. /**
  21841. * Creates a polyhedron mesh.
  21842. * Please consider using the same method from the MeshBuilder class instead.
  21843. * 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
  21844. * to choose the wanted type.
  21845. * The parameter `size` (positive float, default 1) sets the polygon size.
  21846. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21847. * 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`.
  21848. * 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
  21849. * 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)`).
  21850. * 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
  21851. * 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.
  21852. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21853. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21854. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21855. */
  21856. Mesh.CreatePolyhedron = function (name, options, scene) {
  21857. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21858. };
  21859. /**
  21860. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21861. * Please consider using the same method from the MeshBuilder class instead.
  21862. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21863. * 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`).
  21864. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21865. * 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.
  21866. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21867. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21868. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21869. */
  21870. Mesh.CreateIcoSphere = function (name, options, scene) {
  21871. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21872. };
  21873. /**
  21874. * Creates a decal mesh.
  21875. * Please consider using the same method from the MeshBuilder class instead.
  21876. * 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.
  21877. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21878. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21879. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21880. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21881. */
  21882. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21883. var options = {
  21884. position: position,
  21885. normal: normal,
  21886. size: size,
  21887. angle: angle
  21888. };
  21889. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21890. };
  21891. // Skeletons
  21892. /**
  21893. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21894. */
  21895. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21896. var source;
  21897. if (!this._sourcePositions) {
  21898. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21899. this._sourcePositions = new Float32Array(source);
  21900. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21901. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21902. }
  21903. }
  21904. return this._sourcePositions;
  21905. };
  21906. /**
  21907. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21908. */
  21909. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21910. var source;
  21911. if (!this._sourceNormals) {
  21912. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21913. this._sourceNormals = new Float32Array(source);
  21914. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21915. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21916. }
  21917. }
  21918. return this._sourceNormals;
  21919. };
  21920. /**
  21921. * Update the vertex buffers by applying transformation from the bones
  21922. * @param {skeleton} skeleton to apply
  21923. */
  21924. Mesh.prototype.applySkeleton = function (skeleton) {
  21925. if (!this.geometry) {
  21926. return;
  21927. }
  21928. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21929. return;
  21930. }
  21931. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21932. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21933. return this;
  21934. }
  21935. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21936. return this;
  21937. }
  21938. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21939. return this;
  21940. }
  21941. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21942. return this;
  21943. }
  21944. if (!this._sourcePositions) {
  21945. var submeshes = this.subMeshes.slice();
  21946. this.setPositionsForCPUSkinning();
  21947. this.subMeshes = submeshes;
  21948. }
  21949. if (!this._sourceNormals) {
  21950. this.setNormalsForCPUSkinning();
  21951. }
  21952. // positionsData checks for not being Float32Array will only pass at most once
  21953. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21954. if (!(positionsData instanceof Float32Array)) {
  21955. positionsData = new Float32Array(positionsData);
  21956. }
  21957. // normalsData checks for not being Float32Array will only pass at most once
  21958. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21959. if (!(normalsData instanceof Float32Array)) {
  21960. normalsData = new Float32Array(normalsData);
  21961. }
  21962. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21963. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21964. var needExtras = this.numBoneInfluencers > 4;
  21965. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21966. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21967. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21968. var tempVector3 = BABYLON.Vector3.Zero();
  21969. var finalMatrix = new BABYLON.Matrix();
  21970. var tempMatrix = new BABYLON.Matrix();
  21971. var matWeightIdx = 0;
  21972. var inf;
  21973. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21974. var weight;
  21975. for (inf = 0; inf < 4; inf++) {
  21976. weight = matricesWeightsData[matWeightIdx + inf];
  21977. if (weight > 0) {
  21978. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21979. finalMatrix.addToSelf(tempMatrix);
  21980. }
  21981. else
  21982. break;
  21983. }
  21984. if (needExtras) {
  21985. for (inf = 0; inf < 4; inf++) {
  21986. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21987. if (weight > 0) {
  21988. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21989. finalMatrix.addToSelf(tempMatrix);
  21990. }
  21991. else
  21992. break;
  21993. }
  21994. }
  21995. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21996. tempVector3.toArray(positionsData, index);
  21997. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21998. tempVector3.toArray(normalsData, index);
  21999. finalMatrix.reset();
  22000. }
  22001. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  22002. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  22003. return this;
  22004. };
  22005. // Tools
  22006. /**
  22007. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  22008. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  22009. */
  22010. Mesh.MinMax = function (meshes) {
  22011. var minVector = null;
  22012. var maxVector = null;
  22013. meshes.forEach(function (mesh, index, array) {
  22014. var boundingBox = mesh.getBoundingInfo().boundingBox;
  22015. if (!minVector) {
  22016. minVector = boundingBox.minimumWorld;
  22017. maxVector = boundingBox.maximumWorld;
  22018. }
  22019. else {
  22020. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  22021. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  22022. }
  22023. });
  22024. return {
  22025. min: minVector,
  22026. max: maxVector
  22027. };
  22028. };
  22029. /**
  22030. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  22031. */
  22032. Mesh.Center = function (meshesOrMinMaxVector) {
  22033. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  22034. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  22035. };
  22036. /**
  22037. * Merge the array of meshes into a single mesh for performance reasons.
  22038. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  22039. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  22040. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  22041. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  22042. */
  22043. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  22044. if (disposeSource === void 0) { disposeSource = true; }
  22045. var index;
  22046. if (!allow32BitsIndices) {
  22047. var totalVertices = 0;
  22048. // Counting vertices
  22049. for (index = 0; index < meshes.length; index++) {
  22050. if (meshes[index]) {
  22051. totalVertices += meshes[index].getTotalVertices();
  22052. if (totalVertices > 65536) {
  22053. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  22054. return null;
  22055. }
  22056. }
  22057. }
  22058. }
  22059. // Merge
  22060. var vertexData;
  22061. var otherVertexData;
  22062. var source;
  22063. for (index = 0; index < meshes.length; index++) {
  22064. if (meshes[index]) {
  22065. meshes[index].computeWorldMatrix(true);
  22066. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  22067. otherVertexData.transform(meshes[index].getWorldMatrix());
  22068. if (vertexData) {
  22069. vertexData.merge(otherVertexData);
  22070. }
  22071. else {
  22072. vertexData = otherVertexData;
  22073. source = meshes[index];
  22074. }
  22075. }
  22076. }
  22077. if (!meshSubclass) {
  22078. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22079. }
  22080. vertexData.applyToMesh(meshSubclass);
  22081. // Setting properties
  22082. meshSubclass.material = source.material;
  22083. meshSubclass.checkCollisions = source.checkCollisions;
  22084. // Cleaning
  22085. if (disposeSource) {
  22086. for (index = 0; index < meshes.length; index++) {
  22087. if (meshes[index]) {
  22088. meshes[index].dispose();
  22089. }
  22090. }
  22091. }
  22092. return meshSubclass;
  22093. };
  22094. return Mesh;
  22095. }(BABYLON.AbstractMesh));
  22096. // Consts
  22097. Mesh._FRONTSIDE = 0;
  22098. Mesh._BACKSIDE = 1;
  22099. Mesh._DOUBLESIDE = 2;
  22100. Mesh._DEFAULTSIDE = 0;
  22101. Mesh._NO_CAP = 0;
  22102. Mesh._CAP_START = 1;
  22103. Mesh._CAP_END = 2;
  22104. Mesh._CAP_ALL = 3;
  22105. BABYLON.Mesh = Mesh;
  22106. })(BABYLON || (BABYLON = {}));
  22107. //# sourceMappingURL=babylon.mesh.js.map
  22108. var BABYLON;
  22109. (function (BABYLON) {
  22110. var SubMesh = (function () {
  22111. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22112. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22113. this.materialIndex = materialIndex;
  22114. this.verticesStart = verticesStart;
  22115. this.verticesCount = verticesCount;
  22116. this.indexStart = indexStart;
  22117. this.indexCount = indexCount;
  22118. this._renderId = 0;
  22119. this._mesh = mesh;
  22120. this._renderingMesh = renderingMesh || mesh;
  22121. mesh.subMeshes.push(this);
  22122. this._trianglePlanes = [];
  22123. this._id = mesh.subMeshes.length - 1;
  22124. if (createBoundingBox) {
  22125. this.refreshBoundingInfo();
  22126. mesh.computeWorldMatrix(true);
  22127. }
  22128. }
  22129. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22130. get: function () {
  22131. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22132. },
  22133. enumerable: true,
  22134. configurable: true
  22135. });
  22136. SubMesh.prototype.getBoundingInfo = function () {
  22137. if (this.IsGlobal) {
  22138. return this._mesh.getBoundingInfo();
  22139. }
  22140. return this._boundingInfo;
  22141. };
  22142. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22143. this._boundingInfo = boundingInfo;
  22144. };
  22145. SubMesh.prototype.getMesh = function () {
  22146. return this._mesh;
  22147. };
  22148. SubMesh.prototype.getRenderingMesh = function () {
  22149. return this._renderingMesh;
  22150. };
  22151. SubMesh.prototype.getMaterial = function () {
  22152. var rootMaterial = this._renderingMesh.material;
  22153. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  22154. var multiMaterial = rootMaterial;
  22155. return multiMaterial.getSubMaterial(this.materialIndex);
  22156. }
  22157. if (!rootMaterial) {
  22158. return this._mesh.getScene().defaultMaterial;
  22159. }
  22160. return rootMaterial;
  22161. };
  22162. // Methods
  22163. SubMesh.prototype.refreshBoundingInfo = function () {
  22164. this._lastColliderWorldVertices = null;
  22165. if (this.IsGlobal) {
  22166. return;
  22167. }
  22168. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22169. if (!data) {
  22170. this._boundingInfo = this._mesh._boundingInfo;
  22171. return;
  22172. }
  22173. var indices = this._renderingMesh.getIndices();
  22174. var extend;
  22175. //is this the only submesh?
  22176. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22177. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22178. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22179. }
  22180. else {
  22181. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22182. }
  22183. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22184. };
  22185. SubMesh.prototype._checkCollision = function (collider) {
  22186. return this.getBoundingInfo()._checkCollision(collider);
  22187. };
  22188. SubMesh.prototype.updateBoundingInfo = function (world) {
  22189. if (!this.getBoundingInfo()) {
  22190. this.refreshBoundingInfo();
  22191. }
  22192. this.getBoundingInfo().update(world);
  22193. };
  22194. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22195. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22196. };
  22197. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22198. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22199. };
  22200. SubMesh.prototype.render = function (enableAlphaMode) {
  22201. this._renderingMesh.render(this, enableAlphaMode);
  22202. };
  22203. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22204. if (!this._linesIndexBuffer) {
  22205. var linesIndices = [];
  22206. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22207. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22208. }
  22209. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22210. this.linesIndexCount = linesIndices.length;
  22211. }
  22212. return this._linesIndexBuffer;
  22213. };
  22214. SubMesh.prototype.canIntersects = function (ray) {
  22215. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22216. };
  22217. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22218. var intersectInfo = null;
  22219. // LineMesh first as it's also a Mesh...
  22220. if (this._mesh instanceof BABYLON.LinesMesh) {
  22221. var lineMesh = this._mesh;
  22222. // Line test
  22223. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22224. var p0 = positions[indices[index]];
  22225. var p1 = positions[indices[index + 1]];
  22226. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22227. if (length < 0) {
  22228. continue;
  22229. }
  22230. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22231. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22232. if (fastCheck) {
  22233. break;
  22234. }
  22235. }
  22236. }
  22237. }
  22238. else {
  22239. // Triangles test
  22240. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22241. var p0 = positions[indices[index]];
  22242. var p1 = positions[indices[index + 1]];
  22243. var p2 = positions[indices[index + 2]];
  22244. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22245. if (currentIntersectInfo) {
  22246. if (currentIntersectInfo.distance < 0) {
  22247. continue;
  22248. }
  22249. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22250. intersectInfo = currentIntersectInfo;
  22251. intersectInfo.faceId = index / 3;
  22252. if (fastCheck) {
  22253. break;
  22254. }
  22255. }
  22256. }
  22257. }
  22258. }
  22259. return intersectInfo;
  22260. };
  22261. // Clone
  22262. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22263. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22264. if (!this.IsGlobal) {
  22265. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22266. }
  22267. return result;
  22268. };
  22269. // Dispose
  22270. SubMesh.prototype.dispose = function () {
  22271. if (this._linesIndexBuffer) {
  22272. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22273. this._linesIndexBuffer = null;
  22274. }
  22275. // Remove from mesh
  22276. var index = this._mesh.subMeshes.indexOf(this);
  22277. this._mesh.subMeshes.splice(index, 1);
  22278. };
  22279. // Statics
  22280. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22281. var minVertexIndex = Number.MAX_VALUE;
  22282. var maxVertexIndex = -Number.MAX_VALUE;
  22283. renderingMesh = renderingMesh || mesh;
  22284. var indices = renderingMesh.getIndices();
  22285. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22286. var vertexIndex = indices[index];
  22287. if (vertexIndex < minVertexIndex)
  22288. minVertexIndex = vertexIndex;
  22289. if (vertexIndex > maxVertexIndex)
  22290. maxVertexIndex = vertexIndex;
  22291. }
  22292. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22293. };
  22294. return SubMesh;
  22295. }());
  22296. BABYLON.SubMesh = SubMesh;
  22297. })(BABYLON || (BABYLON = {}));
  22298. //# sourceMappingURL=babylon.subMesh.js.map
  22299. var BABYLON;
  22300. (function (BABYLON) {
  22301. var MeshBuilder = (function () {
  22302. function MeshBuilder() {
  22303. }
  22304. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  22305. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  22306. return BABYLON.Mesh.DOUBLESIDE;
  22307. }
  22308. if (orientation === undefined || orientation === null) {
  22309. return BABYLON.Mesh.FRONTSIDE;
  22310. }
  22311. return orientation;
  22312. };
  22313. /**
  22314. * Creates a box mesh.
  22315. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  22316. * The parameter `size` sets the size (float) of each box side (default 1).
  22317. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  22318. * 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).
  22319. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  22320. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22321. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22322. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22323. */
  22324. MeshBuilder.CreateBox = function (name, options, scene) {
  22325. var box = new BABYLON.Mesh(name, scene);
  22326. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22327. box.sideOrientation = options.sideOrientation;
  22328. var vertexData = BABYLON.VertexData.CreateBox(options);
  22329. vertexData.applyToMesh(box, options.updatable);
  22330. return box;
  22331. };
  22332. /**
  22333. * Creates a sphere mesh.
  22334. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  22335. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22336. * 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`).
  22337. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22338. * 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
  22339. * 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).
  22340. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22341. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22342. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22343. */
  22344. MeshBuilder.CreateSphere = function (name, options, scene) {
  22345. var sphere = new BABYLON.Mesh(name, scene);
  22346. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22347. sphere.sideOrientation = options.sideOrientation;
  22348. var vertexData = BABYLON.VertexData.CreateSphere(options);
  22349. vertexData.applyToMesh(sphere, options.updatable);
  22350. return sphere;
  22351. };
  22352. /**
  22353. * Creates a plane polygonal mesh. By default, this is a disc.
  22354. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  22355. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22356. * 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.
  22357. * 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
  22358. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22359. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22360. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22361. */
  22362. MeshBuilder.CreateDisc = function (name, options, scene) {
  22363. var disc = new BABYLON.Mesh(name, scene);
  22364. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22365. disc.sideOrientation = options.sideOrientation;
  22366. var vertexData = BABYLON.VertexData.CreateDisc(options);
  22367. vertexData.applyToMesh(disc, options.updatable);
  22368. return disc;
  22369. };
  22370. /**
  22371. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22372. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  22373. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22374. * 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`).
  22375. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22376. * 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.
  22377. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22378. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22379. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22380. */
  22381. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  22382. var sphere = new BABYLON.Mesh(name, scene);
  22383. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22384. sphere.sideOrientation = options.sideOrientation;
  22385. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  22386. vertexData.applyToMesh(sphere, options.updatable);
  22387. return sphere;
  22388. };
  22389. ;
  22390. /**
  22391. * Creates a ribbon mesh.
  22392. * 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.
  22393. *
  22394. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  22395. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  22396. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  22397. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  22398. * 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.
  22399. * 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.
  22400. * 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
  22401. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22402. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22403. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22404. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22405. */
  22406. MeshBuilder.CreateRibbon = function (name, options, scene) {
  22407. var pathArray = options.pathArray;
  22408. var closeArray = options.closeArray;
  22409. var closePath = options.closePath;
  22410. var offset = options.offset;
  22411. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22412. var instance = options.instance;
  22413. var updatable = options.updatable;
  22414. if (instance) {
  22415. // positionFunction : ribbon case
  22416. // only pathArray and sideOrientation parameters are taken into account for positions update
  22417. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  22418. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  22419. var positionFunction = function (positions) {
  22420. var minlg = pathArray[0].length;
  22421. var i = 0;
  22422. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  22423. for (var si = 1; si <= ns; si++) {
  22424. for (var p = 0; p < pathArray.length; p++) {
  22425. var path = pathArray[p];
  22426. var l = path.length;
  22427. minlg = (minlg < l) ? minlg : l;
  22428. var j = 0;
  22429. while (j < minlg) {
  22430. positions[i] = path[j].x;
  22431. positions[i + 1] = path[j].y;
  22432. positions[i + 2] = path[j].z;
  22433. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  22434. BABYLON.Tmp.Vector3[0].x = path[j].x;
  22435. }
  22436. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  22437. BABYLON.Tmp.Vector3[1].x = path[j].x;
  22438. }
  22439. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  22440. BABYLON.Tmp.Vector3[0].y = path[j].y;
  22441. }
  22442. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  22443. BABYLON.Tmp.Vector3[1].y = path[j].y;
  22444. }
  22445. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  22446. BABYLON.Tmp.Vector3[0].z = path[j].z;
  22447. }
  22448. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  22449. BABYLON.Tmp.Vector3[1].z = path[j].z;
  22450. }
  22451. j++;
  22452. i += 3;
  22453. }
  22454. if (instance._closePath) {
  22455. positions[i] = path[0].x;
  22456. positions[i + 1] = path[0].y;
  22457. positions[i + 2] = path[0].z;
  22458. i += 3;
  22459. }
  22460. }
  22461. }
  22462. };
  22463. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22464. positionFunction(positions);
  22465. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  22466. instance._boundingInfo.update(instance._worldMatrix);
  22467. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  22468. if (!(instance.areNormalsFrozen)) {
  22469. var indices = instance.getIndices();
  22470. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22471. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  22472. if (instance._closePath) {
  22473. var indexFirst = 0;
  22474. var indexLast = 0;
  22475. for (var p = 0; p < pathArray.length; p++) {
  22476. indexFirst = instance._idx[p] * 3;
  22477. if (p + 1 < pathArray.length) {
  22478. indexLast = (instance._idx[p + 1] - 1) * 3;
  22479. }
  22480. else {
  22481. indexLast = normals.length - 3;
  22482. }
  22483. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  22484. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  22485. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  22486. normals[indexLast] = normals[indexFirst];
  22487. normals[indexLast + 1] = normals[indexFirst + 1];
  22488. normals[indexLast + 2] = normals[indexFirst + 2];
  22489. }
  22490. }
  22491. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  22492. }
  22493. return instance;
  22494. }
  22495. else {
  22496. var ribbon = new BABYLON.Mesh(name, scene);
  22497. ribbon.sideOrientation = sideOrientation;
  22498. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  22499. if (closePath) {
  22500. ribbon._idx = vertexData._idx;
  22501. }
  22502. ribbon._closePath = closePath;
  22503. ribbon._closeArray = closeArray;
  22504. vertexData.applyToMesh(ribbon, updatable);
  22505. return ribbon;
  22506. }
  22507. };
  22508. /**
  22509. * Creates a cylinder or a cone mesh.
  22510. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  22511. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  22512. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  22513. * 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.
  22514. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  22515. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  22516. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  22517. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  22518. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  22519. * 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).
  22520. * 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
  22521. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  22522. * 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
  22523. * 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.
  22524. * If `enclose` is false, a ring surface is one element.
  22525. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  22526. * 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
  22527. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22528. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22529. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22530. */
  22531. MeshBuilder.CreateCylinder = function (name, options, scene) {
  22532. var cylinder = new BABYLON.Mesh(name, scene);
  22533. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22534. cylinder.sideOrientation = options.sideOrientation;
  22535. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  22536. vertexData.applyToMesh(cylinder, options.updatable);
  22537. return cylinder;
  22538. };
  22539. /**
  22540. * Creates a torus mesh.
  22541. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  22542. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  22543. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  22544. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  22545. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22546. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22547. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22548. */
  22549. MeshBuilder.CreateTorus = function (name, options, scene) {
  22550. var torus = new BABYLON.Mesh(name, scene);
  22551. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22552. torus.sideOrientation = options.sideOrientation;
  22553. var vertexData = BABYLON.VertexData.CreateTorus(options);
  22554. vertexData.applyToMesh(torus, options.updatable);
  22555. return torus;
  22556. };
  22557. /**
  22558. * Creates a torus knot mesh.
  22559. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  22560. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  22561. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  22562. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  22563. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  22564. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22565. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22566. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22567. */
  22568. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  22569. var torusKnot = new BABYLON.Mesh(name, scene);
  22570. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22571. torusKnot.sideOrientation = options.sideOrientation;
  22572. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  22573. vertexData.applyToMesh(torusKnot, options.updatable);
  22574. return torusKnot;
  22575. };
  22576. /**
  22577. * Creates a line system mesh.
  22578. * A line system is a pool of many lines gathered in a single mesh.
  22579. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  22580. * 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.
  22581. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  22582. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  22583. * 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
  22584. * 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
  22585. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  22586. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22587. */
  22588. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  22589. var instance = options.instance;
  22590. var lines = options.lines;
  22591. if (instance) {
  22592. var positionFunction = function (positions) {
  22593. var i = 0;
  22594. for (var l = 0; l < lines.length; l++) {
  22595. var points = lines[l];
  22596. for (var p = 0; p < points.length; p++) {
  22597. positions[i] = points[p].x;
  22598. positions[i + 1] = points[p].y;
  22599. positions[i + 2] = points[p].z;
  22600. i += 3;
  22601. }
  22602. }
  22603. };
  22604. instance.updateMeshPositions(positionFunction, false);
  22605. return instance;
  22606. }
  22607. // line system creation
  22608. var lineSystem = new BABYLON.LinesMesh(name, scene);
  22609. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  22610. vertexData.applyToMesh(lineSystem, options.updatable);
  22611. return lineSystem;
  22612. };
  22613. /**
  22614. * Creates a line mesh.
  22615. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  22616. * 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.
  22617. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22618. * The parameter `points` is an array successive Vector3.
  22619. * 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
  22620. * When updating an instance, remember that only point positions can change, not the number of points.
  22621. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22622. */
  22623. MeshBuilder.CreateLines = function (name, options, scene) {
  22624. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  22625. return lines;
  22626. };
  22627. /**
  22628. * Creates a dashed line mesh.
  22629. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  22630. * 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.
  22631. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22632. * The parameter `points` is an array successive Vector3.
  22633. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  22634. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  22635. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  22636. * 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
  22637. * When updating an instance, remember that only point positions can change, not the number of points.
  22638. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22639. */
  22640. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  22641. var points = options.points;
  22642. var instance = options.instance;
  22643. var gapSize = options.gapSize;
  22644. var dashNb = options.dashNb;
  22645. var dashSize = options.dashSize;
  22646. if (instance) {
  22647. var positionFunction = function (positions) {
  22648. var curvect = BABYLON.Vector3.Zero();
  22649. var nbSeg = positions.length / 6;
  22650. var lg = 0;
  22651. var nb = 0;
  22652. var shft = 0;
  22653. var dashshft = 0;
  22654. var curshft = 0;
  22655. var p = 0;
  22656. var i = 0;
  22657. var j = 0;
  22658. for (i = 0; i < points.length - 1; i++) {
  22659. points[i + 1].subtractToRef(points[i], curvect);
  22660. lg += curvect.length();
  22661. }
  22662. shft = lg / nbSeg;
  22663. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  22664. for (i = 0; i < points.length - 1; i++) {
  22665. points[i + 1].subtractToRef(points[i], curvect);
  22666. nb = Math.floor(curvect.length() / shft);
  22667. curvect.normalize();
  22668. j = 0;
  22669. while (j < nb && p < positions.length) {
  22670. curshft = shft * j;
  22671. positions[p] = points[i].x + curshft * curvect.x;
  22672. positions[p + 1] = points[i].y + curshft * curvect.y;
  22673. positions[p + 2] = points[i].z + curshft * curvect.z;
  22674. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  22675. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  22676. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  22677. p += 6;
  22678. j++;
  22679. }
  22680. }
  22681. while (p < positions.length) {
  22682. positions[p] = points[i].x;
  22683. positions[p + 1] = points[i].y;
  22684. positions[p + 2] = points[i].z;
  22685. p += 3;
  22686. }
  22687. };
  22688. instance.updateMeshPositions(positionFunction, false);
  22689. return instance;
  22690. }
  22691. // dashed lines creation
  22692. var dashedLines = new BABYLON.LinesMesh(name, scene);
  22693. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  22694. vertexData.applyToMesh(dashedLines, options.updatable);
  22695. dashedLines.dashSize = dashSize;
  22696. dashedLines.gapSize = gapSize;
  22697. return dashedLines;
  22698. };
  22699. /**
  22700. * Creates an extruded shape mesh.
  22701. * 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.
  22702. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  22703. *
  22704. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22705. * 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
  22706. * extruded along the Z axis.
  22707. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22708. * 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.
  22709. * The parameter `scale` (float, default 1) is the value to scale the shape.
  22710. * 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
  22711. * 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
  22712. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22713. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22714. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22715. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22716. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22717. */
  22718. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  22719. var path = options.path;
  22720. var shape = options.shape;
  22721. var scale = options.scale || 1;
  22722. var rotation = options.rotation || 0;
  22723. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  22724. var updatable = options.updatable;
  22725. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22726. var instance = options.instance;
  22727. var invertUV = options.invertUV || false;
  22728. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  22729. };
  22730. /**
  22731. * Creates an custom extruded shape mesh.
  22732. * 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.
  22733. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  22734. *
  22735. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22736. * 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
  22737. * extruded along the Z axis.
  22738. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22739. * 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
  22740. * and the distance of this point from the begining of the path :
  22741. * ```javascript
  22742. * var rotationFunction = function(i, distance) {
  22743. * // do things
  22744. * return rotationValue; }
  22745. * ```
  22746. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  22747. * 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
  22748. * and the distance of this point from the begining of the path :
  22749. * ```javascript
  22750. * var scaleFunction = function(i, distance) {
  22751. * // do things
  22752. * return scaleValue;}
  22753. * ```
  22754. * It must returns a float value that will be the scale value applied to the shape on each path point.
  22755. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  22756. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  22757. * 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
  22758. * 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
  22759. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22760. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22761. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22762. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22763. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22764. */
  22765. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  22766. var path = options.path;
  22767. var shape = options.shape;
  22768. var scaleFunction = options.scaleFunction || (function () { return 1; });
  22769. var rotationFunction = options.rotationFunction || (function () { return 0; });
  22770. var ribbonCloseArray = options.ribbonCloseArray || false;
  22771. var ribbonClosePath = options.ribbonClosePath || false;
  22772. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  22773. var updatable = options.updatable;
  22774. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22775. var instance = options.instance;
  22776. var invertUV = options.invertUV || false;
  22777. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  22778. };
  22779. /**
  22780. * Creates lathe mesh.
  22781. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  22782. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  22783. *
  22784. * 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
  22785. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  22786. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  22787. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  22788. * 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.
  22789. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  22790. * 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
  22791. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22792. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22793. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22794. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22795. */
  22796. MeshBuilder.CreateLathe = function (name, options, scene) {
  22797. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  22798. var closed = (options.closed === undefined) ? true : options.closed;
  22799. var shape = options.shape;
  22800. var radius = options.radius || 1;
  22801. var tessellation = options.tessellation || 64;
  22802. var updatable = options.updatable;
  22803. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22804. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22805. var pi2 = Math.PI * 2;
  22806. var paths = new Array();
  22807. var invertUV = options.invertUV || false;
  22808. var i = 0;
  22809. var p = 0;
  22810. var step = pi2 / tessellation * arc;
  22811. var rotated;
  22812. var path = new Array();
  22813. ;
  22814. for (i = 0; i <= tessellation; i++) {
  22815. var path = [];
  22816. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  22817. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  22818. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  22819. }
  22820. for (p = 0; p < shape.length; p++) {
  22821. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  22822. path.push(rotated);
  22823. }
  22824. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  22825. 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));
  22826. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  22827. }
  22828. paths.push(path);
  22829. }
  22830. // lathe ribbon
  22831. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  22832. return lathe;
  22833. };
  22834. /**
  22835. * Creates a plane mesh.
  22836. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22837. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22838. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  22839. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  22840. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22841. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22842. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22843. */
  22844. MeshBuilder.CreatePlane = function (name, options, scene) {
  22845. var plane = new BABYLON.Mesh(name, scene);
  22846. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22847. plane.sideOrientation = options.sideOrientation;
  22848. var vertexData = BABYLON.VertexData.CreatePlane(options);
  22849. vertexData.applyToMesh(plane, options.updatable);
  22850. if (options.sourcePlane) {
  22851. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  22852. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  22853. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  22854. plane.rotate(vectorProduct, product);
  22855. }
  22856. return plane;
  22857. };
  22858. /**
  22859. * Creates a ground mesh.
  22860. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22861. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22862. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22863. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22864. */
  22865. MeshBuilder.CreateGround = function (name, options, scene) {
  22866. var ground = new BABYLON.GroundMesh(name, scene);
  22867. ground._setReady(false);
  22868. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  22869. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  22870. ground._width = options.width || 1;
  22871. ground._height = options.height || 1;
  22872. ground._maxX = ground._width / 2;
  22873. ground._maxZ = ground._height / 2;
  22874. ground._minX = -ground._maxX;
  22875. ground._minZ = -ground._maxZ;
  22876. var vertexData = BABYLON.VertexData.CreateGround(options);
  22877. vertexData.applyToMesh(ground, options.updatable);
  22878. ground._setReady(true);
  22879. return ground;
  22880. };
  22881. /**
  22882. * Creates a tiled ground mesh.
  22883. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  22884. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22885. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22886. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22887. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22888. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22889. * numbers of subdivisions on the ground width and height of each tile.
  22890. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22891. */
  22892. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  22893. var tiledGround = new BABYLON.Mesh(name, scene);
  22894. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  22895. vertexData.applyToMesh(tiledGround, options.updatable);
  22896. return tiledGround;
  22897. };
  22898. /**
  22899. * Creates a ground mesh from a height map.
  22900. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22901. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  22902. * The parameter `url` sets the URL of the height map image resource.
  22903. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22904. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22905. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22906. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22907. * 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).
  22908. * This function is passed the newly built mesh :
  22909. * ```javascript
  22910. * function(mesh) { // do things
  22911. * return; }
  22912. * ```
  22913. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22914. */
  22915. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  22916. var width = options.width || 10.0;
  22917. var height = options.height || 10.0;
  22918. var subdivisions = options.subdivisions || 1 | 0;
  22919. var minHeight = options.minHeight || 0.0;
  22920. var maxHeight = options.maxHeight || 10.0;
  22921. var updatable = options.updatable;
  22922. var onReady = options.onReady;
  22923. var ground = new BABYLON.GroundMesh(name, scene);
  22924. ground._subdivisionsX = subdivisions;
  22925. ground._subdivisionsY = subdivisions;
  22926. ground._width = width;
  22927. ground._height = height;
  22928. ground._maxX = ground._width / 2.0;
  22929. ground._maxZ = ground._height / 2.0;
  22930. ground._minX = -ground._maxX;
  22931. ground._minZ = -ground._maxZ;
  22932. ground._setReady(false);
  22933. var onload = function (img) {
  22934. // Getting height map data
  22935. var canvas = document.createElement("canvas");
  22936. var context = canvas.getContext("2d");
  22937. var bufferWidth = img.width;
  22938. var bufferHeight = img.height;
  22939. canvas.width = bufferWidth;
  22940. canvas.height = bufferHeight;
  22941. context.drawImage(img, 0, 0);
  22942. // Create VertexData from map data
  22943. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22944. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  22945. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  22946. width: width, height: height,
  22947. subdivisions: subdivisions,
  22948. minHeight: minHeight, maxHeight: maxHeight,
  22949. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  22950. });
  22951. vertexData.applyToMesh(ground, updatable);
  22952. ground._setReady(true);
  22953. //execute ready callback, if set
  22954. if (onReady) {
  22955. onReady(ground);
  22956. }
  22957. };
  22958. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22959. return ground;
  22960. };
  22961. /**
  22962. * Creates a tube mesh.
  22963. * 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.
  22964. *
  22965. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  22966. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22967. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22968. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22969. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22970. * 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.
  22971. * It must return a radius value (positive float) :
  22972. * ```javascript
  22973. * var radiusFunction = function(i, distance) {
  22974. * // do things
  22975. * return radius; }
  22976. * ```
  22977. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  22978. * 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
  22979. * 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
  22980. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22981. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22982. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22983. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22984. */
  22985. MeshBuilder.CreateTube = function (name, options, scene) {
  22986. var path = options.path;
  22987. var radius = options.radius || 1.0;
  22988. var tessellation = options.tessellation || 64 | 0;
  22989. var radiusFunction = options.radiusFunction;
  22990. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22991. var invertUV = options.invertUV || false;
  22992. var updatable = options.updatable;
  22993. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22994. var instance = options.instance;
  22995. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  22996. // tube geometry
  22997. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  22998. var tangents = path3D.getTangents();
  22999. var normals = path3D.getNormals();
  23000. var distances = path3D.getDistances();
  23001. var pi2 = Math.PI * 2;
  23002. var step = pi2 / tessellation * arc;
  23003. var returnRadius = function () { return radius; };
  23004. var radiusFunctionFinal = radiusFunction || returnRadius;
  23005. var circlePath;
  23006. var rad;
  23007. var normal;
  23008. var rotated;
  23009. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  23010. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  23011. for (var i = 0; i < path.length; i++) {
  23012. rad = radiusFunctionFinal(i, distances[i]); // current radius
  23013. circlePath = Array(); // current circle array
  23014. normal = normals[i]; // current normal
  23015. for (var t = 0; t < tessellation; t++) {
  23016. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  23017. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  23018. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  23019. rotated.scaleInPlace(rad).addInPlace(path[i]);
  23020. circlePath[t] = rotated;
  23021. }
  23022. circlePaths[index] = circlePath;
  23023. index++;
  23024. }
  23025. // cap
  23026. var capPath = function (nbPoints, pathIndex) {
  23027. var pointCap = Array();
  23028. for (var i = 0; i < nbPoints; i++) {
  23029. pointCap.push(path[pathIndex]);
  23030. }
  23031. return pointCap;
  23032. };
  23033. switch (cap) {
  23034. case BABYLON.Mesh.NO_CAP:
  23035. break;
  23036. case BABYLON.Mesh.CAP_START:
  23037. circlePaths[0] = capPath(tessellation, 0);
  23038. circlePaths[1] = circlePaths[2].slice(0);
  23039. break;
  23040. case BABYLON.Mesh.CAP_END:
  23041. circlePaths[index] = circlePaths[index - 1].slice(0);
  23042. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  23043. break;
  23044. case BABYLON.Mesh.CAP_ALL:
  23045. circlePaths[0] = capPath(tessellation, 0);
  23046. circlePaths[1] = circlePaths[2].slice(0);
  23047. circlePaths[index] = circlePaths[index - 1].slice(0);
  23048. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  23049. break;
  23050. default:
  23051. break;
  23052. }
  23053. return circlePaths;
  23054. };
  23055. var path3D;
  23056. var pathArray;
  23057. if (instance) {
  23058. var arc = options.arc || instance.arc;
  23059. path3D = (instance.path3D).update(path);
  23060. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  23061. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  23062. instance.path3D = path3D;
  23063. instance.pathArray = pathArray;
  23064. instance.arc = arc;
  23065. return instance;
  23066. }
  23067. // tube creation
  23068. path3D = new BABYLON.Path3D(path);
  23069. var newPathArray = new Array();
  23070. cap = (cap < 0 || cap > 3) ? 0 : cap;
  23071. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  23072. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  23073. tube.pathArray = pathArray;
  23074. tube.path3D = path3D;
  23075. tube.tessellation = tessellation;
  23076. tube.cap = cap;
  23077. tube.arc = options.arc;
  23078. return tube;
  23079. };
  23080. /**
  23081. * Creates a polyhedron mesh.
  23082. *
  23083. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  23084. * 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
  23085. * to choose the wanted type.
  23086. * The parameter `size` (positive float, default 1) sets the polygon size.
  23087. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23088. * 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`.
  23089. * 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
  23090. * 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)`).
  23091. * 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
  23092. * 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.
  23093. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23094. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23095. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23096. */
  23097. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  23098. var polyhedron = new BABYLON.Mesh(name, scene);
  23099. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  23100. polyhedron.sideOrientation = options.sideOrientation;
  23101. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  23102. vertexData.applyToMesh(polyhedron, options.updatable);
  23103. return polyhedron;
  23104. };
  23105. /**
  23106. * Creates a decal mesh.
  23107. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  23108. * 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.
  23109. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23110. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23111. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23112. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23113. */
  23114. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  23115. var indices = sourceMesh.getIndices();
  23116. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23117. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23118. var position = options.position || BABYLON.Vector3.Zero();
  23119. var normal = options.normal || BABYLON.Vector3.Up();
  23120. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  23121. var angle = options.angle || 0;
  23122. // Getting correct rotation
  23123. if (!normal) {
  23124. var target = new BABYLON.Vector3(0, 0, 1);
  23125. var camera = sourceMesh.getScene().activeCamera;
  23126. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  23127. normal = camera.globalPosition.subtract(cameraWorldTarget);
  23128. }
  23129. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  23130. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  23131. var pitch = Math.atan2(normal.y, len);
  23132. // Matrix
  23133. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  23134. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  23135. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  23136. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  23137. var vertexData = new BABYLON.VertexData();
  23138. vertexData.indices = [];
  23139. vertexData.positions = [];
  23140. vertexData.normals = [];
  23141. vertexData.uvs = [];
  23142. var currentVertexDataIndex = 0;
  23143. var extractDecalVector3 = function (indexId) {
  23144. var vertexId = indices[indexId];
  23145. var result = new BABYLON.PositionNormalVertex();
  23146. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  23147. // Send vector to decal local world
  23148. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  23149. // Get normal
  23150. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  23151. return result;
  23152. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  23153. var clip = function (vertices, axis) {
  23154. if (vertices.length === 0) {
  23155. return vertices;
  23156. }
  23157. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  23158. var clipVertices = function (v0, v1) {
  23159. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  23160. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  23161. };
  23162. var result = new Array();
  23163. for (var index = 0; index < vertices.length; index += 3) {
  23164. var v1Out;
  23165. var v2Out;
  23166. var v3Out;
  23167. var total = 0;
  23168. var nV1, nV2, nV3, nV4;
  23169. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  23170. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  23171. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  23172. v1Out = d1 > 0;
  23173. v2Out = d2 > 0;
  23174. v3Out = d3 > 0;
  23175. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  23176. switch (total) {
  23177. case 0:
  23178. result.push(vertices[index]);
  23179. result.push(vertices[index + 1]);
  23180. result.push(vertices[index + 2]);
  23181. break;
  23182. case 1:
  23183. if (v1Out) {
  23184. nV1 = vertices[index + 1];
  23185. nV2 = vertices[index + 2];
  23186. nV3 = clipVertices(vertices[index], nV1);
  23187. nV4 = clipVertices(vertices[index], nV2);
  23188. }
  23189. if (v2Out) {
  23190. nV1 = vertices[index];
  23191. nV2 = vertices[index + 2];
  23192. nV3 = clipVertices(vertices[index + 1], nV1);
  23193. nV4 = clipVertices(vertices[index + 1], nV2);
  23194. result.push(nV3);
  23195. result.push(nV2.clone());
  23196. result.push(nV1.clone());
  23197. result.push(nV2.clone());
  23198. result.push(nV3.clone());
  23199. result.push(nV4);
  23200. break;
  23201. }
  23202. if (v3Out) {
  23203. nV1 = vertices[index];
  23204. nV2 = vertices[index + 1];
  23205. nV3 = clipVertices(vertices[index + 2], nV1);
  23206. nV4 = clipVertices(vertices[index + 2], nV2);
  23207. }
  23208. result.push(nV1.clone());
  23209. result.push(nV2.clone());
  23210. result.push(nV3);
  23211. result.push(nV4);
  23212. result.push(nV3.clone());
  23213. result.push(nV2.clone());
  23214. break;
  23215. case 2:
  23216. if (!v1Out) {
  23217. nV1 = vertices[index].clone();
  23218. nV2 = clipVertices(nV1, vertices[index + 1]);
  23219. nV3 = clipVertices(nV1, vertices[index + 2]);
  23220. result.push(nV1);
  23221. result.push(nV2);
  23222. result.push(nV3);
  23223. }
  23224. if (!v2Out) {
  23225. nV1 = vertices[index + 1].clone();
  23226. nV2 = clipVertices(nV1, vertices[index + 2]);
  23227. nV3 = clipVertices(nV1, vertices[index]);
  23228. result.push(nV1);
  23229. result.push(nV2);
  23230. result.push(nV3);
  23231. }
  23232. if (!v3Out) {
  23233. nV1 = vertices[index + 2].clone();
  23234. nV2 = clipVertices(nV1, vertices[index]);
  23235. nV3 = clipVertices(nV1, vertices[index + 1]);
  23236. result.push(nV1);
  23237. result.push(nV2);
  23238. result.push(nV3);
  23239. }
  23240. break;
  23241. case 3:
  23242. break;
  23243. }
  23244. }
  23245. return result;
  23246. };
  23247. for (var index = 0; index < indices.length; index += 3) {
  23248. var faceVertices = new Array();
  23249. faceVertices.push(extractDecalVector3(index));
  23250. faceVertices.push(extractDecalVector3(index + 1));
  23251. faceVertices.push(extractDecalVector3(index + 2));
  23252. // Clip
  23253. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  23254. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  23255. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  23256. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  23257. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  23258. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  23259. if (faceVertices.length === 0) {
  23260. continue;
  23261. }
  23262. // Add UVs and get back to world
  23263. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  23264. var vertex = faceVertices[vIndex];
  23265. //TODO check for Int32Array
  23266. vertexData.indices.push(currentVertexDataIndex);
  23267. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  23268. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  23269. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  23270. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  23271. currentVertexDataIndex++;
  23272. }
  23273. }
  23274. // Return mesh
  23275. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  23276. vertexData.applyToMesh(decal);
  23277. decal.position = position.clone();
  23278. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  23279. return decal;
  23280. };
  23281. // Privates
  23282. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  23283. // extrusion geometry
  23284. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  23285. var tangents = path3D.getTangents();
  23286. var normals = path3D.getNormals();
  23287. var binormals = path3D.getBinormals();
  23288. var distances = path3D.getDistances();
  23289. var angle = 0;
  23290. var returnScale = function () { return scale; };
  23291. var returnRotation = function () { return rotation; };
  23292. var rotate = custom ? rotateFunction : returnRotation;
  23293. var scl = custom ? scaleFunction : returnScale;
  23294. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  23295. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  23296. for (var i = 0; i < curve.length; i++) {
  23297. var shapePath = new Array();
  23298. var angleStep = rotate(i, distances[i]);
  23299. var scaleRatio = scl(i, distances[i]);
  23300. for (var p = 0; p < shape.length; p++) {
  23301. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  23302. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  23303. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  23304. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  23305. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  23306. shapePath[p] = rotated;
  23307. }
  23308. shapePaths[index] = shapePath;
  23309. angle += angleStep;
  23310. index++;
  23311. }
  23312. // cap
  23313. var capPath = function (shapePath) {
  23314. var pointCap = Array();
  23315. var barycenter = BABYLON.Vector3.Zero();
  23316. var i;
  23317. for (i = 0; i < shapePath.length; i++) {
  23318. barycenter.addInPlace(shapePath[i]);
  23319. }
  23320. barycenter.scaleInPlace(1 / shapePath.length);
  23321. for (i = 0; i < shapePath.length; i++) {
  23322. pointCap.push(barycenter);
  23323. }
  23324. return pointCap;
  23325. };
  23326. switch (cap) {
  23327. case BABYLON.Mesh.NO_CAP:
  23328. break;
  23329. case BABYLON.Mesh.CAP_START:
  23330. shapePaths[0] = capPath(shapePaths[2]);
  23331. shapePaths[1] = shapePaths[2].slice(0);
  23332. break;
  23333. case BABYLON.Mesh.CAP_END:
  23334. shapePaths[index] = shapePaths[index - 1];
  23335. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  23336. break;
  23337. case BABYLON.Mesh.CAP_ALL:
  23338. shapePaths[0] = capPath(shapePaths[2]);
  23339. shapePaths[1] = shapePaths[2].slice(0);
  23340. shapePaths[index] = shapePaths[index - 1];
  23341. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  23342. break;
  23343. default:
  23344. break;
  23345. }
  23346. return shapePaths;
  23347. };
  23348. var path3D;
  23349. var pathArray;
  23350. if (instance) {
  23351. path3D = (instance.path3D).update(curve);
  23352. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  23353. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  23354. return instance;
  23355. }
  23356. // extruded shape creation
  23357. path3D = new BABYLON.Path3D(curve);
  23358. var newShapePaths = new Array();
  23359. cap = (cap < 0 || cap > 3) ? 0 : cap;
  23360. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  23361. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  23362. extrudedGeneric.pathArray = pathArray;
  23363. extrudedGeneric.path3D = path3D;
  23364. extrudedGeneric.cap = cap;
  23365. return extrudedGeneric;
  23366. };
  23367. return MeshBuilder;
  23368. }());
  23369. BABYLON.MeshBuilder = MeshBuilder;
  23370. })(BABYLON || (BABYLON = {}));
  23371. //# sourceMappingURL=babylon.meshBuilder.js.map
  23372. var BABYLON;
  23373. (function (BABYLON) {
  23374. var BaseTexture = (function () {
  23375. function BaseTexture(scene) {
  23376. this.hasAlpha = false;
  23377. this.getAlphaFromRGB = false;
  23378. this.level = 1;
  23379. this.coordinatesIndex = 0;
  23380. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  23381. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23382. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23383. this.anisotropicFilteringLevel = 4;
  23384. this.isCube = false;
  23385. this.isRenderTarget = false;
  23386. this.animations = new Array();
  23387. /**
  23388. * An event triggered when the texture is disposed.
  23389. * @type {BABYLON.Observable}
  23390. */
  23391. this.onDisposeObservable = new BABYLON.Observable();
  23392. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23393. this._scene = scene;
  23394. this._scene.textures.push(this);
  23395. this._uid = null;
  23396. }
  23397. Object.defineProperty(BaseTexture.prototype, "uid", {
  23398. get: function () {
  23399. if (!this._uid) {
  23400. this._uid = BABYLON.Tools.RandomId();
  23401. }
  23402. return this._uid;
  23403. },
  23404. enumerable: true,
  23405. configurable: true
  23406. });
  23407. BaseTexture.prototype.toString = function () {
  23408. return this.name;
  23409. };
  23410. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  23411. set: function (callback) {
  23412. if (this._onDisposeObserver) {
  23413. this.onDisposeObservable.remove(this._onDisposeObserver);
  23414. }
  23415. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23416. },
  23417. enumerable: true,
  23418. configurable: true
  23419. });
  23420. BaseTexture.prototype.getScene = function () {
  23421. return this._scene;
  23422. };
  23423. BaseTexture.prototype.getTextureMatrix = function () {
  23424. return null;
  23425. };
  23426. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  23427. return null;
  23428. };
  23429. BaseTexture.prototype.getInternalTexture = function () {
  23430. return this._texture;
  23431. };
  23432. BaseTexture.prototype.isReady = function () {
  23433. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23434. return true;
  23435. }
  23436. if (this._texture) {
  23437. return this._texture.isReady;
  23438. }
  23439. return false;
  23440. };
  23441. BaseTexture.prototype.getSize = function () {
  23442. if (this._texture._width) {
  23443. return new BABYLON.Size(this._texture._width, this._texture._height);
  23444. }
  23445. if (this._texture._size) {
  23446. return new BABYLON.Size(this._texture._size, this._texture._size);
  23447. }
  23448. return BABYLON.Size.Zero();
  23449. };
  23450. BaseTexture.prototype.getBaseSize = function () {
  23451. if (!this.isReady() || !this._texture)
  23452. return BABYLON.Size.Zero();
  23453. if (this._texture._size) {
  23454. return new BABYLON.Size(this._texture._size, this._texture._size);
  23455. }
  23456. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  23457. };
  23458. BaseTexture.prototype.scale = function (ratio) {
  23459. };
  23460. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  23461. get: function () {
  23462. return false;
  23463. },
  23464. enumerable: true,
  23465. configurable: true
  23466. });
  23467. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  23468. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  23469. for (var index = 0; index < texturesCache.length; index++) {
  23470. var texturesCacheEntry = texturesCache[index];
  23471. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  23472. texturesCache.splice(index, 1);
  23473. return;
  23474. }
  23475. }
  23476. };
  23477. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  23478. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  23479. for (var index = 0; index < texturesCache.length; index++) {
  23480. var texturesCacheEntry = texturesCache[index];
  23481. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  23482. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  23483. texturesCacheEntry.references++;
  23484. return texturesCacheEntry;
  23485. }
  23486. }
  23487. }
  23488. return null;
  23489. };
  23490. BaseTexture.prototype.delayLoad = function () {
  23491. };
  23492. BaseTexture.prototype.clone = function () {
  23493. return null;
  23494. };
  23495. BaseTexture.prototype.releaseInternalTexture = function () {
  23496. if (this._texture) {
  23497. this._scene.getEngine().releaseInternalTexture(this._texture);
  23498. delete this._texture;
  23499. }
  23500. };
  23501. BaseTexture.prototype.dispose = function () {
  23502. // Animations
  23503. this.getScene().stopAnimation(this);
  23504. // Remove from scene
  23505. var index = this._scene.textures.indexOf(this);
  23506. if (index >= 0) {
  23507. this._scene.textures.splice(index, 1);
  23508. }
  23509. if (this._texture === undefined) {
  23510. return;
  23511. }
  23512. // Release
  23513. this.releaseInternalTexture();
  23514. // Callback
  23515. this.onDisposeObservable.notifyObservers(this);
  23516. this.onDisposeObservable.clear();
  23517. };
  23518. BaseTexture.prototype.serialize = function () {
  23519. if (!this.name) {
  23520. return null;
  23521. }
  23522. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23523. // Animations
  23524. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23525. return serializationObject;
  23526. };
  23527. return BaseTexture;
  23528. }());
  23529. __decorate([
  23530. BABYLON.serialize()
  23531. ], BaseTexture.prototype, "name", void 0);
  23532. __decorate([
  23533. BABYLON.serialize()
  23534. ], BaseTexture.prototype, "hasAlpha", void 0);
  23535. __decorate([
  23536. BABYLON.serialize()
  23537. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  23538. __decorate([
  23539. BABYLON.serialize()
  23540. ], BaseTexture.prototype, "level", void 0);
  23541. __decorate([
  23542. BABYLON.serialize()
  23543. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  23544. __decorate([
  23545. BABYLON.serialize()
  23546. ], BaseTexture.prototype, "coordinatesMode", void 0);
  23547. __decorate([
  23548. BABYLON.serialize()
  23549. ], BaseTexture.prototype, "wrapU", void 0);
  23550. __decorate([
  23551. BABYLON.serialize()
  23552. ], BaseTexture.prototype, "wrapV", void 0);
  23553. __decorate([
  23554. BABYLON.serialize()
  23555. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  23556. __decorate([
  23557. BABYLON.serialize()
  23558. ], BaseTexture.prototype, "isCube", void 0);
  23559. __decorate([
  23560. BABYLON.serialize()
  23561. ], BaseTexture.prototype, "isRenderTarget", void 0);
  23562. BABYLON.BaseTexture = BaseTexture;
  23563. })(BABYLON || (BABYLON = {}));
  23564. //# sourceMappingURL=babylon.baseTexture.js.map
  23565. var BABYLON;
  23566. (function (BABYLON) {
  23567. var Texture = (function (_super) {
  23568. __extends(Texture, _super);
  23569. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  23570. if (noMipmap === void 0) { noMipmap = false; }
  23571. if (invertY === void 0) { invertY = true; }
  23572. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23573. if (onLoad === void 0) { onLoad = null; }
  23574. if (onError === void 0) { onError = null; }
  23575. if (buffer === void 0) { buffer = null; }
  23576. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23577. var _this = _super.call(this, scene) || this;
  23578. _this.uOffset = 0;
  23579. _this.vOffset = 0;
  23580. _this.uScale = 1.0;
  23581. _this.vScale = 1.0;
  23582. _this.uAng = 0;
  23583. _this.vAng = 0;
  23584. _this.wAng = 0;
  23585. _this.name = url;
  23586. _this.url = url;
  23587. _this._noMipmap = noMipmap;
  23588. _this._invertY = invertY;
  23589. _this._samplingMode = samplingMode;
  23590. _this._buffer = buffer;
  23591. _this._deleteBuffer = deleteBuffer;
  23592. if (!url) {
  23593. return _this;
  23594. }
  23595. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  23596. var load = function () {
  23597. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  23598. _this.onLoadObservable.notifyObservers(true);
  23599. }
  23600. if (onLoad) {
  23601. onLoad();
  23602. }
  23603. };
  23604. if (!_this._texture) {
  23605. if (!scene.useDelayedTextureLoading) {
  23606. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer);
  23607. if (deleteBuffer) {
  23608. delete _this._buffer;
  23609. }
  23610. }
  23611. else {
  23612. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23613. _this._delayedOnLoad = load;
  23614. _this._delayedOnError = onError;
  23615. }
  23616. }
  23617. else {
  23618. if (_this._texture.isReady) {
  23619. BABYLON.Tools.SetImmediate(function () { return load(); });
  23620. }
  23621. else {
  23622. _this._texture.onLoadedCallbacks.push(load);
  23623. }
  23624. }
  23625. return _this;
  23626. }
  23627. Object.defineProperty(Texture.prototype, "noMipmap", {
  23628. get: function () {
  23629. return this._noMipmap;
  23630. },
  23631. enumerable: true,
  23632. configurable: true
  23633. });
  23634. Texture.prototype.delayLoad = function () {
  23635. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23636. return;
  23637. }
  23638. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23639. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  23640. if (!this._texture) {
  23641. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  23642. if (this._deleteBuffer) {
  23643. delete this._buffer;
  23644. }
  23645. }
  23646. };
  23647. Texture.prototype.updateSamplingMode = function (samplingMode) {
  23648. if (!this._texture) {
  23649. return;
  23650. }
  23651. this._samplingMode = samplingMode;
  23652. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  23653. };
  23654. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  23655. x *= this.uScale;
  23656. y *= this.vScale;
  23657. x -= 0.5 * this.uScale;
  23658. y -= 0.5 * this.vScale;
  23659. z -= 0.5;
  23660. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  23661. t.x += 0.5 * this.uScale + this.uOffset;
  23662. t.y += 0.5 * this.vScale + this.vOffset;
  23663. t.z += 0.5;
  23664. };
  23665. Texture.prototype.getTextureMatrix = function () {
  23666. if (this.uOffset === this._cachedUOffset &&
  23667. this.vOffset === this._cachedVOffset &&
  23668. this.uScale === this._cachedUScale &&
  23669. this.vScale === this._cachedVScale &&
  23670. this.uAng === this._cachedUAng &&
  23671. this.vAng === this._cachedVAng &&
  23672. this.wAng === this._cachedWAng) {
  23673. return this._cachedTextureMatrix;
  23674. }
  23675. this._cachedUOffset = this.uOffset;
  23676. this._cachedVOffset = this.vOffset;
  23677. this._cachedUScale = this.uScale;
  23678. this._cachedVScale = this.vScale;
  23679. this._cachedUAng = this.uAng;
  23680. this._cachedVAng = this.vAng;
  23681. this._cachedWAng = this.wAng;
  23682. if (!this._cachedTextureMatrix) {
  23683. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23684. this._rowGenerationMatrix = new BABYLON.Matrix();
  23685. this._t0 = BABYLON.Vector3.Zero();
  23686. this._t1 = BABYLON.Vector3.Zero();
  23687. this._t2 = BABYLON.Vector3.Zero();
  23688. }
  23689. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  23690. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  23691. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  23692. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  23693. this._t1.subtractInPlace(this._t0);
  23694. this._t2.subtractInPlace(this._t0);
  23695. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23696. this._cachedTextureMatrix.m[0] = this._t1.x;
  23697. this._cachedTextureMatrix.m[1] = this._t1.y;
  23698. this._cachedTextureMatrix.m[2] = this._t1.z;
  23699. this._cachedTextureMatrix.m[4] = this._t2.x;
  23700. this._cachedTextureMatrix.m[5] = this._t2.y;
  23701. this._cachedTextureMatrix.m[6] = this._t2.z;
  23702. this._cachedTextureMatrix.m[8] = this._t0.x;
  23703. this._cachedTextureMatrix.m[9] = this._t0.y;
  23704. this._cachedTextureMatrix.m[10] = this._t0.z;
  23705. return this._cachedTextureMatrix;
  23706. };
  23707. Texture.prototype.getReflectionTextureMatrix = function () {
  23708. if (this.uOffset === this._cachedUOffset &&
  23709. this.vOffset === this._cachedVOffset &&
  23710. this.uScale === this._cachedUScale &&
  23711. this.vScale === this._cachedVScale &&
  23712. this.coordinatesMode === this._cachedCoordinatesMode) {
  23713. return this._cachedTextureMatrix;
  23714. }
  23715. if (!this._cachedTextureMatrix) {
  23716. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23717. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  23718. }
  23719. this._cachedCoordinatesMode = this.coordinatesMode;
  23720. switch (this.coordinatesMode) {
  23721. case Texture.PLANAR_MODE:
  23722. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23723. this._cachedTextureMatrix[0] = this.uScale;
  23724. this._cachedTextureMatrix[5] = this.vScale;
  23725. this._cachedTextureMatrix[12] = this.uOffset;
  23726. this._cachedTextureMatrix[13] = this.vOffset;
  23727. break;
  23728. case Texture.PROJECTION_MODE:
  23729. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  23730. this._projectionModeMatrix.m[0] = 0.5;
  23731. this._projectionModeMatrix.m[5] = -0.5;
  23732. this._projectionModeMatrix.m[10] = 0.0;
  23733. this._projectionModeMatrix.m[12] = 0.5;
  23734. this._projectionModeMatrix.m[13] = 0.5;
  23735. this._projectionModeMatrix.m[14] = 1.0;
  23736. this._projectionModeMatrix.m[15] = 1.0;
  23737. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  23738. break;
  23739. default:
  23740. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23741. break;
  23742. }
  23743. return this._cachedTextureMatrix;
  23744. };
  23745. Texture.prototype.clone = function () {
  23746. var _this = this;
  23747. return BABYLON.SerializationHelper.Clone(function () {
  23748. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  23749. }, this);
  23750. };
  23751. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  23752. get: function () {
  23753. if (!this._onLoadObservarble) {
  23754. this._onLoadObservarble = new BABYLON.Observable();
  23755. }
  23756. return this._onLoadObservarble;
  23757. },
  23758. enumerable: true,
  23759. configurable: true
  23760. });
  23761. // Statics
  23762. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  23763. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23764. if (onLoad === void 0) { onLoad = null; }
  23765. if (onError === void 0) { onError = null; }
  23766. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  23767. };
  23768. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  23769. if (parsedTexture.customType) {
  23770. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  23771. return customTexture.Parse(parsedTexture, scene, rootUrl);
  23772. }
  23773. if (parsedTexture.isCube) {
  23774. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  23775. }
  23776. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  23777. return null;
  23778. }
  23779. var texture = BABYLON.SerializationHelper.Parse(function () {
  23780. if (parsedTexture.mirrorPlane) {
  23781. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  23782. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  23783. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  23784. return mirrorTexture;
  23785. }
  23786. else if (parsedTexture.isRenderTarget) {
  23787. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  23788. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  23789. return renderTargetTexture;
  23790. }
  23791. else {
  23792. var texture;
  23793. if (parsedTexture.base64String) {
  23794. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  23795. }
  23796. else {
  23797. texture = new Texture(rootUrl + parsedTexture.name, scene);
  23798. }
  23799. return texture;
  23800. }
  23801. }, parsedTexture, scene);
  23802. // Animations
  23803. if (parsedTexture.animations) {
  23804. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23805. var parsedAnimation = parsedTexture.animations[animationIndex];
  23806. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23807. }
  23808. }
  23809. return texture;
  23810. };
  23811. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError) {
  23812. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23813. if (noMipmap === void 0) { noMipmap = false; }
  23814. if (invertY === void 0) { invertY = true; }
  23815. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23816. if (onLoad === void 0) { onLoad = null; }
  23817. if (onError === void 0) { onError = null; }
  23818. if (name.substr(0, 5) !== "data:") {
  23819. name = "data:" + name;
  23820. }
  23821. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer);
  23822. };
  23823. return Texture;
  23824. }(BABYLON.BaseTexture));
  23825. // Constants
  23826. Texture.NEAREST_SAMPLINGMODE = 1;
  23827. Texture.BILINEAR_SAMPLINGMODE = 2;
  23828. Texture.TRILINEAR_SAMPLINGMODE = 3;
  23829. Texture.EXPLICIT_MODE = 0;
  23830. Texture.SPHERICAL_MODE = 1;
  23831. Texture.PLANAR_MODE = 2;
  23832. Texture.CUBIC_MODE = 3;
  23833. Texture.PROJECTION_MODE = 4;
  23834. Texture.SKYBOX_MODE = 5;
  23835. Texture.INVCUBIC_MODE = 6;
  23836. Texture.EQUIRECTANGULAR_MODE = 7;
  23837. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  23838. Texture.CLAMP_ADDRESSMODE = 0;
  23839. Texture.WRAP_ADDRESSMODE = 1;
  23840. Texture.MIRROR_ADDRESSMODE = 2;
  23841. __decorate([
  23842. BABYLON.serialize()
  23843. ], Texture.prototype, "url", void 0);
  23844. __decorate([
  23845. BABYLON.serialize()
  23846. ], Texture.prototype, "uOffset", void 0);
  23847. __decorate([
  23848. BABYLON.serialize()
  23849. ], Texture.prototype, "vOffset", void 0);
  23850. __decorate([
  23851. BABYLON.serialize()
  23852. ], Texture.prototype, "uScale", void 0);
  23853. __decorate([
  23854. BABYLON.serialize()
  23855. ], Texture.prototype, "vScale", void 0);
  23856. __decorate([
  23857. BABYLON.serialize()
  23858. ], Texture.prototype, "uAng", void 0);
  23859. __decorate([
  23860. BABYLON.serialize()
  23861. ], Texture.prototype, "vAng", void 0);
  23862. __decorate([
  23863. BABYLON.serialize()
  23864. ], Texture.prototype, "wAng", void 0);
  23865. BABYLON.Texture = Texture;
  23866. })(BABYLON || (BABYLON = {}));
  23867. //# sourceMappingURL=babylon.texture.js.map
  23868. var BABYLON;
  23869. (function (BABYLON) {
  23870. var CubeTexture = (function (_super) {
  23871. __extends(CubeTexture, _super);
  23872. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError) {
  23873. if (onLoad === void 0) { onLoad = null; }
  23874. if (onError === void 0) { onError = null; }
  23875. var _this = _super.call(this, scene) || this;
  23876. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  23877. _this.name = rootUrl;
  23878. _this.url = rootUrl;
  23879. _this._noMipmap = noMipmap;
  23880. _this.hasAlpha = false;
  23881. if (!rootUrl && !files) {
  23882. return _this;
  23883. }
  23884. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  23885. if (!files) {
  23886. if (!extensions) {
  23887. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  23888. }
  23889. files = [];
  23890. for (var index = 0; index < extensions.length; index++) {
  23891. files.push(rootUrl + extensions[index]);
  23892. }
  23893. _this._extensions = extensions;
  23894. }
  23895. _this._files = files;
  23896. if (!_this._texture) {
  23897. if (!scene.useDelayedTextureLoading) {
  23898. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError);
  23899. }
  23900. else {
  23901. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23902. }
  23903. }
  23904. else if (onLoad) {
  23905. if (_this._texture.isReady) {
  23906. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  23907. }
  23908. else {
  23909. _this._texture.onLoadedCallbacks.push(onLoad);
  23910. }
  23911. }
  23912. _this.isCube = true;
  23913. _this._textureMatrix = BABYLON.Matrix.Identity();
  23914. return _this;
  23915. }
  23916. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  23917. return new CubeTexture("", scene, null, noMipmap, files);
  23918. };
  23919. // Methods
  23920. CubeTexture.prototype.delayLoad = function () {
  23921. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23922. return;
  23923. }
  23924. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23925. this._texture = this._getFromCache(this.url, this._noMipmap);
  23926. if (!this._texture) {
  23927. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  23928. }
  23929. };
  23930. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  23931. return this._textureMatrix;
  23932. };
  23933. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  23934. var texture = BABYLON.SerializationHelper.Parse(function () {
  23935. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  23936. }, parsedTexture, scene);
  23937. // Animations
  23938. if (parsedTexture.animations) {
  23939. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23940. var parsedAnimation = parsedTexture.animations[animationIndex];
  23941. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23942. }
  23943. }
  23944. return texture;
  23945. };
  23946. CubeTexture.prototype.clone = function () {
  23947. var _this = this;
  23948. return BABYLON.SerializationHelper.Clone(function () {
  23949. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  23950. }, this);
  23951. };
  23952. return CubeTexture;
  23953. }(BABYLON.BaseTexture));
  23954. BABYLON.CubeTexture = CubeTexture;
  23955. })(BABYLON || (BABYLON = {}));
  23956. //# sourceMappingURL=babylon.cubeTexture.js.map
  23957. var BABYLON;
  23958. (function (BABYLON) {
  23959. var RenderTargetTexture = (function (_super) {
  23960. __extends(RenderTargetTexture, _super);
  23961. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  23962. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  23963. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23964. if (isCube === void 0) { isCube = false; }
  23965. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23966. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  23967. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  23968. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  23969. _this.isCube = isCube;
  23970. /**
  23971. * Use this list to define the list of mesh you want to render.
  23972. */
  23973. _this.renderList = new Array();
  23974. _this.renderParticles = true;
  23975. _this.renderSprites = false;
  23976. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  23977. // Events
  23978. /**
  23979. * An event triggered when the texture is unbind.
  23980. * @type {BABYLON.Observable}
  23981. */
  23982. _this.onAfterUnbindObservable = new BABYLON.Observable();
  23983. /**
  23984. * An event triggered before rendering the texture
  23985. * @type {BABYLON.Observable}
  23986. */
  23987. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23988. /**
  23989. * An event triggered after rendering the texture
  23990. * @type {BABYLON.Observable}
  23991. */
  23992. _this.onAfterRenderObservable = new BABYLON.Observable();
  23993. /**
  23994. * An event triggered after the texture clear
  23995. * @type {BABYLON.Observable}
  23996. */
  23997. _this.onClearObservable = new BABYLON.Observable();
  23998. _this._currentRefreshId = -1;
  23999. _this._refreshRate = 1;
  24000. _this.name = name;
  24001. _this.isRenderTarget = true;
  24002. _this._size = size;
  24003. _this._generateMipMaps = generateMipMaps;
  24004. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  24005. _this._renderTargetOptions = {
  24006. generateMipMaps: generateMipMaps,
  24007. type: type,
  24008. samplingMode: samplingMode,
  24009. generateDepthBuffer: generateDepthBuffer,
  24010. generateStencilBuffer: generateStencilBuffer
  24011. };
  24012. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  24013. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24014. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24015. }
  24016. if (isCube) {
  24017. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  24018. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  24019. _this._textureMatrix = BABYLON.Matrix.Identity();
  24020. }
  24021. else {
  24022. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  24023. }
  24024. // Rendering groups
  24025. _this._renderingManager = new BABYLON.RenderingManager(scene);
  24026. return _this;
  24027. }
  24028. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  24029. get: function () {
  24030. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  24031. },
  24032. enumerable: true,
  24033. configurable: true
  24034. });
  24035. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  24036. get: function () {
  24037. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  24038. },
  24039. enumerable: true,
  24040. configurable: true
  24041. });
  24042. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  24043. get: function () {
  24044. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  24045. },
  24046. enumerable: true,
  24047. configurable: true
  24048. });
  24049. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  24050. set: function (callback) {
  24051. if (this._onAfterUnbindObserver) {
  24052. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  24053. }
  24054. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  24055. },
  24056. enumerable: true,
  24057. configurable: true
  24058. });
  24059. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  24060. set: function (callback) {
  24061. if (this._onBeforeRenderObserver) {
  24062. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24063. }
  24064. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24065. },
  24066. enumerable: true,
  24067. configurable: true
  24068. });
  24069. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  24070. set: function (callback) {
  24071. if (this._onAfterRenderObserver) {
  24072. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24073. }
  24074. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24075. },
  24076. enumerable: true,
  24077. configurable: true
  24078. });
  24079. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  24080. set: function (callback) {
  24081. if (this._onClearObserver) {
  24082. this.onClearObservable.remove(this._onClearObserver);
  24083. }
  24084. this._onClearObserver = this.onClearObservable.add(callback);
  24085. },
  24086. enumerable: true,
  24087. configurable: true
  24088. });
  24089. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  24090. this._currentRefreshId = -1;
  24091. };
  24092. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  24093. get: function () {
  24094. return this._refreshRate;
  24095. },
  24096. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  24097. set: function (value) {
  24098. this._refreshRate = value;
  24099. this.resetRefreshCounter();
  24100. },
  24101. enumerable: true,
  24102. configurable: true
  24103. });
  24104. RenderTargetTexture.prototype._shouldRender = function () {
  24105. if (this._currentRefreshId === -1) {
  24106. this._currentRefreshId = 1;
  24107. return true;
  24108. }
  24109. if (this.refreshRate === this._currentRefreshId) {
  24110. this._currentRefreshId = 1;
  24111. return true;
  24112. }
  24113. this._currentRefreshId++;
  24114. return false;
  24115. };
  24116. RenderTargetTexture.prototype.isReady = function () {
  24117. if (!this.getScene().renderTargetsEnabled) {
  24118. return false;
  24119. }
  24120. return _super.prototype.isReady.call(this);
  24121. };
  24122. RenderTargetTexture.prototype.getRenderSize = function () {
  24123. return this._size;
  24124. };
  24125. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  24126. get: function () {
  24127. return true;
  24128. },
  24129. enumerable: true,
  24130. configurable: true
  24131. });
  24132. RenderTargetTexture.prototype.scale = function (ratio) {
  24133. var newSize = this._size * ratio;
  24134. this.resize(newSize);
  24135. };
  24136. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  24137. if (this.isCube) {
  24138. return this._textureMatrix;
  24139. }
  24140. return _super.prototype.getReflectionTextureMatrix.call(this);
  24141. };
  24142. RenderTargetTexture.prototype.resize = function (size) {
  24143. this.releaseInternalTexture();
  24144. if (this.isCube) {
  24145. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  24146. }
  24147. else {
  24148. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  24149. }
  24150. };
  24151. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  24152. var scene = this.getScene();
  24153. var engine = scene.getEngine();
  24154. if (this.useCameraPostProcesses !== undefined) {
  24155. useCameraPostProcess = this.useCameraPostProcesses;
  24156. }
  24157. if (this._waitingRenderList) {
  24158. this.renderList = [];
  24159. for (var index = 0; index < this._waitingRenderList.length; index++) {
  24160. var id = this._waitingRenderList[index];
  24161. this.renderList.push(scene.getMeshByID(id));
  24162. }
  24163. delete this._waitingRenderList;
  24164. }
  24165. // Is predicate defined?
  24166. if (this.renderListPredicate) {
  24167. this.renderList.splice(0); // Clear previous renderList
  24168. var sceneMeshes = this.getScene().meshes;
  24169. for (var index = 0; index < sceneMeshes.length; index++) {
  24170. var mesh = sceneMeshes[index];
  24171. if (this.renderListPredicate(mesh)) {
  24172. this.renderList.push(mesh);
  24173. }
  24174. }
  24175. }
  24176. if (this.renderList && this.renderList.length === 0) {
  24177. return;
  24178. }
  24179. // Set custom projection.
  24180. // Needs to be before binding to prevent changing the aspect ratio.
  24181. if (this.activeCamera) {
  24182. engine.setViewport(this.activeCamera.viewport);
  24183. if (this.activeCamera !== scene.activeCamera) {
  24184. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  24185. }
  24186. }
  24187. else {
  24188. engine.setViewport(scene.activeCamera.viewport);
  24189. }
  24190. // Prepare renderingManager
  24191. this._renderingManager.reset();
  24192. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  24193. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  24194. var sceneRenderId = scene.getRenderId();
  24195. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  24196. var mesh = currentRenderList[meshIndex];
  24197. if (mesh) {
  24198. if (!mesh.isReady()) {
  24199. // Reset _currentRefreshId
  24200. this.resetRefreshCounter();
  24201. continue;
  24202. }
  24203. mesh._preActivateForIntermediateRendering(sceneRenderId);
  24204. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  24205. mesh._activate(sceneRenderId);
  24206. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24207. var subMesh = mesh.subMeshes[subIndex];
  24208. scene._activeIndices.addCount(subMesh.indexCount, false);
  24209. this._renderingManager.dispatch(subMesh);
  24210. }
  24211. }
  24212. }
  24213. }
  24214. if (this.isCube) {
  24215. for (var face = 0; face < 6; face++) {
  24216. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  24217. scene.incrementRenderId();
  24218. scene.resetCachedMaterial();
  24219. }
  24220. }
  24221. else {
  24222. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  24223. }
  24224. this.onAfterUnbindObservable.notifyObservers(this);
  24225. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  24226. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  24227. }
  24228. engine.setViewport(scene.activeCamera.viewport);
  24229. scene.resetCachedMaterial();
  24230. };
  24231. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  24232. var scene = this.getScene();
  24233. var engine = scene.getEngine();
  24234. // Bind
  24235. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  24236. if (this.isCube) {
  24237. engine.bindFramebuffer(this._texture, faceIndex);
  24238. }
  24239. else {
  24240. engine.bindFramebuffer(this._texture);
  24241. }
  24242. }
  24243. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  24244. // Clear
  24245. if (this.onClearObservable.hasObservers()) {
  24246. this.onClearObservable.notifyObservers(engine);
  24247. }
  24248. else {
  24249. engine.clear(scene.clearColor, true, true, true);
  24250. }
  24251. if (!this._doNotChangeAspectRatio) {
  24252. scene.updateTransformMatrix(true);
  24253. }
  24254. // Render
  24255. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  24256. if (useCameraPostProcess) {
  24257. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  24258. }
  24259. if (!this._doNotChangeAspectRatio) {
  24260. scene.updateTransformMatrix(true);
  24261. }
  24262. this.onAfterRenderObservable.notifyObservers(faceIndex);
  24263. // Dump ?
  24264. if (dumpForDebug) {
  24265. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  24266. }
  24267. // Unbind
  24268. if (!this.isCube || faceIndex === 5) {
  24269. if (this.isCube) {
  24270. if (faceIndex === 5) {
  24271. engine.generateMipMapsForCubemap(this._texture);
  24272. }
  24273. }
  24274. engine.unBindFramebuffer(this._texture, this.isCube);
  24275. }
  24276. };
  24277. /**
  24278. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24279. * This allowed control for front to back rendering or reversly depending of the special needs.
  24280. *
  24281. * @param renderingGroupId The rendering group id corresponding to its index
  24282. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24283. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24284. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24285. */
  24286. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24287. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24288. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24289. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24290. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24291. };
  24292. /**
  24293. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24294. *
  24295. * @param renderingGroupId The rendering group id corresponding to its index
  24296. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24297. */
  24298. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  24299. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  24300. };
  24301. RenderTargetTexture.prototype.clone = function () {
  24302. var textureSize = this.getSize();
  24303. 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);
  24304. // Base texture
  24305. newTexture.hasAlpha = this.hasAlpha;
  24306. newTexture.level = this.level;
  24307. // RenderTarget Texture
  24308. newTexture.coordinatesMode = this.coordinatesMode;
  24309. newTexture.renderList = this.renderList.slice(0);
  24310. return newTexture;
  24311. };
  24312. RenderTargetTexture.prototype.serialize = function () {
  24313. if (!this.name) {
  24314. return null;
  24315. }
  24316. var serializationObject = _super.prototype.serialize.call(this);
  24317. serializationObject.renderTargetSize = this.getRenderSize();
  24318. serializationObject.renderList = [];
  24319. for (var index = 0; index < this.renderList.length; index++) {
  24320. serializationObject.renderList.push(this.renderList[index].id);
  24321. }
  24322. return serializationObject;
  24323. };
  24324. return RenderTargetTexture;
  24325. }(BABYLON.Texture));
  24326. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  24327. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  24328. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  24329. BABYLON.RenderTargetTexture = RenderTargetTexture;
  24330. })(BABYLON || (BABYLON = {}));
  24331. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  24332. var BABYLON;
  24333. (function (BABYLON) {
  24334. var ProceduralTexture = (function (_super) {
  24335. __extends(ProceduralTexture, _super);
  24336. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  24337. if (generateMipMaps === void 0) { generateMipMaps = true; }
  24338. if (isCube === void 0) { isCube = false; }
  24339. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  24340. _this.isCube = isCube;
  24341. _this.isEnabled = true;
  24342. _this._currentRefreshId = -1;
  24343. _this._refreshRate = 1;
  24344. _this._vertexBuffers = {};
  24345. _this._uniforms = new Array();
  24346. _this._samplers = new Array();
  24347. _this._textures = new Array();
  24348. _this._floats = new Array();
  24349. _this._floatsArrays = {};
  24350. _this._colors3 = new Array();
  24351. _this._colors4 = new Array();
  24352. _this._vectors2 = new Array();
  24353. _this._vectors3 = new Array();
  24354. _this._matrices = new Array();
  24355. _this._fallbackTextureUsed = false;
  24356. scene._proceduralTextures.push(_this);
  24357. _this.name = name;
  24358. _this.isRenderTarget = true;
  24359. _this._size = size;
  24360. _this._generateMipMaps = generateMipMaps;
  24361. _this.setFragment(fragment);
  24362. _this._fallbackTexture = fallbackTexture;
  24363. var engine = scene.getEngine();
  24364. if (isCube) {
  24365. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  24366. _this.setFloat("face", 0);
  24367. }
  24368. else {
  24369. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  24370. }
  24371. // VBO
  24372. var vertices = [];
  24373. vertices.push(1, 1);
  24374. vertices.push(-1, 1);
  24375. vertices.push(-1, -1);
  24376. vertices.push(1, -1);
  24377. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  24378. // Indices
  24379. var indices = [];
  24380. indices.push(0);
  24381. indices.push(1);
  24382. indices.push(2);
  24383. indices.push(0);
  24384. indices.push(2);
  24385. indices.push(3);
  24386. _this._indexBuffer = engine.createIndexBuffer(indices);
  24387. return _this;
  24388. }
  24389. ProceduralTexture.prototype.reset = function () {
  24390. if (this._effect === undefined) {
  24391. return;
  24392. }
  24393. var engine = this.getScene().getEngine();
  24394. engine._releaseEffect(this._effect);
  24395. };
  24396. ProceduralTexture.prototype.isReady = function () {
  24397. var _this = this;
  24398. var engine = this.getScene().getEngine();
  24399. var shaders;
  24400. if (!this._fragment) {
  24401. return false;
  24402. }
  24403. if (this._fallbackTextureUsed) {
  24404. return true;
  24405. }
  24406. if (this._fragment.fragmentElement !== undefined) {
  24407. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  24408. }
  24409. else {
  24410. shaders = { vertex: "procedural", fragment: this._fragment };
  24411. }
  24412. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  24413. _this.releaseInternalTexture();
  24414. if (_this._fallbackTexture) {
  24415. _this._texture = _this._fallbackTexture._texture;
  24416. _this._texture.references++;
  24417. }
  24418. _this._fallbackTextureUsed = true;
  24419. });
  24420. return this._effect.isReady();
  24421. };
  24422. ProceduralTexture.prototype.resetRefreshCounter = function () {
  24423. this._currentRefreshId = -1;
  24424. };
  24425. ProceduralTexture.prototype.setFragment = function (fragment) {
  24426. this._fragment = fragment;
  24427. };
  24428. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  24429. get: function () {
  24430. return this._refreshRate;
  24431. },
  24432. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  24433. set: function (value) {
  24434. this._refreshRate = value;
  24435. this.resetRefreshCounter();
  24436. },
  24437. enumerable: true,
  24438. configurable: true
  24439. });
  24440. ProceduralTexture.prototype._shouldRender = function () {
  24441. if (!this.isEnabled || !this.isReady() || !this._texture) {
  24442. return false;
  24443. }
  24444. if (this._fallbackTextureUsed) {
  24445. return false;
  24446. }
  24447. if (this._currentRefreshId === -1) {
  24448. this._currentRefreshId = 1;
  24449. return true;
  24450. }
  24451. if (this.refreshRate === this._currentRefreshId) {
  24452. this._currentRefreshId = 1;
  24453. return true;
  24454. }
  24455. this._currentRefreshId++;
  24456. return false;
  24457. };
  24458. ProceduralTexture.prototype.getRenderSize = function () {
  24459. return this._size;
  24460. };
  24461. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  24462. if (this._fallbackTextureUsed) {
  24463. return;
  24464. }
  24465. this.releaseInternalTexture();
  24466. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  24467. };
  24468. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  24469. if (this._uniforms.indexOf(uniformName) === -1) {
  24470. this._uniforms.push(uniformName);
  24471. }
  24472. };
  24473. ProceduralTexture.prototype.setTexture = function (name, texture) {
  24474. if (this._samplers.indexOf(name) === -1) {
  24475. this._samplers.push(name);
  24476. }
  24477. this._textures[name] = texture;
  24478. return this;
  24479. };
  24480. ProceduralTexture.prototype.setFloat = function (name, value) {
  24481. this._checkUniform(name);
  24482. this._floats[name] = value;
  24483. return this;
  24484. };
  24485. ProceduralTexture.prototype.setFloats = function (name, value) {
  24486. this._checkUniform(name);
  24487. this._floatsArrays[name] = value;
  24488. return this;
  24489. };
  24490. ProceduralTexture.prototype.setColor3 = function (name, value) {
  24491. this._checkUniform(name);
  24492. this._colors3[name] = value;
  24493. return this;
  24494. };
  24495. ProceduralTexture.prototype.setColor4 = function (name, value) {
  24496. this._checkUniform(name);
  24497. this._colors4[name] = value;
  24498. return this;
  24499. };
  24500. ProceduralTexture.prototype.setVector2 = function (name, value) {
  24501. this._checkUniform(name);
  24502. this._vectors2[name] = value;
  24503. return this;
  24504. };
  24505. ProceduralTexture.prototype.setVector3 = function (name, value) {
  24506. this._checkUniform(name);
  24507. this._vectors3[name] = value;
  24508. return this;
  24509. };
  24510. ProceduralTexture.prototype.setMatrix = function (name, value) {
  24511. this._checkUniform(name);
  24512. this._matrices[name] = value;
  24513. return this;
  24514. };
  24515. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  24516. var scene = this.getScene();
  24517. var engine = scene.getEngine();
  24518. // Render
  24519. engine.enableEffect(this._effect);
  24520. engine.setState(false);
  24521. // Texture
  24522. for (var name in this._textures) {
  24523. this._effect.setTexture(name, this._textures[name]);
  24524. }
  24525. // Float
  24526. for (name in this._floats) {
  24527. this._effect.setFloat(name, this._floats[name]);
  24528. }
  24529. // Floats
  24530. for (name in this._floatsArrays) {
  24531. this._effect.setArray(name, this._floatsArrays[name]);
  24532. }
  24533. // Color3
  24534. for (name in this._colors3) {
  24535. this._effect.setColor3(name, this._colors3[name]);
  24536. }
  24537. // Color4
  24538. for (name in this._colors4) {
  24539. var color = this._colors4[name];
  24540. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  24541. }
  24542. // Vector2
  24543. for (name in this._vectors2) {
  24544. this._effect.setVector2(name, this._vectors2[name]);
  24545. }
  24546. // Vector3
  24547. for (name in this._vectors3) {
  24548. this._effect.setVector3(name, this._vectors3[name]);
  24549. }
  24550. // Matrix
  24551. for (name in this._matrices) {
  24552. this._effect.setMatrix(name, this._matrices[name]);
  24553. }
  24554. // VBOs
  24555. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  24556. if (this.isCube) {
  24557. for (var face = 0; face < 6; face++) {
  24558. engine.bindFramebuffer(this._texture, face);
  24559. this._effect.setFloat("face", face);
  24560. // Clear
  24561. engine.clear(scene.clearColor, true, true, true);
  24562. // Draw order
  24563. engine.draw(true, 0, 6);
  24564. // Mipmaps
  24565. if (face === 5) {
  24566. engine.generateMipMapsForCubemap(this._texture);
  24567. }
  24568. }
  24569. }
  24570. else {
  24571. engine.bindFramebuffer(this._texture);
  24572. // Clear
  24573. engine.clear(scene.clearColor, true, true, true);
  24574. // Draw order
  24575. engine.draw(true, 0, 6);
  24576. }
  24577. // Unbind
  24578. engine.unBindFramebuffer(this._texture, this.isCube);
  24579. if (this.onGenerated) {
  24580. this.onGenerated();
  24581. }
  24582. };
  24583. ProceduralTexture.prototype.clone = function () {
  24584. var textureSize = this.getSize();
  24585. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  24586. // Base texture
  24587. newTexture.hasAlpha = this.hasAlpha;
  24588. newTexture.level = this.level;
  24589. // RenderTarget Texture
  24590. newTexture.coordinatesMode = this.coordinatesMode;
  24591. return newTexture;
  24592. };
  24593. ProceduralTexture.prototype.dispose = function () {
  24594. var index = this.getScene()._proceduralTextures.indexOf(this);
  24595. if (index >= 0) {
  24596. this.getScene()._proceduralTextures.splice(index, 1);
  24597. }
  24598. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  24599. if (vertexBuffer) {
  24600. vertexBuffer.dispose();
  24601. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  24602. }
  24603. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  24604. this._indexBuffer = null;
  24605. }
  24606. _super.prototype.dispose.call(this);
  24607. };
  24608. return ProceduralTexture;
  24609. }(BABYLON.Texture));
  24610. BABYLON.ProceduralTexture = ProceduralTexture;
  24611. })(BABYLON || (BABYLON = {}));
  24612. //# sourceMappingURL=babylon.proceduralTexture.js.map
  24613. var BABYLON;
  24614. (function (BABYLON) {
  24615. var MirrorTexture = (function (_super) {
  24616. __extends(MirrorTexture, _super);
  24617. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  24618. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  24619. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  24620. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  24621. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  24622. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  24623. _this._transformMatrix = BABYLON.Matrix.Zero();
  24624. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  24625. _this.onBeforeRenderObservable.add(function () {
  24626. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  24627. _this._savedViewMatrix = scene.getViewMatrix();
  24628. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  24629. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  24630. scene.clipPlane = _this.mirrorPlane;
  24631. scene.getEngine().cullBackFaces = false;
  24632. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  24633. });
  24634. _this.onAfterRenderObservable.add(function () {
  24635. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  24636. scene.getEngine().cullBackFaces = true;
  24637. scene._mirroredCameraPosition = null;
  24638. delete scene.clipPlane;
  24639. });
  24640. return _this;
  24641. }
  24642. MirrorTexture.prototype.clone = function () {
  24643. var textureSize = this.getSize();
  24644. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  24645. // Base texture
  24646. newTexture.hasAlpha = this.hasAlpha;
  24647. newTexture.level = this.level;
  24648. // Mirror Texture
  24649. newTexture.mirrorPlane = this.mirrorPlane.clone();
  24650. newTexture.renderList = this.renderList.slice(0);
  24651. return newTexture;
  24652. };
  24653. MirrorTexture.prototype.serialize = function () {
  24654. if (!this.name) {
  24655. return null;
  24656. }
  24657. var serializationObject = _super.prototype.serialize.call(this);
  24658. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  24659. return serializationObject;
  24660. };
  24661. return MirrorTexture;
  24662. }(BABYLON.RenderTargetTexture));
  24663. BABYLON.MirrorTexture = MirrorTexture;
  24664. })(BABYLON || (BABYLON = {}));
  24665. //# sourceMappingURL=babylon.mirrorTexture.js.map
  24666. var BABYLON;
  24667. (function (BABYLON) {
  24668. /**
  24669. * Creates a refraction texture used by refraction channel of the standard material.
  24670. * @param name the texture name
  24671. * @param size size of the underlying texture
  24672. * @param scene root scene
  24673. */
  24674. var RefractionTexture = (function (_super) {
  24675. __extends(RefractionTexture, _super);
  24676. function RefractionTexture(name, size, scene, generateMipMaps) {
  24677. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  24678. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  24679. _this.depth = 2.0;
  24680. _this.onBeforeRenderObservable.add(function () {
  24681. scene.clipPlane = _this.refractionPlane;
  24682. });
  24683. _this.onAfterRenderObservable.add(function () {
  24684. delete scene.clipPlane;
  24685. });
  24686. return _this;
  24687. }
  24688. RefractionTexture.prototype.clone = function () {
  24689. var textureSize = this.getSize();
  24690. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24691. // Base texture
  24692. newTexture.hasAlpha = this.hasAlpha;
  24693. newTexture.level = this.level;
  24694. // Refraction Texture
  24695. newTexture.refractionPlane = this.refractionPlane.clone();
  24696. newTexture.renderList = this.renderList.slice(0);
  24697. newTexture.depth = this.depth;
  24698. return newTexture;
  24699. };
  24700. RefractionTexture.prototype.serialize = function () {
  24701. if (!this.name) {
  24702. return null;
  24703. }
  24704. var serializationObject = _super.prototype.serialize.call(this);
  24705. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  24706. serializationObject.depth = this.depth;
  24707. return serializationObject;
  24708. };
  24709. return RefractionTexture;
  24710. }(BABYLON.RenderTargetTexture));
  24711. BABYLON.RefractionTexture = RefractionTexture;
  24712. })(BABYLON || (BABYLON = {}));
  24713. //# sourceMappingURL=babylon.refractionTexture.js.map
  24714. var BABYLON;
  24715. (function (BABYLON) {
  24716. var DynamicTexture = (function (_super) {
  24717. __extends(DynamicTexture, _super);
  24718. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  24719. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24720. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  24721. _this.name = name;
  24722. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24723. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24724. _this._generateMipMaps = generateMipMaps;
  24725. if (options.getContext) {
  24726. _this._canvas = options;
  24727. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  24728. }
  24729. else {
  24730. _this._canvas = document.createElement("canvas");
  24731. if (options.width) {
  24732. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  24733. }
  24734. else {
  24735. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  24736. }
  24737. }
  24738. var textureSize = _this.getSize();
  24739. _this._canvas.width = textureSize.width;
  24740. _this._canvas.height = textureSize.height;
  24741. _this._context = _this._canvas.getContext("2d");
  24742. return _this;
  24743. }
  24744. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  24745. get: function () {
  24746. return true;
  24747. },
  24748. enumerable: true,
  24749. configurable: true
  24750. });
  24751. DynamicTexture.prototype.scale = function (ratio) {
  24752. var textureSize = this.getSize();
  24753. textureSize.width *= ratio;
  24754. textureSize.height *= ratio;
  24755. this._canvas.width = textureSize.width;
  24756. this._canvas.height = textureSize.height;
  24757. this.releaseInternalTexture();
  24758. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  24759. };
  24760. DynamicTexture.prototype.getContext = function () {
  24761. return this._context;
  24762. };
  24763. DynamicTexture.prototype.clear = function () {
  24764. var size = this.getSize();
  24765. this._context.fillRect(0, 0, size.width, size.height);
  24766. };
  24767. DynamicTexture.prototype.update = function (invertY) {
  24768. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  24769. };
  24770. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  24771. if (update === void 0) { update = true; }
  24772. var size = this.getSize();
  24773. if (clearColor) {
  24774. this._context.fillStyle = clearColor;
  24775. this._context.fillRect(0, 0, size.width, size.height);
  24776. }
  24777. this._context.font = font;
  24778. if (x === null) {
  24779. var textSize = this._context.measureText(text);
  24780. x = (size.width - textSize.width) / 2;
  24781. }
  24782. this._context.fillStyle = color;
  24783. this._context.fillText(text, x, y);
  24784. if (update) {
  24785. this.update(invertY);
  24786. }
  24787. };
  24788. DynamicTexture.prototype.clone = function () {
  24789. var textureSize = this.getSize();
  24790. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  24791. // Base texture
  24792. newTexture.hasAlpha = this.hasAlpha;
  24793. newTexture.level = this.level;
  24794. // Dynamic Texture
  24795. newTexture.wrapU = this.wrapU;
  24796. newTexture.wrapV = this.wrapV;
  24797. return newTexture;
  24798. };
  24799. return DynamicTexture;
  24800. }(BABYLON.Texture));
  24801. BABYLON.DynamicTexture = DynamicTexture;
  24802. })(BABYLON || (BABYLON = {}));
  24803. //# sourceMappingURL=babylon.dynamicTexture.js.map
  24804. var BABYLON;
  24805. (function (BABYLON) {
  24806. var VideoTexture = (function (_super) {
  24807. __extends(VideoTexture, _super);
  24808. /**
  24809. * Creates a video texture.
  24810. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  24811. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  24812. * @param {BABYLON.Scene} scene is obviously the current scene.
  24813. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  24814. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  24815. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  24816. */
  24817. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  24818. if (generateMipMaps === void 0) { generateMipMaps = false; }
  24819. if (invertY === void 0) { invertY = false; }
  24820. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24821. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  24822. _this._autoLaunch = true;
  24823. var urls;
  24824. _this.name = name;
  24825. if (urlsOrVideo instanceof HTMLVideoElement) {
  24826. _this.video = urlsOrVideo;
  24827. }
  24828. else {
  24829. urls = urlsOrVideo;
  24830. _this.video = document.createElement("video");
  24831. _this.video.autoplay = false;
  24832. _this.video.loop = true;
  24833. }
  24834. _this._generateMipMaps = generateMipMaps;
  24835. _this._samplingMode = samplingMode;
  24836. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  24837. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24838. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24839. }
  24840. else {
  24841. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24842. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24843. _this._generateMipMaps = false;
  24844. }
  24845. if (urls) {
  24846. _this.video.addEventListener("canplaythrough", function () {
  24847. _this._createTexture();
  24848. });
  24849. urls.forEach(function (url) {
  24850. var source = document.createElement("source");
  24851. source.src = url;
  24852. _this.video.appendChild(source);
  24853. });
  24854. }
  24855. else {
  24856. _this._createTexture();
  24857. }
  24858. _this._lastUpdate = BABYLON.Tools.Now;
  24859. return _this;
  24860. }
  24861. VideoTexture.prototype._createTexture = function () {
  24862. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  24863. this._texture.isReady = true;
  24864. };
  24865. VideoTexture.prototype.update = function () {
  24866. if (this._autoLaunch) {
  24867. this._autoLaunch = false;
  24868. this.video.play();
  24869. }
  24870. var now = BABYLON.Tools.Now;
  24871. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  24872. return false;
  24873. }
  24874. this._lastUpdate = now;
  24875. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  24876. return true;
  24877. };
  24878. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  24879. var video = document.createElement("video");
  24880. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  24881. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  24882. if (navigator.getUserMedia) {
  24883. navigator.getUserMedia({
  24884. video: {
  24885. width: {
  24886. min: (constraints && constraints.minWidth) || 256,
  24887. max: (constraints && constraints.maxWidth) || 640
  24888. },
  24889. height: {
  24890. min: (constraints && constraints.minHeight) || 256,
  24891. max: (constraints && constraints.maxHeight) || 480
  24892. }
  24893. }
  24894. }, function (stream) {
  24895. if (video.mozSrcObject !== undefined) {
  24896. video.mozSrcObject = stream;
  24897. }
  24898. else {
  24899. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  24900. }
  24901. video.play();
  24902. if (onReady) {
  24903. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  24904. }
  24905. }, function (e) {
  24906. BABYLON.Tools.Error(e.name);
  24907. });
  24908. }
  24909. };
  24910. return VideoTexture;
  24911. }(BABYLON.Texture));
  24912. BABYLON.VideoTexture = VideoTexture;
  24913. })(BABYLON || (BABYLON = {}));
  24914. //# sourceMappingURL=babylon.videoTexture.js.map
  24915. var BABYLON;
  24916. (function (BABYLON) {
  24917. var CustomProceduralTexture = (function (_super) {
  24918. __extends(CustomProceduralTexture, _super);
  24919. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  24920. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  24921. _this._animate = true;
  24922. _this._time = 0;
  24923. _this._texturePath = texturePath;
  24924. //Try to load json
  24925. _this.loadJson(texturePath);
  24926. _this.refreshRate = 1;
  24927. return _this;
  24928. }
  24929. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  24930. var _this = this;
  24931. var that = this;
  24932. function noConfigFile() {
  24933. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  24934. try {
  24935. that.setFragment(that._texturePath);
  24936. }
  24937. catch (ex) {
  24938. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  24939. }
  24940. }
  24941. var configFileUrl = jsonUrl + "/config.json";
  24942. var xhr = new XMLHttpRequest();
  24943. xhr.open("GET", configFileUrl, true);
  24944. xhr.addEventListener("load", function () {
  24945. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  24946. try {
  24947. _this._config = JSON.parse(xhr.response);
  24948. _this.updateShaderUniforms();
  24949. _this.updateTextures();
  24950. _this.setFragment(_this._texturePath + "/custom");
  24951. _this._animate = _this._config.animate;
  24952. _this.refreshRate = _this._config.refreshrate;
  24953. }
  24954. catch (ex) {
  24955. noConfigFile();
  24956. }
  24957. }
  24958. else {
  24959. noConfigFile();
  24960. }
  24961. }, false);
  24962. xhr.addEventListener("error", function () {
  24963. noConfigFile();
  24964. }, false);
  24965. try {
  24966. xhr.send();
  24967. }
  24968. catch (ex) {
  24969. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  24970. }
  24971. };
  24972. CustomProceduralTexture.prototype.isReady = function () {
  24973. if (!_super.prototype.isReady.call(this)) {
  24974. return false;
  24975. }
  24976. for (var name in this._textures) {
  24977. var texture = this._textures[name];
  24978. if (!texture.isReady()) {
  24979. return false;
  24980. }
  24981. }
  24982. return true;
  24983. };
  24984. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  24985. if (this._animate) {
  24986. this._time += this.getScene().getAnimationRatio() * 0.03;
  24987. this.updateShaderUniforms();
  24988. }
  24989. _super.prototype.render.call(this, useCameraPostProcess);
  24990. };
  24991. CustomProceduralTexture.prototype.updateTextures = function () {
  24992. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  24993. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  24994. }
  24995. };
  24996. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  24997. if (this._config) {
  24998. for (var j = 0; j < this._config.uniforms.length; j++) {
  24999. var uniform = this._config.uniforms[j];
  25000. switch (uniform.type) {
  25001. case "float":
  25002. this.setFloat(uniform.name, uniform.value);
  25003. break;
  25004. case "color3":
  25005. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  25006. break;
  25007. case "color4":
  25008. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  25009. break;
  25010. case "vector2":
  25011. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  25012. break;
  25013. case "vector3":
  25014. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  25015. break;
  25016. }
  25017. }
  25018. }
  25019. this.setFloat("time", this._time);
  25020. };
  25021. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  25022. get: function () {
  25023. return this._animate;
  25024. },
  25025. set: function (value) {
  25026. this._animate = value;
  25027. },
  25028. enumerable: true,
  25029. configurable: true
  25030. });
  25031. return CustomProceduralTexture;
  25032. }(BABYLON.ProceduralTexture));
  25033. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  25034. })(BABYLON || (BABYLON = {}));
  25035. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  25036. var BABYLON;
  25037. (function (BABYLON) {
  25038. var EffectFallbacks = (function () {
  25039. function EffectFallbacks() {
  25040. this._defines = {};
  25041. this._currentRank = 32;
  25042. this._maxRank = -1;
  25043. }
  25044. EffectFallbacks.prototype.addFallback = function (rank, define) {
  25045. if (!this._defines[rank]) {
  25046. if (rank < this._currentRank) {
  25047. this._currentRank = rank;
  25048. }
  25049. if (rank > this._maxRank) {
  25050. this._maxRank = rank;
  25051. }
  25052. this._defines[rank] = new Array();
  25053. }
  25054. this._defines[rank].push(define);
  25055. };
  25056. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  25057. this._meshRank = rank;
  25058. this._mesh = mesh;
  25059. if (rank > this._maxRank) {
  25060. this._maxRank = rank;
  25061. }
  25062. };
  25063. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  25064. get: function () {
  25065. return this._currentRank <= this._maxRank;
  25066. },
  25067. enumerable: true,
  25068. configurable: true
  25069. });
  25070. EffectFallbacks.prototype.reduce = function (currentDefines) {
  25071. var currentFallbacks = this._defines[this._currentRank];
  25072. for (var index = 0; index < currentFallbacks.length; index++) {
  25073. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  25074. }
  25075. if (this._mesh && this._currentRank === this._meshRank) {
  25076. this._mesh.computeBonesUsingShaders = false;
  25077. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  25078. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  25079. }
  25080. this._currentRank++;
  25081. return currentDefines;
  25082. };
  25083. return EffectFallbacks;
  25084. }());
  25085. BABYLON.EffectFallbacks = EffectFallbacks;
  25086. var Effect = (function () {
  25087. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  25088. var _this = this;
  25089. this._isReady = false;
  25090. this._compilationError = "";
  25091. this._valueCache = {};
  25092. this._engine = engine;
  25093. this.name = baseName;
  25094. this.defines = defines;
  25095. this._uniformsNames = uniformsNames.concat(samplers);
  25096. this._samplers = samplers;
  25097. this._attributesNames = attributesNames;
  25098. this.onError = onError;
  25099. this.onCompiled = onCompiled;
  25100. this._indexParameters = indexParameters;
  25101. var vertexSource;
  25102. var fragmentSource;
  25103. if (baseName.vertexElement) {
  25104. vertexSource = document.getElementById(baseName.vertexElement);
  25105. if (!vertexSource) {
  25106. vertexSource = baseName.vertexElement;
  25107. }
  25108. }
  25109. else {
  25110. vertexSource = baseName.vertex || baseName;
  25111. }
  25112. if (baseName.fragmentElement) {
  25113. fragmentSource = document.getElementById(baseName.fragmentElement);
  25114. if (!fragmentSource) {
  25115. fragmentSource = baseName.fragmentElement;
  25116. }
  25117. }
  25118. else {
  25119. fragmentSource = baseName.fragment || baseName;
  25120. }
  25121. this._loadVertexShader(vertexSource, function (vertexCode) {
  25122. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  25123. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  25124. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  25125. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  25126. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  25127. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, attributesNames, defines, fallbacks);
  25128. });
  25129. });
  25130. });
  25131. });
  25132. });
  25133. });
  25134. }
  25135. // Properties
  25136. Effect.prototype.isReady = function () {
  25137. return this._isReady;
  25138. };
  25139. Effect.prototype.getProgram = function () {
  25140. return this._program;
  25141. };
  25142. Effect.prototype.getAttributesNames = function () {
  25143. return this._attributesNames;
  25144. };
  25145. Effect.prototype.getAttributeLocation = function (index) {
  25146. return this._attributes[index];
  25147. };
  25148. Effect.prototype.getAttributeLocationByName = function (name) {
  25149. var index = this._attributesNames.indexOf(name);
  25150. return this._attributes[index];
  25151. };
  25152. Effect.prototype.getAttributesCount = function () {
  25153. return this._attributes.length;
  25154. };
  25155. Effect.prototype.getUniformIndex = function (uniformName) {
  25156. return this._uniformsNames.indexOf(uniformName);
  25157. };
  25158. Effect.prototype.getUniform = function (uniformName) {
  25159. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  25160. };
  25161. Effect.prototype.getSamplers = function () {
  25162. return this._samplers;
  25163. };
  25164. Effect.prototype.getCompilationError = function () {
  25165. return this._compilationError;
  25166. };
  25167. Effect.prototype.getVertexShaderSource = function () {
  25168. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  25169. };
  25170. Effect.prototype.getFragmentShaderSource = function () {
  25171. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  25172. };
  25173. // Methods
  25174. Effect.prototype._loadVertexShader = function (vertex, callback) {
  25175. // DOM element ?
  25176. if (vertex instanceof HTMLElement) {
  25177. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  25178. callback(vertexCode);
  25179. return;
  25180. }
  25181. // Base64 encoded ?
  25182. if (vertex.substr(0, 7) === "base64:") {
  25183. var vertexBinary = window.atob(vertex.substr(7));
  25184. callback(vertexBinary);
  25185. return;
  25186. }
  25187. // Is in local store ?
  25188. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  25189. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  25190. return;
  25191. }
  25192. var vertexShaderUrl;
  25193. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  25194. vertexShaderUrl = vertex;
  25195. }
  25196. else {
  25197. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  25198. }
  25199. // Vertex shader
  25200. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  25201. };
  25202. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  25203. // DOM element ?
  25204. if (fragment instanceof HTMLElement) {
  25205. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  25206. callback(fragmentCode);
  25207. return;
  25208. }
  25209. // Base64 encoded ?
  25210. if (fragment.substr(0, 7) === "base64:") {
  25211. var fragmentBinary = window.atob(fragment.substr(7));
  25212. callback(fragmentBinary);
  25213. return;
  25214. }
  25215. // Is in local store ?
  25216. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  25217. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  25218. return;
  25219. }
  25220. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  25221. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  25222. return;
  25223. }
  25224. var fragmentShaderUrl;
  25225. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  25226. fragmentShaderUrl = fragment;
  25227. }
  25228. else {
  25229. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  25230. }
  25231. // Fragment shader
  25232. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  25233. };
  25234. Effect.prototype._dumpShadersName = function () {
  25235. if (this.name.vertexElement) {
  25236. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  25237. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  25238. }
  25239. else if (this.name.vertex) {
  25240. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  25241. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  25242. }
  25243. else {
  25244. BABYLON.Tools.Error("Vertex shader:" + this.name);
  25245. BABYLON.Tools.Error("Fragment shader:" + this.name);
  25246. }
  25247. };
  25248. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  25249. var preparedSourceCode = this._processPrecision(sourceCode);
  25250. if (this._engine.webGLVersion == 1) {
  25251. callback(preparedSourceCode);
  25252. return;
  25253. }
  25254. // Already converted
  25255. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  25256. callback(preparedSourceCode);
  25257. return;
  25258. }
  25259. // Remove extensions
  25260. // #extension GL_OES_standard_derivatives : enable
  25261. // #extension GL_EXT_shader_texture_lod : enable
  25262. // #extension GL_EXT_frag_depth : enable
  25263. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  25264. var result = preparedSourceCode.replace(regex, "");
  25265. // Migrate to GLSL v300
  25266. result = result.replace(/varying\s/g, isFragment ? "in " : "out ");
  25267. result = result.replace(/attribute\s/g, "in ");
  25268. if (isFragment) {
  25269. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  25270. result = result.replace(/texture2D\(/g, "texture(");
  25271. result = result.replace(/textureCube\(/g, "texture(");
  25272. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  25273. result = result.replace(/gl_FragColor/g, "glFragColor");
  25274. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  25275. }
  25276. callback(result);
  25277. };
  25278. Effect.prototype._processIncludes = function (sourceCode, callback) {
  25279. var _this = this;
  25280. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  25281. var match = regex.exec(sourceCode);
  25282. var returnValue = new String(sourceCode);
  25283. while (match != null) {
  25284. var includeFile = match[1];
  25285. if (Effect.IncludesShadersStore[includeFile]) {
  25286. // Substitution
  25287. var includeContent = Effect.IncludesShadersStore[includeFile];
  25288. if (match[2]) {
  25289. var splits = match[3].split(",");
  25290. for (var index = 0; index < splits.length; index += 2) {
  25291. var source = new RegExp(splits[index], "g");
  25292. var dest = splits[index + 1];
  25293. includeContent = includeContent.replace(source, dest);
  25294. }
  25295. }
  25296. if (match[4]) {
  25297. var indexString = match[5];
  25298. if (indexString.indexOf("..") !== -1) {
  25299. var indexSplits = indexString.split("..");
  25300. var minIndex = parseInt(indexSplits[0]);
  25301. var maxIndex = parseInt(indexSplits[1]);
  25302. var sourceIncludeContent = includeContent.slice(0);
  25303. includeContent = "";
  25304. if (isNaN(maxIndex)) {
  25305. maxIndex = this._indexParameters[indexSplits[1]];
  25306. }
  25307. for (var i = minIndex; i <= maxIndex; i++) {
  25308. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  25309. }
  25310. }
  25311. else {
  25312. includeContent = includeContent.replace(/\{X\}/g, indexString);
  25313. }
  25314. }
  25315. // Replace
  25316. returnValue = returnValue.replace(match[0], includeContent);
  25317. }
  25318. else {
  25319. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  25320. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  25321. Effect.IncludesShadersStore[includeFile] = fileContent;
  25322. _this._processIncludes(returnValue, callback);
  25323. });
  25324. return;
  25325. }
  25326. match = regex.exec(sourceCode);
  25327. }
  25328. callback(returnValue);
  25329. };
  25330. Effect.prototype._processPrecision = function (source) {
  25331. if (source.indexOf("precision highp float") === -1) {
  25332. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25333. source = "precision mediump float;\n" + source;
  25334. }
  25335. else {
  25336. source = "precision highp float;\n" + source;
  25337. }
  25338. }
  25339. else {
  25340. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25341. source = source.replace("precision highp float", "precision mediump float");
  25342. }
  25343. }
  25344. return source;
  25345. };
  25346. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  25347. try {
  25348. var engine = this._engine;
  25349. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  25350. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  25351. this._attributes = engine.getAttributes(this._program, attributesNames);
  25352. var index;
  25353. for (index = 0; index < this._samplers.length; index++) {
  25354. var sampler = this.getUniform(this._samplers[index]);
  25355. if (sampler == null) {
  25356. this._samplers.splice(index, 1);
  25357. index--;
  25358. }
  25359. }
  25360. engine.bindSamplers(this);
  25361. this._compilationError = "";
  25362. this._isReady = true;
  25363. if (this.onCompiled) {
  25364. this.onCompiled(this);
  25365. }
  25366. }
  25367. catch (e) {
  25368. this._compilationError = e.message;
  25369. // Let's go through fallbacks then
  25370. BABYLON.Tools.Error("Unable to compile effect: ");
  25371. BABYLON.Tools.Error("Defines: " + defines);
  25372. BABYLON.Tools.Error("Error: " + this._compilationError);
  25373. this._dumpShadersName();
  25374. if (fallbacks && fallbacks.isMoreFallbacks) {
  25375. BABYLON.Tools.Error("Trying next fallback.");
  25376. defines = fallbacks.reduce(defines);
  25377. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  25378. }
  25379. else {
  25380. if (this.onError) {
  25381. this.onError(this, this._compilationError);
  25382. }
  25383. }
  25384. }
  25385. };
  25386. Object.defineProperty(Effect.prototype, "isSupported", {
  25387. get: function () {
  25388. return this._compilationError === "";
  25389. },
  25390. enumerable: true,
  25391. configurable: true
  25392. });
  25393. Effect.prototype._bindTexture = function (channel, texture) {
  25394. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  25395. };
  25396. Effect.prototype.setTexture = function (channel, texture) {
  25397. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  25398. };
  25399. Effect.prototype.setTextureArray = function (channel, textures) {
  25400. if (this._samplers.indexOf(channel + "Ex") === -1) {
  25401. var initialPos = this._samplers.indexOf(channel);
  25402. for (var index = 1; index < textures.length; index++) {
  25403. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  25404. }
  25405. }
  25406. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  25407. };
  25408. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  25409. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  25410. };
  25411. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  25412. var changed = false;
  25413. var cache = this._valueCache[uniformName];
  25414. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  25415. changed = true;
  25416. cache = new BABYLON.Matrix();
  25417. }
  25418. var tm = cache.m;
  25419. var om = matrix.m;
  25420. for (var index = 0; index < 16; index++) {
  25421. if (tm[index] !== om[index]) {
  25422. tm[index] = om[index];
  25423. changed = true;
  25424. }
  25425. }
  25426. this._valueCache[uniformName] = cache;
  25427. return changed;
  25428. };
  25429. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  25430. var cache = this._valueCache[uniformName];
  25431. if (!cache) {
  25432. cache = [x, y];
  25433. this._valueCache[uniformName] = cache;
  25434. return true;
  25435. }
  25436. var changed = false;
  25437. if (cache[0] !== x) {
  25438. cache[0] = x;
  25439. changed = true;
  25440. }
  25441. if (cache[1] !== y) {
  25442. cache[1] = y;
  25443. changed = true;
  25444. }
  25445. return changed;
  25446. };
  25447. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  25448. var cache = this._valueCache[uniformName];
  25449. if (!cache) {
  25450. cache = [x, y, z];
  25451. this._valueCache[uniformName] = cache;
  25452. return true;
  25453. }
  25454. var changed = false;
  25455. if (cache[0] !== x) {
  25456. cache[0] = x;
  25457. changed = true;
  25458. }
  25459. if (cache[1] !== y) {
  25460. cache[1] = y;
  25461. changed = true;
  25462. }
  25463. if (cache[2] !== z) {
  25464. cache[2] = z;
  25465. changed = true;
  25466. }
  25467. return changed;
  25468. };
  25469. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  25470. var cache = this._valueCache[uniformName];
  25471. if (!cache) {
  25472. cache = [x, y, z, w];
  25473. this._valueCache[uniformName] = cache;
  25474. return true;
  25475. }
  25476. var changed = false;
  25477. if (cache[0] !== x) {
  25478. cache[0] = x;
  25479. changed = true;
  25480. }
  25481. if (cache[1] !== y) {
  25482. cache[1] = y;
  25483. changed = true;
  25484. }
  25485. if (cache[2] !== z) {
  25486. cache[2] = z;
  25487. changed = true;
  25488. }
  25489. if (cache[3] !== w) {
  25490. cache[3] = w;
  25491. changed = true;
  25492. }
  25493. return changed;
  25494. };
  25495. Effect.prototype.setIntArray = function (uniformName, array) {
  25496. this._valueCache[uniformName] = null;
  25497. this._engine.setIntArray(this.getUniform(uniformName), array);
  25498. return this;
  25499. };
  25500. Effect.prototype.setIntArray2 = function (uniformName, array) {
  25501. this._valueCache[uniformName] = null;
  25502. this._engine.setIntArray2(this.getUniform(uniformName), array);
  25503. return this;
  25504. };
  25505. Effect.prototype.setIntArray3 = function (uniformName, array) {
  25506. this._valueCache[uniformName] = null;
  25507. this._engine.setIntArray3(this.getUniform(uniformName), array);
  25508. return this;
  25509. };
  25510. Effect.prototype.setIntArray4 = function (uniformName, array) {
  25511. this._valueCache[uniformName] = null;
  25512. this._engine.setIntArray4(this.getUniform(uniformName), array);
  25513. return this;
  25514. };
  25515. Effect.prototype.setFloatArray = function (uniformName, array) {
  25516. this._valueCache[uniformName] = null;
  25517. this._engine.setFloatArray(this.getUniform(uniformName), array);
  25518. return this;
  25519. };
  25520. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  25521. this._valueCache[uniformName] = null;
  25522. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  25523. return this;
  25524. };
  25525. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  25526. this._valueCache[uniformName] = null;
  25527. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  25528. return this;
  25529. };
  25530. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  25531. this._valueCache[uniformName] = null;
  25532. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  25533. return this;
  25534. };
  25535. Effect.prototype.setArray = function (uniformName, array) {
  25536. this._valueCache[uniformName] = null;
  25537. this._engine.setArray(this.getUniform(uniformName), array);
  25538. return this;
  25539. };
  25540. Effect.prototype.setArray2 = function (uniformName, array) {
  25541. this._valueCache[uniformName] = null;
  25542. this._engine.setArray2(this.getUniform(uniformName), array);
  25543. return this;
  25544. };
  25545. Effect.prototype.setArray3 = function (uniformName, array) {
  25546. this._valueCache[uniformName] = null;
  25547. this._engine.setArray3(this.getUniform(uniformName), array);
  25548. return this;
  25549. };
  25550. Effect.prototype.setArray4 = function (uniformName, array) {
  25551. this._valueCache[uniformName] = null;
  25552. this._engine.setArray4(this.getUniform(uniformName), array);
  25553. return this;
  25554. };
  25555. Effect.prototype.setMatrices = function (uniformName, matrices) {
  25556. this._valueCache[uniformName] = null;
  25557. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  25558. return this;
  25559. };
  25560. Effect.prototype.setMatrix = function (uniformName, matrix) {
  25561. if (this._cacheMatrix(uniformName, matrix)) {
  25562. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  25563. }
  25564. return this;
  25565. };
  25566. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  25567. this._valueCache[uniformName] = null;
  25568. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  25569. return this;
  25570. };
  25571. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  25572. this._valueCache[uniformName] = null;
  25573. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  25574. return this;
  25575. };
  25576. Effect.prototype.setFloat = function (uniformName, value) {
  25577. var cache = this._valueCache[uniformName];
  25578. if (cache !== undefined && cache === value)
  25579. return this;
  25580. this._valueCache[uniformName] = value;
  25581. this._engine.setFloat(this.getUniform(uniformName), value);
  25582. return this;
  25583. };
  25584. Effect.prototype.setBool = function (uniformName, bool) {
  25585. var cache = this._valueCache[uniformName];
  25586. if (cache !== undefined && cache === bool)
  25587. return this;
  25588. this._valueCache[uniformName] = bool;
  25589. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  25590. return this;
  25591. };
  25592. Effect.prototype.setVector2 = function (uniformName, vector2) {
  25593. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  25594. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  25595. }
  25596. return this;
  25597. };
  25598. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  25599. if (this._cacheFloat2(uniformName, x, y)) {
  25600. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  25601. }
  25602. return this;
  25603. };
  25604. Effect.prototype.setVector3 = function (uniformName, vector3) {
  25605. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  25606. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  25607. }
  25608. return this;
  25609. };
  25610. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  25611. if (this._cacheFloat3(uniformName, x, y, z)) {
  25612. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  25613. }
  25614. return this;
  25615. };
  25616. Effect.prototype.setVector4 = function (uniformName, vector4) {
  25617. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  25618. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  25619. }
  25620. return this;
  25621. };
  25622. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  25623. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  25624. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  25625. }
  25626. return this;
  25627. };
  25628. Effect.prototype.setColor3 = function (uniformName, color3) {
  25629. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  25630. this._engine.setColor3(this.getUniform(uniformName), color3);
  25631. }
  25632. return this;
  25633. };
  25634. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  25635. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  25636. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  25637. }
  25638. return this;
  25639. };
  25640. Effect.prototype._recombineShader = function (node) {
  25641. if (node.define) {
  25642. if (node.condition) {
  25643. var defineIndex = this.defines.indexOf("#define " + node.define);
  25644. if (defineIndex === -1) {
  25645. return null;
  25646. }
  25647. var nextComma = this.defines.indexOf("\n", defineIndex);
  25648. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  25649. var condition = defineValue + node.condition;
  25650. if (!eval(condition)) {
  25651. return null;
  25652. }
  25653. }
  25654. else if (node.ndef) {
  25655. if (this.defines.indexOf("#define " + node.define) !== -1) {
  25656. return null;
  25657. }
  25658. }
  25659. else if (this.defines.indexOf("#define " + node.define) === -1) {
  25660. return null;
  25661. }
  25662. }
  25663. var result = "";
  25664. for (var index = 0; index < node.children.length; index++) {
  25665. var line = node.children[index];
  25666. if (line.children) {
  25667. var combined = this._recombineShader(line);
  25668. if (combined !== null) {
  25669. result += combined + "\r\n";
  25670. }
  25671. continue;
  25672. }
  25673. if (line.length > 0) {
  25674. result += line + "\r\n";
  25675. }
  25676. }
  25677. return result;
  25678. };
  25679. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  25680. var root = {
  25681. children: []
  25682. };
  25683. var currentNode = root;
  25684. var lines = shaderString.split("\n");
  25685. for (var index = 0; index < lines.length; index++) {
  25686. var line = lines[index].trim();
  25687. // #ifdef
  25688. var pos = line.indexOf("#ifdef ");
  25689. if (pos !== -1) {
  25690. var define = line.substr(pos + 7);
  25691. var newNode = {
  25692. condition: null,
  25693. ndef: false,
  25694. define: define,
  25695. children: [],
  25696. parent: currentNode
  25697. };
  25698. currentNode.children.push(newNode);
  25699. currentNode = newNode;
  25700. continue;
  25701. }
  25702. // #ifndef
  25703. var pos = line.indexOf("#ifndef ");
  25704. if (pos !== -1) {
  25705. var define = line.substr(pos + 8);
  25706. newNode = {
  25707. condition: null,
  25708. define: define,
  25709. ndef: true,
  25710. children: [],
  25711. parent: currentNode
  25712. };
  25713. currentNode.children.push(newNode);
  25714. currentNode = newNode;
  25715. continue;
  25716. }
  25717. // #if
  25718. var pos = line.indexOf("#if ");
  25719. if (pos !== -1) {
  25720. var define = line.substr(pos + 4).trim();
  25721. var conditionPos = define.indexOf(" ");
  25722. newNode = {
  25723. condition: define.substr(conditionPos + 1),
  25724. define: define.substr(0, conditionPos),
  25725. ndef: false,
  25726. children: [],
  25727. parent: currentNode
  25728. };
  25729. currentNode.children.push(newNode);
  25730. currentNode = newNode;
  25731. continue;
  25732. }
  25733. // #endif
  25734. pos = line.indexOf("#endif");
  25735. if (pos !== -1) {
  25736. currentNode = currentNode.parent;
  25737. continue;
  25738. }
  25739. currentNode.children.push(line);
  25740. }
  25741. // Recombine
  25742. return this._recombineShader(root);
  25743. };
  25744. return Effect;
  25745. }());
  25746. // Statics
  25747. Effect.ShadersStore = {};
  25748. Effect.IncludesShadersStore = {};
  25749. BABYLON.Effect = Effect;
  25750. })(BABYLON || (BABYLON = {}));
  25751. //# sourceMappingURL=babylon.effect.js.map
  25752. var BABYLON;
  25753. (function (BABYLON) {
  25754. var MaterialHelper = (function () {
  25755. function MaterialHelper() {
  25756. }
  25757. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  25758. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25759. var lightIndex = 0;
  25760. var needNormals = false;
  25761. var needRebuild = false;
  25762. var needShadows = false;
  25763. var lightmapMode = false;
  25764. for (var index = 0; index < scene.lights.length; index++) {
  25765. var light = scene.lights[index];
  25766. if (!light.isEnabled()) {
  25767. continue;
  25768. }
  25769. // Excluded check
  25770. if (light._excludedMeshesIds.length > 0) {
  25771. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  25772. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  25773. if (excludedMesh) {
  25774. light.excludedMeshes.push(excludedMesh);
  25775. }
  25776. }
  25777. light._excludedMeshesIds = [];
  25778. }
  25779. // Included check
  25780. if (light._includedOnlyMeshesIds.length > 0) {
  25781. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  25782. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  25783. if (includedOnlyMesh) {
  25784. light.includedOnlyMeshes.push(includedOnlyMesh);
  25785. }
  25786. }
  25787. light._includedOnlyMeshesIds = [];
  25788. }
  25789. if (!light.canAffectMesh(mesh)) {
  25790. continue;
  25791. }
  25792. needNormals = true;
  25793. if (defines["LIGHT" + lightIndex] === undefined) {
  25794. needRebuild = true;
  25795. }
  25796. defines["LIGHT" + lightIndex] = true;
  25797. var type;
  25798. if (light instanceof BABYLON.SpotLight) {
  25799. type = "SPOTLIGHT" + lightIndex;
  25800. }
  25801. else if (light instanceof BABYLON.HemisphericLight) {
  25802. type = "HEMILIGHT" + lightIndex;
  25803. }
  25804. else if (light instanceof BABYLON.PointLight) {
  25805. type = "POINTLIGHT" + lightIndex;
  25806. }
  25807. else {
  25808. type = "DIRLIGHT" + lightIndex;
  25809. }
  25810. if (defines[type] === undefined) {
  25811. needRebuild = true;
  25812. }
  25813. defines[type] = true;
  25814. // Specular
  25815. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  25816. defines["SPECULARTERM"] = true;
  25817. }
  25818. // Shadows
  25819. if (scene.shadowsEnabled) {
  25820. var shadowGenerator = light.getShadowGenerator();
  25821. if (mesh && mesh.receiveShadows && shadowGenerator) {
  25822. if (defines["SHADOW" + lightIndex] === undefined) {
  25823. needRebuild = true;
  25824. }
  25825. defines["SHADOW" + lightIndex] = true;
  25826. defines["SHADOWS"] = true;
  25827. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  25828. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  25829. needRebuild = true;
  25830. }
  25831. defines["SHADOWVSM" + lightIndex] = true;
  25832. }
  25833. if (shadowGenerator.usePoissonSampling) {
  25834. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  25835. needRebuild = true;
  25836. }
  25837. defines["SHADOWPCF" + lightIndex] = true;
  25838. }
  25839. needShadows = true;
  25840. }
  25841. }
  25842. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25843. lightmapMode = true;
  25844. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  25845. needRebuild = true;
  25846. }
  25847. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  25848. needRebuild = true;
  25849. }
  25850. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25851. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  25852. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  25853. }
  25854. }
  25855. lightIndex++;
  25856. if (lightIndex === maxSimultaneousLights)
  25857. break;
  25858. }
  25859. var caps = scene.getEngine().getCaps();
  25860. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  25861. if (defines["SHADOWFULLFLOAT"] === undefined) {
  25862. needRebuild = true;
  25863. }
  25864. defines["SHADOWFULLFLOAT"] = true;
  25865. }
  25866. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  25867. needRebuild = true;
  25868. }
  25869. if (lightmapMode) {
  25870. defines["LIGHTMAPEXCLUDED"] = true;
  25871. }
  25872. if (needRebuild) {
  25873. defines.rebuild();
  25874. }
  25875. return needNormals;
  25876. };
  25877. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  25878. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25879. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25880. if (!defines["LIGHT" + lightIndex]) {
  25881. break;
  25882. }
  25883. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  25884. samplersList.push("shadowSampler" + lightIndex);
  25885. }
  25886. };
  25887. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25888. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25889. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25890. if (!defines["LIGHT" + lightIndex]) {
  25891. break;
  25892. }
  25893. if (lightIndex > 0) {
  25894. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25895. }
  25896. if (defines["SHADOW" + lightIndex]) {
  25897. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25898. }
  25899. if (defines["SHADOWPCF" + lightIndex]) {
  25900. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25901. }
  25902. if (defines["SHADOWVSM" + lightIndex]) {
  25903. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  25904. }
  25905. }
  25906. };
  25907. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25908. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25909. fallbacks.addCPUSkinningFallback(0, mesh);
  25910. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25911. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25912. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25913. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25914. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25915. }
  25916. }
  25917. };
  25918. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25919. if (defines["INSTANCES"]) {
  25920. attribs.push("world0");
  25921. attribs.push("world1");
  25922. attribs.push("world2");
  25923. attribs.push("world3");
  25924. }
  25925. };
  25926. // Bindings
  25927. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  25928. var shadowGenerator = light.getShadowGenerator();
  25929. if (mesh.receiveShadows && shadowGenerator) {
  25930. if (!light.needCube()) {
  25931. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  25932. }
  25933. else {
  25934. if (!depthValuesAlreadySet) {
  25935. depthValuesAlreadySet = true;
  25936. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  25937. }
  25938. }
  25939. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  25940. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  25941. }
  25942. return depthValuesAlreadySet;
  25943. };
  25944. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25945. if (light instanceof BABYLON.PointLight) {
  25946. // Point Light
  25947. light.transferToEffect(effect, "vLightData" + lightIndex);
  25948. }
  25949. else if (light instanceof BABYLON.DirectionalLight) {
  25950. // Directional Light
  25951. light.transferToEffect(effect, "vLightData" + lightIndex);
  25952. }
  25953. else if (light instanceof BABYLON.SpotLight) {
  25954. // Spot Light
  25955. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  25956. }
  25957. else if (light instanceof BABYLON.HemisphericLight) {
  25958. // Hemispheric Light
  25959. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  25960. }
  25961. };
  25962. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  25963. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25964. var lightIndex = 0;
  25965. var depthValuesAlreadySet = false;
  25966. for (var index = 0; index < scene.lights.length; index++) {
  25967. var light = scene.lights[index];
  25968. if (!light.isEnabled()) {
  25969. continue;
  25970. }
  25971. if (!light.canAffectMesh(mesh)) {
  25972. continue;
  25973. }
  25974. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25975. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  25976. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  25977. if (defines["SPECULARTERM"]) {
  25978. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  25979. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  25980. }
  25981. // Shadows
  25982. if (scene.shadowsEnabled) {
  25983. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  25984. }
  25985. lightIndex++;
  25986. if (lightIndex === maxSimultaneousLights)
  25987. break;
  25988. }
  25989. };
  25990. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25991. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25992. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25993. effect.setColor3("vFogColor", scene.fogColor);
  25994. }
  25995. };
  25996. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25997. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25998. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25999. if (matrices) {
  26000. effect.setMatrices("mBones", matrices);
  26001. }
  26002. }
  26003. };
  26004. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  26005. if (defines["LOGARITHMICDEPTH"]) {
  26006. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  26007. }
  26008. };
  26009. MaterialHelper.BindClipPlane = function (effect, scene) {
  26010. if (scene.clipPlane) {
  26011. var clipPlane = scene.clipPlane;
  26012. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26013. }
  26014. };
  26015. return MaterialHelper;
  26016. }());
  26017. BABYLON.MaterialHelper = MaterialHelper;
  26018. })(BABYLON || (BABYLON = {}));
  26019. //# sourceMappingURL=babylon.materialHelper.js.map
  26020. var BABYLON;
  26021. (function (BABYLON) {
  26022. var FresnelParameters = (function () {
  26023. function FresnelParameters() {
  26024. this.isEnabled = true;
  26025. this.leftColor = BABYLON.Color3.White();
  26026. this.rightColor = BABYLON.Color3.Black();
  26027. this.bias = 0;
  26028. this.power = 1;
  26029. }
  26030. FresnelParameters.prototype.clone = function () {
  26031. var newFresnelParameters = new FresnelParameters();
  26032. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  26033. return newFresnelParameters;
  26034. };
  26035. FresnelParameters.prototype.serialize = function () {
  26036. var serializationObject = {};
  26037. serializationObject.isEnabled = this.isEnabled;
  26038. serializationObject.leftColor = this.leftColor;
  26039. serializationObject.rightColor = this.rightColor;
  26040. serializationObject.bias = this.bias;
  26041. serializationObject.power = this.power;
  26042. return serializationObject;
  26043. };
  26044. FresnelParameters.Parse = function (parsedFresnelParameters) {
  26045. var fresnelParameters = new FresnelParameters();
  26046. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  26047. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  26048. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  26049. fresnelParameters.bias = parsedFresnelParameters.bias;
  26050. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  26051. return fresnelParameters;
  26052. };
  26053. return FresnelParameters;
  26054. }());
  26055. BABYLON.FresnelParameters = FresnelParameters;
  26056. })(BABYLON || (BABYLON = {}));
  26057. //# sourceMappingURL=babylon.fresnelParameters.js.map
  26058. var BABYLON;
  26059. (function (BABYLON) {
  26060. var MaterialDefines = (function () {
  26061. function MaterialDefines() {
  26062. }
  26063. MaterialDefines.prototype.rebuild = function () {
  26064. if (this._keys) {
  26065. delete this._keys;
  26066. }
  26067. this._keys = Object.keys(this);
  26068. };
  26069. MaterialDefines.prototype.isEqual = function (other) {
  26070. if (this._keys.length !== other._keys.length) {
  26071. return false;
  26072. }
  26073. for (var index = 0; index < this._keys.length; index++) {
  26074. var prop = this._keys[index];
  26075. if (this[prop] !== other[prop]) {
  26076. return false;
  26077. }
  26078. }
  26079. return true;
  26080. };
  26081. MaterialDefines.prototype.cloneTo = function (other) {
  26082. if (this._keys.length !== other._keys.length) {
  26083. other._keys = this._keys.slice(0);
  26084. }
  26085. for (var index = 0; index < this._keys.length; index++) {
  26086. var prop = this._keys[index];
  26087. other[prop] = this[prop];
  26088. }
  26089. };
  26090. MaterialDefines.prototype.reset = function () {
  26091. for (var index = 0; index < this._keys.length; index++) {
  26092. var prop = this._keys[index];
  26093. if (typeof (this[prop]) === "number") {
  26094. this[prop] = 0;
  26095. }
  26096. else {
  26097. this[prop] = false;
  26098. }
  26099. }
  26100. };
  26101. MaterialDefines.prototype.toString = function () {
  26102. var result = "";
  26103. for (var index = 0; index < this._keys.length; index++) {
  26104. var prop = this._keys[index];
  26105. if (typeof (this[prop]) === "number") {
  26106. result += "#define " + prop + " " + this[prop] + "\n";
  26107. }
  26108. else if (this[prop]) {
  26109. result += "#define " + prop + "\n";
  26110. }
  26111. }
  26112. return result;
  26113. };
  26114. return MaterialDefines;
  26115. }());
  26116. BABYLON.MaterialDefines = MaterialDefines;
  26117. var Material = (function () {
  26118. function Material(name, scene, doNotAdd) {
  26119. this.checkReadyOnEveryCall = false;
  26120. this.checkReadyOnlyOnce = false;
  26121. this.state = "";
  26122. this.alpha = 1.0;
  26123. this.backFaceCulling = true;
  26124. this.doNotSerialize = false;
  26125. /**
  26126. * An event triggered when the material is disposed.
  26127. * @type {BABYLON.Observable}
  26128. */
  26129. this.onDisposeObservable = new BABYLON.Observable();
  26130. /**
  26131. * An event triggered when the material is bound.
  26132. * @type {BABYLON.Observable}
  26133. */
  26134. this.onBindObservable = new BABYLON.Observable();
  26135. /**
  26136. * An event triggered when the material is unbound.
  26137. * @type {BABYLON.Observable}
  26138. */
  26139. this.onUnBindObservable = new BABYLON.Observable();
  26140. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  26141. this.disableDepthWrite = false;
  26142. this.fogEnabled = true;
  26143. this.pointSize = 1.0;
  26144. this.zOffset = 0;
  26145. this._wasPreviouslyReady = false;
  26146. this._fillMode = Material.TriangleFillMode;
  26147. this.name = name;
  26148. this.id = name;
  26149. this._scene = scene;
  26150. if (scene.useRightHandedSystem) {
  26151. this.sideOrientation = Material.ClockWiseSideOrientation;
  26152. }
  26153. else {
  26154. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  26155. }
  26156. if (!doNotAdd) {
  26157. scene.materials.push(this);
  26158. }
  26159. }
  26160. Object.defineProperty(Material, "TriangleFillMode", {
  26161. get: function () {
  26162. return Material._TriangleFillMode;
  26163. },
  26164. enumerable: true,
  26165. configurable: true
  26166. });
  26167. Object.defineProperty(Material, "WireFrameFillMode", {
  26168. get: function () {
  26169. return Material._WireFrameFillMode;
  26170. },
  26171. enumerable: true,
  26172. configurable: true
  26173. });
  26174. Object.defineProperty(Material, "PointFillMode", {
  26175. get: function () {
  26176. return Material._PointFillMode;
  26177. },
  26178. enumerable: true,
  26179. configurable: true
  26180. });
  26181. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  26182. get: function () {
  26183. return Material._ClockWiseSideOrientation;
  26184. },
  26185. enumerable: true,
  26186. configurable: true
  26187. });
  26188. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  26189. get: function () {
  26190. return Material._CounterClockWiseSideOrientation;
  26191. },
  26192. enumerable: true,
  26193. configurable: true
  26194. });
  26195. Object.defineProperty(Material.prototype, "onDispose", {
  26196. set: function (callback) {
  26197. if (this._onDisposeObserver) {
  26198. this.onDisposeObservable.remove(this._onDisposeObserver);
  26199. }
  26200. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26201. },
  26202. enumerable: true,
  26203. configurable: true
  26204. });
  26205. Object.defineProperty(Material.prototype, "onBind", {
  26206. set: function (callback) {
  26207. if (this._onBindObserver) {
  26208. this.onBindObservable.remove(this._onBindObserver);
  26209. }
  26210. this._onBindObserver = this.onBindObservable.add(callback);
  26211. },
  26212. enumerable: true,
  26213. configurable: true
  26214. });
  26215. Object.defineProperty(Material.prototype, "wireframe", {
  26216. get: function () {
  26217. return this._fillMode === Material.WireFrameFillMode;
  26218. },
  26219. set: function (value) {
  26220. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  26221. },
  26222. enumerable: true,
  26223. configurable: true
  26224. });
  26225. Object.defineProperty(Material.prototype, "pointsCloud", {
  26226. get: function () {
  26227. return this._fillMode === Material.PointFillMode;
  26228. },
  26229. set: function (value) {
  26230. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  26231. },
  26232. enumerable: true,
  26233. configurable: true
  26234. });
  26235. Object.defineProperty(Material.prototype, "fillMode", {
  26236. get: function () {
  26237. return this._fillMode;
  26238. },
  26239. set: function (value) {
  26240. this._fillMode = value;
  26241. },
  26242. enumerable: true,
  26243. configurable: true
  26244. });
  26245. /**
  26246. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26247. * subclasses should override adding information pertainent to themselves
  26248. */
  26249. Material.prototype.toString = function (fullDetails) {
  26250. var ret = "Name: " + this.name;
  26251. if (fullDetails) {
  26252. }
  26253. return ret;
  26254. };
  26255. Material.prototype.getClassName = function () {
  26256. return "Material";
  26257. };
  26258. Object.defineProperty(Material.prototype, "isFrozen", {
  26259. get: function () {
  26260. return this.checkReadyOnlyOnce;
  26261. },
  26262. enumerable: true,
  26263. configurable: true
  26264. });
  26265. Material.prototype.freeze = function () {
  26266. this.checkReadyOnlyOnce = true;
  26267. };
  26268. Material.prototype.unfreeze = function () {
  26269. this.checkReadyOnlyOnce = false;
  26270. };
  26271. Material.prototype.isReady = function (mesh, useInstances) {
  26272. return true;
  26273. };
  26274. Material.prototype.getEffect = function () {
  26275. return this._effect;
  26276. };
  26277. Material.prototype.getScene = function () {
  26278. return this._scene;
  26279. };
  26280. Material.prototype.needAlphaBlending = function () {
  26281. return (this.alpha < 1.0);
  26282. };
  26283. Material.prototype.needAlphaTesting = function () {
  26284. return false;
  26285. };
  26286. Material.prototype.getAlphaTestTexture = function () {
  26287. return null;
  26288. };
  26289. Material.prototype.markDirty = function () {
  26290. this._wasPreviouslyReady = false;
  26291. };
  26292. Material.prototype._preBind = function () {
  26293. var engine = this._scene.getEngine();
  26294. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  26295. engine.enableEffect(this._effect);
  26296. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  26297. };
  26298. Material.prototype.bind = function (world, mesh) {
  26299. this._scene._cachedMaterial = this;
  26300. this.onBindObservable.notifyObservers(mesh);
  26301. if (this.disableDepthWrite) {
  26302. var engine = this._scene.getEngine();
  26303. this._cachedDepthWriteState = engine.getDepthWrite();
  26304. engine.setDepthWrite(false);
  26305. }
  26306. };
  26307. Material.prototype.bindOnlyWorldMatrix = function (world) {
  26308. };
  26309. Material.prototype.unbind = function () {
  26310. this.onUnBindObservable.notifyObservers(this);
  26311. if (this.disableDepthWrite) {
  26312. var engine = this._scene.getEngine();
  26313. engine.setDepthWrite(this._cachedDepthWriteState);
  26314. }
  26315. };
  26316. Material.prototype.clone = function (name) {
  26317. return null;
  26318. };
  26319. Material.prototype.getBindedMeshes = function () {
  26320. var result = new Array();
  26321. for (var index = 0; index < this._scene.meshes.length; index++) {
  26322. var mesh = this._scene.meshes[index];
  26323. if (mesh.material === this) {
  26324. result.push(mesh);
  26325. }
  26326. }
  26327. return result;
  26328. };
  26329. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26330. // Animations
  26331. this.getScene().stopAnimation(this);
  26332. // Remove from scene
  26333. var index = this._scene.materials.indexOf(this);
  26334. if (index >= 0) {
  26335. this._scene.materials.splice(index, 1);
  26336. }
  26337. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  26338. if (forceDisposeEffect && this._effect) {
  26339. this._scene.getEngine()._releaseEffect(this._effect);
  26340. this._effect = null;
  26341. }
  26342. // Remove from meshes
  26343. for (index = 0; index < this._scene.meshes.length; index++) {
  26344. var mesh = this._scene.meshes[index];
  26345. if (mesh.material === this) {
  26346. mesh.material = null;
  26347. }
  26348. }
  26349. // Callback
  26350. this.onDisposeObservable.notifyObservers(this);
  26351. this.onDisposeObservable.clear();
  26352. this.onBindObservable.clear();
  26353. this.onUnBindObservable.clear();
  26354. };
  26355. Material.prototype.serialize = function () {
  26356. return BABYLON.SerializationHelper.Serialize(this);
  26357. };
  26358. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  26359. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  26360. multiMaterial.id = parsedMultiMaterial.id;
  26361. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  26362. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  26363. var subMatId = parsedMultiMaterial.materials[matIndex];
  26364. if (subMatId) {
  26365. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  26366. }
  26367. else {
  26368. multiMaterial.subMaterials.push(null);
  26369. }
  26370. }
  26371. return multiMaterial;
  26372. };
  26373. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  26374. if (!parsedMaterial.customType) {
  26375. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  26376. }
  26377. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  26378. return materialType.Parse(parsedMaterial, scene, rootUrl);
  26379. ;
  26380. };
  26381. return Material;
  26382. }());
  26383. Material._TriangleFillMode = 0;
  26384. Material._WireFrameFillMode = 1;
  26385. Material._PointFillMode = 2;
  26386. Material._ClockWiseSideOrientation = 0;
  26387. Material._CounterClockWiseSideOrientation = 1;
  26388. __decorate([
  26389. BABYLON.serialize()
  26390. ], Material.prototype, "id", void 0);
  26391. __decorate([
  26392. BABYLON.serialize()
  26393. ], Material.prototype, "name", void 0);
  26394. __decorate([
  26395. BABYLON.serialize()
  26396. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  26397. __decorate([
  26398. BABYLON.serialize()
  26399. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  26400. __decorate([
  26401. BABYLON.serialize()
  26402. ], Material.prototype, "state", void 0);
  26403. __decorate([
  26404. BABYLON.serialize()
  26405. ], Material.prototype, "alpha", void 0);
  26406. __decorate([
  26407. BABYLON.serialize()
  26408. ], Material.prototype, "backFaceCulling", void 0);
  26409. __decorate([
  26410. BABYLON.serialize()
  26411. ], Material.prototype, "sideOrientation", void 0);
  26412. __decorate([
  26413. BABYLON.serialize()
  26414. ], Material.prototype, "alphaMode", void 0);
  26415. __decorate([
  26416. BABYLON.serialize()
  26417. ], Material.prototype, "disableDepthWrite", void 0);
  26418. __decorate([
  26419. BABYLON.serialize()
  26420. ], Material.prototype, "fogEnabled", void 0);
  26421. __decorate([
  26422. BABYLON.serialize()
  26423. ], Material.prototype, "pointSize", void 0);
  26424. __decorate([
  26425. BABYLON.serialize()
  26426. ], Material.prototype, "zOffset", void 0);
  26427. __decorate([
  26428. BABYLON.serialize()
  26429. ], Material.prototype, "wireframe", null);
  26430. __decorate([
  26431. BABYLON.serialize()
  26432. ], Material.prototype, "pointsCloud", null);
  26433. __decorate([
  26434. BABYLON.serialize()
  26435. ], Material.prototype, "fillMode", null);
  26436. BABYLON.Material = Material;
  26437. })(BABYLON || (BABYLON = {}));
  26438. //# sourceMappingURL=babylon.material.js.map
  26439. var BABYLON;
  26440. (function (BABYLON) {
  26441. var StandardMaterialDefines = (function (_super) {
  26442. __extends(StandardMaterialDefines, _super);
  26443. function StandardMaterialDefines() {
  26444. var _this = _super.call(this) || this;
  26445. _this.DIFFUSE = false;
  26446. _this.AMBIENT = false;
  26447. _this.OPACITY = false;
  26448. _this.OPACITYRGB = false;
  26449. _this.REFLECTION = false;
  26450. _this.EMISSIVE = false;
  26451. _this.SPECULAR = false;
  26452. _this.BUMP = false;
  26453. _this.PARALLAX = false;
  26454. _this.PARALLAXOCCLUSION = false;
  26455. _this.SPECULAROVERALPHA = false;
  26456. _this.CLIPPLANE = false;
  26457. _this.ALPHATEST = false;
  26458. _this.ALPHAFROMDIFFUSE = false;
  26459. _this.POINTSIZE = false;
  26460. _this.FOG = false;
  26461. _this.SPECULARTERM = false;
  26462. _this.DIFFUSEFRESNEL = false;
  26463. _this.OPACITYFRESNEL = false;
  26464. _this.REFLECTIONFRESNEL = false;
  26465. _this.REFRACTIONFRESNEL = false;
  26466. _this.EMISSIVEFRESNEL = false;
  26467. _this.FRESNEL = false;
  26468. _this.NORMAL = false;
  26469. _this.UV1 = false;
  26470. _this.UV2 = false;
  26471. _this.VERTEXCOLOR = false;
  26472. _this.VERTEXALPHA = false;
  26473. _this.NUM_BONE_INFLUENCERS = 0;
  26474. _this.BonesPerMesh = 0;
  26475. _this.INSTANCES = false;
  26476. _this.GLOSSINESS = false;
  26477. _this.ROUGHNESS = false;
  26478. _this.EMISSIVEASILLUMINATION = false;
  26479. _this.LINKEMISSIVEWITHDIFFUSE = false;
  26480. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  26481. _this.LIGHTMAP = false;
  26482. _this.USELIGHTMAPASSHADOWMAP = false;
  26483. _this.REFLECTIONMAP_3D = false;
  26484. _this.REFLECTIONMAP_SPHERICAL = false;
  26485. _this.REFLECTIONMAP_PLANAR = false;
  26486. _this.REFLECTIONMAP_CUBIC = false;
  26487. _this.REFLECTIONMAP_PROJECTION = false;
  26488. _this.REFLECTIONMAP_SKYBOX = false;
  26489. _this.REFLECTIONMAP_EXPLICIT = false;
  26490. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  26491. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  26492. _this.INVERTCUBICMAP = false;
  26493. _this.LOGARITHMICDEPTH = false;
  26494. _this.REFRACTION = false;
  26495. _this.REFRACTIONMAP_3D = false;
  26496. _this.REFLECTIONOVERALPHA = false;
  26497. _this.INVERTNORMALMAPX = false;
  26498. _this.INVERTNORMALMAPY = false;
  26499. _this.SHADOWFULLFLOAT = false;
  26500. _this.CAMERACOLORGRADING = false;
  26501. _this.CAMERACOLORCURVES = false;
  26502. _this.rebuild();
  26503. return _this;
  26504. }
  26505. return StandardMaterialDefines;
  26506. }(BABYLON.MaterialDefines));
  26507. var StandardMaterial = (function (_super) {
  26508. __extends(StandardMaterial, _super);
  26509. function StandardMaterial(name, scene) {
  26510. var _this = _super.call(this, name, scene) || this;
  26511. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  26512. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  26513. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  26514. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  26515. _this.specularPower = 64;
  26516. _this.useAlphaFromDiffuseTexture = false;
  26517. _this.useEmissiveAsIllumination = false;
  26518. _this.linkEmissiveWithDiffuse = false;
  26519. _this.useReflectionFresnelFromSpecular = false;
  26520. _this.useSpecularOverAlpha = false;
  26521. _this.useReflectionOverAlpha = false;
  26522. _this.disableLighting = false;
  26523. _this.useParallax = false;
  26524. _this.useParallaxOcclusion = false;
  26525. _this.parallaxScaleBias = 0.05;
  26526. _this.roughness = 0;
  26527. _this.indexOfRefraction = 0.98;
  26528. _this.invertRefractionY = true;
  26529. _this.useLightmapAsShadowmap = false;
  26530. _this.useGlossinessFromSpecularMapAlpha = false;
  26531. _this.maxSimultaneousLights = 4;
  26532. /**
  26533. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  26534. */
  26535. _this.invertNormalMapX = false;
  26536. /**
  26537. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  26538. */
  26539. _this.invertNormalMapY = false;
  26540. /**
  26541. * Color Grading 2D Lookup Texture.
  26542. * This allows special effects like sepia, black and white to sixties rendering style.
  26543. */
  26544. _this.cameraColorGradingTexture = null;
  26545. /**
  26546. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  26547. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  26548. * 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;
  26549. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  26550. */
  26551. _this.cameraColorCurves = null;
  26552. _this._renderTargets = new BABYLON.SmartArray(16);
  26553. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  26554. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  26555. _this._defines = new StandardMaterialDefines();
  26556. _this._cachedDefines = new StandardMaterialDefines();
  26557. _this._cachedDefines.BonesPerMesh = -1;
  26558. _this.getRenderTargetTextures = function () {
  26559. _this._renderTargets.reset();
  26560. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  26561. _this._renderTargets.push(_this.reflectionTexture);
  26562. }
  26563. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  26564. _this._renderTargets.push(_this.refractionTexture);
  26565. }
  26566. return _this._renderTargets;
  26567. };
  26568. return _this;
  26569. }
  26570. StandardMaterial.prototype.getClassName = function () {
  26571. return "StandardMaterial";
  26572. };
  26573. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  26574. get: function () {
  26575. return this._useLogarithmicDepth;
  26576. },
  26577. set: function (value) {
  26578. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  26579. },
  26580. enumerable: true,
  26581. configurable: true
  26582. });
  26583. StandardMaterial.prototype.needAlphaBlending = function () {
  26584. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  26585. };
  26586. StandardMaterial.prototype.needAlphaTesting = function () {
  26587. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  26588. };
  26589. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  26590. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  26591. };
  26592. StandardMaterial.prototype.getAlphaTestTexture = function () {
  26593. return this.diffuseTexture;
  26594. };
  26595. // Methods
  26596. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  26597. if (!mesh) {
  26598. return true;
  26599. }
  26600. if (this._defines.INSTANCES !== useInstances) {
  26601. return false;
  26602. }
  26603. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  26604. return true;
  26605. }
  26606. return false;
  26607. };
  26608. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  26609. if (this.isFrozen) {
  26610. if (this._wasPreviouslyReady) {
  26611. return true;
  26612. }
  26613. }
  26614. var scene = this.getScene();
  26615. var engine = scene.getEngine();
  26616. var needUVs = false;
  26617. var needNormals = false;
  26618. this._defines.reset();
  26619. // Lights
  26620. if (scene.lightsEnabled && !this.disableLighting) {
  26621. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  26622. }
  26623. if (!this.checkReadyOnEveryCall) {
  26624. if (this._renderId === scene.getRenderId()) {
  26625. if (this._checkCache(scene, mesh, useInstances)) {
  26626. return true;
  26627. }
  26628. }
  26629. }
  26630. // Textures
  26631. if (scene.texturesEnabled) {
  26632. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26633. if (!this.diffuseTexture.isReady()) {
  26634. return false;
  26635. }
  26636. else {
  26637. needUVs = true;
  26638. this._defines.DIFFUSE = true;
  26639. }
  26640. }
  26641. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26642. if (!this.ambientTexture.isReady()) {
  26643. return false;
  26644. }
  26645. else {
  26646. needUVs = true;
  26647. this._defines.AMBIENT = true;
  26648. }
  26649. }
  26650. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26651. if (!this.opacityTexture.isReady()) {
  26652. return false;
  26653. }
  26654. else {
  26655. needUVs = true;
  26656. this._defines.OPACITY = true;
  26657. if (this.opacityTexture.getAlphaFromRGB) {
  26658. this._defines.OPACITYRGB = true;
  26659. }
  26660. }
  26661. }
  26662. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26663. if (!this.reflectionTexture.isReady()) {
  26664. return false;
  26665. }
  26666. else {
  26667. needNormals = true;
  26668. this._defines.REFLECTION = true;
  26669. if (this.roughness > 0) {
  26670. this._defines.ROUGHNESS = true;
  26671. }
  26672. if (this.useReflectionOverAlpha) {
  26673. this._defines.REFLECTIONOVERALPHA = true;
  26674. }
  26675. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  26676. this._defines.INVERTCUBICMAP = true;
  26677. }
  26678. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  26679. switch (this.reflectionTexture.coordinatesMode) {
  26680. case BABYLON.Texture.CUBIC_MODE:
  26681. case BABYLON.Texture.INVCUBIC_MODE:
  26682. this._defines.REFLECTIONMAP_CUBIC = true;
  26683. break;
  26684. case BABYLON.Texture.EXPLICIT_MODE:
  26685. this._defines.REFLECTIONMAP_EXPLICIT = true;
  26686. break;
  26687. case BABYLON.Texture.PLANAR_MODE:
  26688. this._defines.REFLECTIONMAP_PLANAR = true;
  26689. break;
  26690. case BABYLON.Texture.PROJECTION_MODE:
  26691. this._defines.REFLECTIONMAP_PROJECTION = true;
  26692. break;
  26693. case BABYLON.Texture.SKYBOX_MODE:
  26694. this._defines.REFLECTIONMAP_SKYBOX = true;
  26695. break;
  26696. case BABYLON.Texture.SPHERICAL_MODE:
  26697. this._defines.REFLECTIONMAP_SPHERICAL = true;
  26698. break;
  26699. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  26700. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  26701. break;
  26702. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  26703. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  26704. break;
  26705. }
  26706. }
  26707. }
  26708. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26709. if (!this.emissiveTexture.isReady()) {
  26710. return false;
  26711. }
  26712. else {
  26713. needUVs = true;
  26714. this._defines.EMISSIVE = true;
  26715. }
  26716. }
  26717. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26718. if (!this.lightmapTexture.isReady()) {
  26719. return false;
  26720. }
  26721. else {
  26722. needUVs = true;
  26723. this._defines.LIGHTMAP = true;
  26724. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  26725. }
  26726. }
  26727. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26728. if (!this.specularTexture.isReady()) {
  26729. return false;
  26730. }
  26731. else {
  26732. needUVs = true;
  26733. this._defines.SPECULAR = true;
  26734. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  26735. }
  26736. }
  26737. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  26738. if (!this.bumpTexture.isReady()) {
  26739. return false;
  26740. }
  26741. else {
  26742. needUVs = true;
  26743. this._defines.BUMP = true;
  26744. if (this.useParallax) {
  26745. this._defines.PARALLAX = true;
  26746. if (this.useParallaxOcclusion) {
  26747. this._defines.PARALLAXOCCLUSION = true;
  26748. }
  26749. }
  26750. if (this.invertNormalMapX) {
  26751. this._defines.INVERTNORMALMAPX = true;
  26752. }
  26753. if (this.invertNormalMapY) {
  26754. this._defines.INVERTNORMALMAPY = true;
  26755. }
  26756. if (scene._mirroredCameraPosition) {
  26757. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  26758. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  26759. }
  26760. }
  26761. }
  26762. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26763. if (!this.refractionTexture.isReady()) {
  26764. return false;
  26765. }
  26766. else {
  26767. needUVs = true;
  26768. this._defines.REFRACTION = true;
  26769. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  26770. }
  26771. }
  26772. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26773. if (!this.cameraColorGradingTexture.isReady()) {
  26774. return false;
  26775. }
  26776. else {
  26777. this._defines.CAMERACOLORGRADING = true;
  26778. }
  26779. }
  26780. }
  26781. // Effect
  26782. if (scene.clipPlane) {
  26783. this._defines.CLIPPLANE = true;
  26784. }
  26785. if (engine.getAlphaTesting()) {
  26786. this._defines.ALPHATEST = true;
  26787. }
  26788. if (this._shouldUseAlphaFromDiffuseTexture()) {
  26789. this._defines.ALPHAFROMDIFFUSE = true;
  26790. }
  26791. if (this.useEmissiveAsIllumination) {
  26792. this._defines.EMISSIVEASILLUMINATION = true;
  26793. }
  26794. if (this.linkEmissiveWithDiffuse) {
  26795. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  26796. }
  26797. if (this.useLogarithmicDepth) {
  26798. this._defines.LOGARITHMICDEPTH = true;
  26799. }
  26800. if (this.cameraColorCurves) {
  26801. this._defines.CAMERACOLORCURVES = true;
  26802. }
  26803. // Point size
  26804. if (this.pointsCloud || scene.forcePointsCloud) {
  26805. this._defines.POINTSIZE = true;
  26806. }
  26807. // Fog
  26808. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26809. this._defines.FOG = true;
  26810. }
  26811. if (StandardMaterial.FresnelEnabled) {
  26812. // Fresnel
  26813. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  26814. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  26815. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  26816. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  26817. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26818. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26819. this._defines.DIFFUSEFRESNEL = true;
  26820. }
  26821. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26822. this._defines.OPACITYFRESNEL = true;
  26823. }
  26824. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26825. this._defines.REFLECTIONFRESNEL = true;
  26826. if (this.useReflectionFresnelFromSpecular) {
  26827. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  26828. }
  26829. }
  26830. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26831. this._defines.REFRACTIONFRESNEL = true;
  26832. }
  26833. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26834. this._defines.EMISSIVEFRESNEL = true;
  26835. }
  26836. needNormals = true;
  26837. this._defines.FRESNEL = true;
  26838. }
  26839. }
  26840. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  26841. this._defines.SPECULAROVERALPHA = true;
  26842. }
  26843. // Attribs
  26844. if (mesh) {
  26845. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26846. this._defines.NORMAL = true;
  26847. }
  26848. if (needUVs) {
  26849. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26850. this._defines.UV1 = true;
  26851. }
  26852. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26853. this._defines.UV2 = true;
  26854. }
  26855. }
  26856. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26857. this._defines.VERTEXCOLOR = true;
  26858. if (mesh.hasVertexAlpha) {
  26859. this._defines.VERTEXALPHA = true;
  26860. }
  26861. }
  26862. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  26863. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  26864. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  26865. }
  26866. // Instances
  26867. if (useInstances) {
  26868. this._defines.INSTANCES = true;
  26869. }
  26870. }
  26871. // Get correct effect
  26872. if (!this._defines.isEqual(this._cachedDefines)) {
  26873. this._defines.cloneTo(this._cachedDefines);
  26874. scene.resetCachedMaterial();
  26875. // Fallbacks
  26876. var fallbacks = new BABYLON.EffectFallbacks();
  26877. if (this._defines.REFLECTION) {
  26878. fallbacks.addFallback(0, "REFLECTION");
  26879. }
  26880. if (this._defines.SPECULAR) {
  26881. fallbacks.addFallback(0, "SPECULAR");
  26882. }
  26883. if (this._defines.BUMP) {
  26884. fallbacks.addFallback(0, "BUMP");
  26885. }
  26886. if (this._defines.PARALLAX) {
  26887. fallbacks.addFallback(1, "PARALLAX");
  26888. }
  26889. if (this._defines.PARALLAXOCCLUSION) {
  26890. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  26891. }
  26892. if (this._defines.SPECULAROVERALPHA) {
  26893. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  26894. }
  26895. if (this._defines.FOG) {
  26896. fallbacks.addFallback(1, "FOG");
  26897. }
  26898. if (this._defines.POINTSIZE) {
  26899. fallbacks.addFallback(0, "POINTSIZE");
  26900. }
  26901. if (this._defines.LOGARITHMICDEPTH) {
  26902. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  26903. }
  26904. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  26905. if (this._defines.SPECULARTERM) {
  26906. fallbacks.addFallback(0, "SPECULARTERM");
  26907. }
  26908. if (this._defines.DIFFUSEFRESNEL) {
  26909. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  26910. }
  26911. if (this._defines.OPACITYFRESNEL) {
  26912. fallbacks.addFallback(2, "OPACITYFRESNEL");
  26913. }
  26914. if (this._defines.REFLECTIONFRESNEL) {
  26915. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  26916. }
  26917. if (this._defines.EMISSIVEFRESNEL) {
  26918. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  26919. }
  26920. if (this._defines.FRESNEL) {
  26921. fallbacks.addFallback(4, "FRESNEL");
  26922. }
  26923. //Attributes
  26924. var attribs = [BABYLON.VertexBuffer.PositionKind];
  26925. if (this._defines.NORMAL) {
  26926. attribs.push(BABYLON.VertexBuffer.NormalKind);
  26927. }
  26928. if (this._defines.UV1) {
  26929. attribs.push(BABYLON.VertexBuffer.UVKind);
  26930. }
  26931. if (this._defines.UV2) {
  26932. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26933. }
  26934. if (this._defines.VERTEXCOLOR) {
  26935. attribs.push(BABYLON.VertexBuffer.ColorKind);
  26936. }
  26937. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  26938. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  26939. var shaderName = "default";
  26940. var join = this._defines.toString();
  26941. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  26942. "vFogInfos", "vFogColor", "pointSize",
  26943. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  26944. "mBones",
  26945. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  26946. "depthValues",
  26947. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  26948. "logarithmicDepthConstant"
  26949. ];
  26950. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  26951. if (this._defines.CAMERACOLORCURVES) {
  26952. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  26953. }
  26954. if (this._defines.CAMERACOLORGRADING) {
  26955. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  26956. }
  26957. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  26958. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  26959. }
  26960. if (!this._effect.isReady()) {
  26961. return false;
  26962. }
  26963. this._renderId = scene.getRenderId();
  26964. this._wasPreviouslyReady = true;
  26965. if (mesh) {
  26966. if (!mesh._materialDefines) {
  26967. mesh._materialDefines = new StandardMaterialDefines();
  26968. }
  26969. this._defines.cloneTo(mesh._materialDefines);
  26970. }
  26971. return true;
  26972. };
  26973. StandardMaterial.prototype.unbind = function () {
  26974. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  26975. this._effect.setTexture("reflection2DSampler", null);
  26976. }
  26977. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  26978. this._effect.setTexture("refraction2DSampler", null);
  26979. }
  26980. _super.prototype.unbind.call(this);
  26981. };
  26982. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26983. this._effect.setMatrix("world", world);
  26984. };
  26985. StandardMaterial.prototype.bind = function (world, mesh) {
  26986. var scene = this.getScene();
  26987. // Matrices
  26988. this.bindOnlyWorldMatrix(world);
  26989. // Bones
  26990. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  26991. if (scene.getCachedMaterial() !== this) {
  26992. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26993. if (StandardMaterial.FresnelEnabled) {
  26994. // Fresnel
  26995. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26996. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  26997. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  26998. }
  26999. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  27000. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  27001. }
  27002. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  27003. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  27004. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  27005. }
  27006. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  27007. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  27008. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  27009. }
  27010. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  27011. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  27012. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  27013. }
  27014. }
  27015. // Textures
  27016. if (scene.texturesEnabled) {
  27017. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27018. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  27019. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  27020. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  27021. }
  27022. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27023. this._effect.setTexture("ambientSampler", this.ambientTexture);
  27024. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  27025. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  27026. }
  27027. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27028. this._effect.setTexture("opacitySampler", this.opacityTexture);
  27029. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  27030. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  27031. }
  27032. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27033. if (this.reflectionTexture.isCube) {
  27034. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  27035. }
  27036. else {
  27037. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  27038. }
  27039. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  27040. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  27041. }
  27042. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27043. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  27044. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  27045. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  27046. }
  27047. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27048. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  27049. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  27050. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  27051. }
  27052. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27053. this._effect.setTexture("specularSampler", this.specularTexture);
  27054. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  27055. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  27056. }
  27057. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  27058. this._effect.setTexture("bumpSampler", this.bumpTexture);
  27059. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  27060. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  27061. }
  27062. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27063. var depth = 1.0;
  27064. if (this.refractionTexture.isCube) {
  27065. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  27066. }
  27067. else {
  27068. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  27069. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  27070. if (this.refractionTexture.depth) {
  27071. depth = this.refractionTexture.depth;
  27072. }
  27073. }
  27074. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  27075. }
  27076. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  27077. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  27078. }
  27079. }
  27080. // Clip plane
  27081. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  27082. // Point size
  27083. if (this.pointsCloud) {
  27084. this._effect.setFloat("pointSize", this.pointSize);
  27085. }
  27086. // Colors
  27087. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  27088. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  27089. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  27090. if (this._defines.SPECULARTERM) {
  27091. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  27092. }
  27093. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  27094. }
  27095. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  27096. // Diffuse
  27097. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  27098. // Lights
  27099. if (scene.lightsEnabled && !this.disableLighting) {
  27100. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  27101. }
  27102. // View
  27103. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  27104. this._effect.setMatrix("view", scene.getViewMatrix());
  27105. }
  27106. // Fog
  27107. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  27108. // Log. depth
  27109. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  27110. // Color Curves
  27111. if (this.cameraColorCurves) {
  27112. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  27113. }
  27114. }
  27115. _super.prototype.bind.call(this, world, mesh);
  27116. };
  27117. StandardMaterial.prototype.getAnimatables = function () {
  27118. var results = [];
  27119. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  27120. results.push(this.diffuseTexture);
  27121. }
  27122. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  27123. results.push(this.ambientTexture);
  27124. }
  27125. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  27126. results.push(this.opacityTexture);
  27127. }
  27128. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  27129. results.push(this.reflectionTexture);
  27130. }
  27131. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  27132. results.push(this.emissiveTexture);
  27133. }
  27134. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  27135. results.push(this.specularTexture);
  27136. }
  27137. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  27138. results.push(this.bumpTexture);
  27139. }
  27140. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  27141. results.push(this.lightmapTexture);
  27142. }
  27143. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  27144. results.push(this.refractionTexture);
  27145. }
  27146. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  27147. results.push(this.cameraColorGradingTexture);
  27148. }
  27149. return results;
  27150. };
  27151. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27152. if (forceDisposeTextures) {
  27153. if (this.diffuseTexture) {
  27154. this.diffuseTexture.dispose();
  27155. }
  27156. if (this.ambientTexture) {
  27157. this.ambientTexture.dispose();
  27158. }
  27159. if (this.opacityTexture) {
  27160. this.opacityTexture.dispose();
  27161. }
  27162. if (this.reflectionTexture) {
  27163. this.reflectionTexture.dispose();
  27164. }
  27165. if (this.emissiveTexture) {
  27166. this.emissiveTexture.dispose();
  27167. }
  27168. if (this.specularTexture) {
  27169. this.specularTexture.dispose();
  27170. }
  27171. if (this.bumpTexture) {
  27172. this.bumpTexture.dispose();
  27173. }
  27174. if (this.lightmapTexture) {
  27175. this.lightmapTexture.dispose();
  27176. }
  27177. if (this.refractionTexture) {
  27178. this.refractionTexture.dispose();
  27179. }
  27180. if (this.cameraColorGradingTexture) {
  27181. this.cameraColorGradingTexture.dispose();
  27182. }
  27183. }
  27184. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  27185. };
  27186. StandardMaterial.prototype.clone = function (name) {
  27187. var _this = this;
  27188. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  27189. };
  27190. StandardMaterial.prototype.serialize = function () {
  27191. return BABYLON.SerializationHelper.Serialize(this);
  27192. };
  27193. // Statics
  27194. StandardMaterial.Parse = function (source, scene, rootUrl) {
  27195. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  27196. };
  27197. return StandardMaterial;
  27198. }(BABYLON.Material));
  27199. // Flags used to enable or disable a type of texture for all Standard Materials
  27200. StandardMaterial.DiffuseTextureEnabled = true;
  27201. StandardMaterial.AmbientTextureEnabled = true;
  27202. StandardMaterial.OpacityTextureEnabled = true;
  27203. StandardMaterial.ReflectionTextureEnabled = true;
  27204. StandardMaterial.EmissiveTextureEnabled = true;
  27205. StandardMaterial.SpecularTextureEnabled = true;
  27206. StandardMaterial.BumpTextureEnabled = true;
  27207. StandardMaterial.FresnelEnabled = true;
  27208. StandardMaterial.LightmapTextureEnabled = true;
  27209. StandardMaterial.RefractionTextureEnabled = true;
  27210. StandardMaterial.ColorGradingTextureEnabled = true;
  27211. __decorate([
  27212. BABYLON.serializeAsTexture()
  27213. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  27214. __decorate([
  27215. BABYLON.serializeAsTexture()
  27216. ], StandardMaterial.prototype, "ambientTexture", void 0);
  27217. __decorate([
  27218. BABYLON.serializeAsTexture()
  27219. ], StandardMaterial.prototype, "opacityTexture", void 0);
  27220. __decorate([
  27221. BABYLON.serializeAsTexture()
  27222. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  27223. __decorate([
  27224. BABYLON.serializeAsTexture()
  27225. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  27226. __decorate([
  27227. BABYLON.serializeAsTexture()
  27228. ], StandardMaterial.prototype, "specularTexture", void 0);
  27229. __decorate([
  27230. BABYLON.serializeAsTexture()
  27231. ], StandardMaterial.prototype, "bumpTexture", void 0);
  27232. __decorate([
  27233. BABYLON.serializeAsTexture()
  27234. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  27235. __decorate([
  27236. BABYLON.serializeAsTexture()
  27237. ], StandardMaterial.prototype, "refractionTexture", void 0);
  27238. __decorate([
  27239. BABYLON.serializeAsColor3("ambient")
  27240. ], StandardMaterial.prototype, "ambientColor", void 0);
  27241. __decorate([
  27242. BABYLON.serializeAsColor3("diffuse")
  27243. ], StandardMaterial.prototype, "diffuseColor", void 0);
  27244. __decorate([
  27245. BABYLON.serializeAsColor3("specular")
  27246. ], StandardMaterial.prototype, "specularColor", void 0);
  27247. __decorate([
  27248. BABYLON.serializeAsColor3("emissive")
  27249. ], StandardMaterial.prototype, "emissiveColor", void 0);
  27250. __decorate([
  27251. BABYLON.serialize()
  27252. ], StandardMaterial.prototype, "specularPower", void 0);
  27253. __decorate([
  27254. BABYLON.serialize()
  27255. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  27256. __decorate([
  27257. BABYLON.serialize()
  27258. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  27259. __decorate([
  27260. BABYLON.serialize()
  27261. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  27262. __decorate([
  27263. BABYLON.serialize()
  27264. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  27265. __decorate([
  27266. BABYLON.serialize()
  27267. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  27268. __decorate([
  27269. BABYLON.serialize()
  27270. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  27271. __decorate([
  27272. BABYLON.serialize()
  27273. ], StandardMaterial.prototype, "disableLighting", void 0);
  27274. __decorate([
  27275. BABYLON.serialize()
  27276. ], StandardMaterial.prototype, "useParallax", void 0);
  27277. __decorate([
  27278. BABYLON.serialize()
  27279. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  27280. __decorate([
  27281. BABYLON.serialize()
  27282. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  27283. __decorate([
  27284. BABYLON.serialize()
  27285. ], StandardMaterial.prototype, "roughness", void 0);
  27286. __decorate([
  27287. BABYLON.serialize()
  27288. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  27289. __decorate([
  27290. BABYLON.serialize()
  27291. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  27292. __decorate([
  27293. BABYLON.serialize()
  27294. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  27295. __decorate([
  27296. BABYLON.serializeAsFresnelParameters()
  27297. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  27298. __decorate([
  27299. BABYLON.serializeAsFresnelParameters()
  27300. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  27301. __decorate([
  27302. BABYLON.serializeAsFresnelParameters()
  27303. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  27304. __decorate([
  27305. BABYLON.serializeAsFresnelParameters()
  27306. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  27307. __decorate([
  27308. BABYLON.serializeAsFresnelParameters()
  27309. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  27310. __decorate([
  27311. BABYLON.serialize()
  27312. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  27313. __decorate([
  27314. BABYLON.serialize()
  27315. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  27316. __decorate([
  27317. BABYLON.serialize()
  27318. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  27319. __decorate([
  27320. BABYLON.serialize()
  27321. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  27322. __decorate([
  27323. BABYLON.serializeAsTexture()
  27324. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  27325. __decorate([
  27326. BABYLON.serializeAsColorCurves()
  27327. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  27328. __decorate([
  27329. BABYLON.serialize()
  27330. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  27331. BABYLON.StandardMaterial = StandardMaterial;
  27332. })(BABYLON || (BABYLON = {}));
  27333. //# sourceMappingURL=babylon.standardMaterial.js.map
  27334. var BABYLON;
  27335. (function (BABYLON) {
  27336. var MultiMaterial = (function (_super) {
  27337. __extends(MultiMaterial, _super);
  27338. function MultiMaterial(name, scene) {
  27339. var _this = _super.call(this, name, scene, true) || this;
  27340. _this.subMaterials = new Array();
  27341. scene.multiMaterials.push(_this);
  27342. return _this;
  27343. }
  27344. // Properties
  27345. MultiMaterial.prototype.getSubMaterial = function (index) {
  27346. if (index < 0 || index >= this.subMaterials.length) {
  27347. return this.getScene().defaultMaterial;
  27348. }
  27349. return this.subMaterials[index];
  27350. };
  27351. // Methods
  27352. MultiMaterial.prototype.getClassName = function () {
  27353. return "MultiMaterial";
  27354. };
  27355. MultiMaterial.prototype.isReady = function (mesh) {
  27356. for (var index = 0; index < this.subMaterials.length; index++) {
  27357. var subMaterial = this.subMaterials[index];
  27358. if (subMaterial) {
  27359. if (!this.subMaterials[index].isReady(mesh)) {
  27360. return false;
  27361. }
  27362. }
  27363. }
  27364. return true;
  27365. };
  27366. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  27367. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  27368. for (var index = 0; index < this.subMaterials.length; index++) {
  27369. var subMaterial = null;
  27370. if (cloneChildren) {
  27371. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  27372. }
  27373. else {
  27374. subMaterial = this.subMaterials[index];
  27375. }
  27376. newMultiMaterial.subMaterials.push(subMaterial);
  27377. }
  27378. return newMultiMaterial;
  27379. };
  27380. MultiMaterial.prototype.serialize = function () {
  27381. var serializationObject = {};
  27382. serializationObject.name = this.name;
  27383. serializationObject.id = this.id;
  27384. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27385. serializationObject.materials = [];
  27386. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  27387. var subMat = this.subMaterials[matIndex];
  27388. if (subMat) {
  27389. serializationObject.materials.push(subMat.id);
  27390. }
  27391. else {
  27392. serializationObject.materials.push(null);
  27393. }
  27394. }
  27395. return serializationObject;
  27396. };
  27397. return MultiMaterial;
  27398. }(BABYLON.Material));
  27399. BABYLON.MultiMaterial = MultiMaterial;
  27400. })(BABYLON || (BABYLON = {}));
  27401. //# sourceMappingURL=babylon.multiMaterial.js.map
  27402. var BABYLON;
  27403. (function (BABYLON) {
  27404. var SceneLoader = (function () {
  27405. function SceneLoader() {
  27406. }
  27407. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  27408. get: function () {
  27409. return 0;
  27410. },
  27411. enumerable: true,
  27412. configurable: true
  27413. });
  27414. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  27415. get: function () {
  27416. return 1;
  27417. },
  27418. enumerable: true,
  27419. configurable: true
  27420. });
  27421. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  27422. get: function () {
  27423. return 2;
  27424. },
  27425. enumerable: true,
  27426. configurable: true
  27427. });
  27428. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  27429. get: function () {
  27430. return 3;
  27431. },
  27432. enumerable: true,
  27433. configurable: true
  27434. });
  27435. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  27436. get: function () {
  27437. return SceneLoader._ForceFullSceneLoadingForIncremental;
  27438. },
  27439. set: function (value) {
  27440. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  27441. },
  27442. enumerable: true,
  27443. configurable: true
  27444. });
  27445. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  27446. get: function () {
  27447. return SceneLoader._ShowLoadingScreen;
  27448. },
  27449. set: function (value) {
  27450. SceneLoader._ShowLoadingScreen = value;
  27451. },
  27452. enumerable: true,
  27453. configurable: true
  27454. });
  27455. Object.defineProperty(SceneLoader, "loggingLevel", {
  27456. get: function () {
  27457. return SceneLoader._loggingLevel;
  27458. },
  27459. set: function (value) {
  27460. SceneLoader._loggingLevel = value;
  27461. },
  27462. enumerable: true,
  27463. configurable: true
  27464. });
  27465. SceneLoader._getDefaultPlugin = function () {
  27466. return SceneLoader._registeredPlugins[".babylon"];
  27467. };
  27468. SceneLoader._getPluginForExtension = function (extension) {
  27469. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  27470. if (registeredPlugin) {
  27471. return registeredPlugin;
  27472. }
  27473. return SceneLoader._getDefaultPlugin();
  27474. };
  27475. SceneLoader._getPluginForFilename = function (sceneFilename) {
  27476. if (sceneFilename.name) {
  27477. sceneFilename = sceneFilename.name;
  27478. }
  27479. var dotPosition = sceneFilename.lastIndexOf(".");
  27480. var queryStringPosition = sceneFilename.indexOf("?");
  27481. if (queryStringPosition === -1) {
  27482. queryStringPosition = sceneFilename.length;
  27483. }
  27484. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  27485. return SceneLoader._getPluginForExtension(extension);
  27486. };
  27487. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  27488. SceneLoader._getDirectLoad = function (sceneFilename) {
  27489. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  27490. return sceneFilename.substr(5);
  27491. }
  27492. return null;
  27493. };
  27494. // Public functions
  27495. SceneLoader.GetPluginForExtension = function (extension) {
  27496. return SceneLoader._getPluginForExtension(extension).plugin;
  27497. };
  27498. SceneLoader.RegisterPlugin = function (plugin) {
  27499. if (typeof plugin.extensions === "string") {
  27500. var extension = plugin.extensions;
  27501. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  27502. plugin: plugin,
  27503. isBinary: false
  27504. };
  27505. }
  27506. else {
  27507. var extensions = plugin.extensions;
  27508. Object.keys(extensions).forEach(function (extension) {
  27509. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  27510. plugin: plugin,
  27511. isBinary: extensions[extension].isBinary
  27512. };
  27513. });
  27514. }
  27515. };
  27516. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  27517. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27518. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27519. return;
  27520. }
  27521. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27522. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27523. return;
  27524. }
  27525. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  27526. var loadingToken = {};
  27527. scene._addPendingData(loadingToken);
  27528. var manifestChecked = function (success) {
  27529. scene.database = database;
  27530. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  27531. var plugin = registeredPlugin.plugin;
  27532. var useArrayBuffer = registeredPlugin.isBinary;
  27533. var importMeshFromData = function (data) {
  27534. var meshes = [];
  27535. var particleSystems = [];
  27536. var skeletons = [];
  27537. try {
  27538. if (plugin.importMesh) {
  27539. var syncedPlugin = plugin;
  27540. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  27541. if (onerror) {
  27542. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  27543. }
  27544. scene._removePendingData(loadingToken);
  27545. return;
  27546. }
  27547. if (onsuccess) {
  27548. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  27549. onsuccess(meshes, particleSystems, skeletons);
  27550. scene._removePendingData(loadingToken);
  27551. }
  27552. }
  27553. else {
  27554. var asyncedPlugin = plugin;
  27555. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  27556. if (onsuccess) {
  27557. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  27558. onsuccess(meshes, particleSystems, skeletons);
  27559. scene._removePendingData(loadingToken);
  27560. }
  27561. }, function () {
  27562. if (onerror) {
  27563. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  27564. }
  27565. scene._removePendingData(loadingToken);
  27566. });
  27567. }
  27568. }
  27569. catch (e) {
  27570. if (onerror) {
  27571. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  27572. }
  27573. scene._removePendingData(loadingToken);
  27574. }
  27575. };
  27576. if (directLoad) {
  27577. importMeshFromData(directLoad);
  27578. return;
  27579. }
  27580. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  27581. importMeshFromData(data);
  27582. }, progressCallBack, database, useArrayBuffer);
  27583. };
  27584. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  27585. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  27586. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  27587. }
  27588. else {
  27589. // If the scene is a data stream or offline support is not enabled, it's a direct load
  27590. manifestChecked(true);
  27591. }
  27592. };
  27593. /**
  27594. * Load a scene
  27595. * @param rootUrl a string that defines the root url for scene and resources
  27596. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  27597. * @param engine is the instance of BABYLON.Engine to use to create the scene
  27598. */
  27599. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  27600. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  27601. };
  27602. /**
  27603. * Append a scene
  27604. * @param rootUrl a string that defines the root url for scene and resources
  27605. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  27606. * @param scene is the instance of BABYLON.Scene to append to
  27607. */
  27608. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  27609. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27610. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27611. return;
  27612. }
  27613. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  27614. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  27615. var plugin = registeredPlugin.plugin;
  27616. var useArrayBuffer = registeredPlugin.isBinary;
  27617. var database;
  27618. var loadingToken = {};
  27619. scene._addPendingData(loadingToken);
  27620. if (SceneLoader.ShowLoadingScreen) {
  27621. scene.getEngine().displayLoadingUI();
  27622. }
  27623. var loadSceneFromData = function (data) {
  27624. scene.database = database;
  27625. if (plugin.load) {
  27626. var syncedPlugin = plugin;
  27627. if (!syncedPlugin.load(scene, data, rootUrl)) {
  27628. if (onerror) {
  27629. onerror(scene);
  27630. }
  27631. scene._removePendingData(loadingToken);
  27632. scene.getEngine().hideLoadingUI();
  27633. return;
  27634. }
  27635. if (onsuccess) {
  27636. onsuccess(scene);
  27637. }
  27638. scene._removePendingData(loadingToken);
  27639. }
  27640. else {
  27641. var asyncedPlugin = plugin;
  27642. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  27643. if (onsuccess) {
  27644. onsuccess(scene);
  27645. }
  27646. scene._removePendingData(loadingToken);
  27647. }, function () {
  27648. if (onerror) {
  27649. onerror(scene);
  27650. }
  27651. scene._removePendingData(loadingToken);
  27652. scene.getEngine().hideLoadingUI();
  27653. });
  27654. }
  27655. if (SceneLoader.ShowLoadingScreen) {
  27656. scene.executeWhenReady(function () {
  27657. scene.getEngine().hideLoadingUI();
  27658. });
  27659. }
  27660. };
  27661. var manifestChecked = function (success) {
  27662. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  27663. };
  27664. if (directLoad) {
  27665. loadSceneFromData(directLoad);
  27666. return;
  27667. }
  27668. if (rootUrl.indexOf("file:") === -1) {
  27669. if (scene.getEngine().enableOfflineSupport) {
  27670. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  27671. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  27672. }
  27673. else {
  27674. manifestChecked(true);
  27675. }
  27676. }
  27677. else {
  27678. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  27679. }
  27680. };
  27681. return SceneLoader;
  27682. }());
  27683. // Flags
  27684. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  27685. SceneLoader._ShowLoadingScreen = true;
  27686. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  27687. // Members
  27688. SceneLoader._registeredPlugins = {};
  27689. BABYLON.SceneLoader = SceneLoader;
  27690. ;
  27691. })(BABYLON || (BABYLON = {}));
  27692. //# sourceMappingURL=babylon.sceneLoader.js.map
  27693. var BABYLON;
  27694. (function (BABYLON) {
  27695. var Internals;
  27696. (function (Internals) {
  27697. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  27698. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  27699. var parsedMaterial = parsedData.materials[index];
  27700. if (parsedMaterial.id === id) {
  27701. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  27702. }
  27703. }
  27704. return null;
  27705. };
  27706. var isDescendantOf = function (mesh, names, hierarchyIds) {
  27707. names = (names instanceof Array) ? names : [names];
  27708. for (var i in names) {
  27709. if (mesh.name === names[i]) {
  27710. hierarchyIds.push(mesh.id);
  27711. return true;
  27712. }
  27713. }
  27714. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  27715. hierarchyIds.push(mesh.id);
  27716. return true;
  27717. }
  27718. return false;
  27719. };
  27720. var logOperation = function (operation, producer) {
  27721. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  27722. };
  27723. BABYLON.SceneLoader.RegisterPlugin({
  27724. extensions: ".babylon",
  27725. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  27726. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  27727. // when SceneLoader.debugLogging = true (default), or exception encountered.
  27728. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  27729. // and avoid problems with multiple concurrent .babylon loads.
  27730. var log = "importMesh has failed JSON parse";
  27731. try {
  27732. var parsedData = JSON.parse(data);
  27733. log = "";
  27734. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  27735. var loadedSkeletonsIds = [];
  27736. var loadedMaterialsIds = [];
  27737. var hierarchyIds = [];
  27738. var index;
  27739. var cache;
  27740. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  27741. var parsedMesh = parsedData.meshes[index];
  27742. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  27743. if (meshesNames instanceof Array) {
  27744. // Remove found mesh name from list.
  27745. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  27746. }
  27747. //Geometry?
  27748. if (parsedMesh.geometryId) {
  27749. //does the file contain geometries?
  27750. if (parsedData.geometries) {
  27751. //find the correct geometry and add it to the scene
  27752. var found = false;
  27753. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  27754. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  27755. return;
  27756. }
  27757. else {
  27758. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  27759. if (parsedGeometryData.id === parsedMesh.geometryId) {
  27760. switch (geometryType) {
  27761. case "boxes":
  27762. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  27763. break;
  27764. case "spheres":
  27765. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  27766. break;
  27767. case "cylinders":
  27768. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  27769. break;
  27770. case "toruses":
  27771. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  27772. break;
  27773. case "grounds":
  27774. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  27775. break;
  27776. case "planes":
  27777. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  27778. break;
  27779. case "torusKnots":
  27780. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  27781. break;
  27782. case "vertexData":
  27783. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  27784. break;
  27785. }
  27786. found = true;
  27787. }
  27788. });
  27789. }
  27790. });
  27791. if (!found) {
  27792. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  27793. }
  27794. }
  27795. }
  27796. // Material ?
  27797. if (parsedMesh.materialId) {
  27798. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  27799. if (!materialFound && parsedData.multiMaterials) {
  27800. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  27801. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  27802. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  27803. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  27804. var subMatId = parsedMultiMaterial.materials[matIndex];
  27805. loadedMaterialsIds.push(subMatId);
  27806. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  27807. log += "\n\tMaterial " + mat.toString(fullDetails);
  27808. }
  27809. loadedMaterialsIds.push(parsedMultiMaterial.id);
  27810. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  27811. materialFound = true;
  27812. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  27813. break;
  27814. }
  27815. }
  27816. }
  27817. if (!materialFound) {
  27818. loadedMaterialsIds.push(parsedMesh.materialId);
  27819. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  27820. if (!mat) {
  27821. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  27822. }
  27823. else {
  27824. log += "\n\tMaterial " + mat.toString(fullDetails);
  27825. }
  27826. }
  27827. }
  27828. // Skeleton ?
  27829. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  27830. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  27831. if (!skeletonAlreadyLoaded) {
  27832. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  27833. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  27834. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  27835. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27836. skeletons.push(skeleton);
  27837. loadedSkeletonsIds.push(parsedSkeleton.id);
  27838. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  27839. }
  27840. }
  27841. }
  27842. }
  27843. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27844. meshes.push(mesh);
  27845. log += "\n\tMesh " + mesh.toString(fullDetails);
  27846. }
  27847. }
  27848. // Connecting parents
  27849. var currentMesh;
  27850. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27851. currentMesh = scene.meshes[index];
  27852. if (currentMesh._waitingParentId) {
  27853. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  27854. currentMesh._waitingParentId = undefined;
  27855. }
  27856. }
  27857. // freeze and compute world matrix application
  27858. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27859. currentMesh = scene.meshes[index];
  27860. if (currentMesh._waitingFreezeWorldMatrix) {
  27861. currentMesh.freezeWorldMatrix();
  27862. currentMesh._waitingFreezeWorldMatrix = undefined;
  27863. }
  27864. else {
  27865. currentMesh.computeWorldMatrix(true);
  27866. }
  27867. }
  27868. // Particles
  27869. if (parsedData.particleSystems) {
  27870. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27871. var parsedParticleSystem = parsedData.particleSystems[index];
  27872. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  27873. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  27874. }
  27875. }
  27876. }
  27877. return true;
  27878. }
  27879. catch (err) {
  27880. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  27881. log = null;
  27882. throw err;
  27883. }
  27884. finally {
  27885. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  27886. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  27887. }
  27888. }
  27889. },
  27890. load: function (scene, data, rootUrl) {
  27891. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  27892. // when SceneLoader.debugLogging = true (default), or exception encountered.
  27893. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  27894. // and avoid problems with multiple concurrent .babylon loads.
  27895. var log = "importScene has failed JSON parse";
  27896. try {
  27897. var parsedData = JSON.parse(data);
  27898. log = "";
  27899. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  27900. // Scene
  27901. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  27902. scene.autoClear = parsedData.autoClear;
  27903. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  27904. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  27905. if (parsedData.gravity) {
  27906. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  27907. }
  27908. // Fog
  27909. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  27910. scene.fogMode = parsedData.fogMode;
  27911. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  27912. scene.fogStart = parsedData.fogStart;
  27913. scene.fogEnd = parsedData.fogEnd;
  27914. scene.fogDensity = parsedData.fogDensity;
  27915. log += "\tFog mode for scene: ";
  27916. switch (scene.fogMode) {
  27917. // getters not compiling, so using hardcoded
  27918. case 1:
  27919. log += "exp\n";
  27920. break;
  27921. case 2:
  27922. log += "exp2\n";
  27923. break;
  27924. case 3:
  27925. log += "linear\n";
  27926. break;
  27927. }
  27928. }
  27929. //Physics
  27930. if (parsedData.physicsEnabled) {
  27931. var physicsPlugin;
  27932. if (parsedData.physicsEngine === "cannon") {
  27933. physicsPlugin = new BABYLON.CannonJSPlugin();
  27934. }
  27935. else if (parsedData.physicsEngine === "oimo") {
  27936. physicsPlugin = new BABYLON.OimoJSPlugin();
  27937. }
  27938. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  27939. //else - default engine, which is currently oimo
  27940. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  27941. scene.enablePhysics(physicsGravity, physicsPlugin);
  27942. }
  27943. // Metadata
  27944. if (parsedData.metadata !== undefined) {
  27945. scene.metadata = parsedData.metadata;
  27946. }
  27947. //collisions, if defined. otherwise, default is true
  27948. if (parsedData.collisionsEnabled != undefined) {
  27949. scene.collisionsEnabled = parsedData.collisionsEnabled;
  27950. }
  27951. scene.workerCollisions = !!parsedData.workerCollisions;
  27952. var index;
  27953. var cache;
  27954. // Lights
  27955. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  27956. var parsedLight = parsedData.lights[index];
  27957. var light = BABYLON.Light.Parse(parsedLight, scene);
  27958. log += (index === 0 ? "\n\tLights:" : "");
  27959. log += "\n\t\t" + light.toString(fullDetails);
  27960. }
  27961. // Animations
  27962. if (parsedData.animations) {
  27963. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  27964. var parsedAnimation = parsedData.animations[index];
  27965. var animation = BABYLON.Animation.Parse(parsedAnimation);
  27966. scene.animations.push(animation);
  27967. log += (index === 0 ? "\n\tAnimations:" : "");
  27968. log += "\n\t\t" + animation.toString(fullDetails);
  27969. }
  27970. }
  27971. if (parsedData.autoAnimate) {
  27972. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  27973. }
  27974. // Materials
  27975. if (parsedData.materials) {
  27976. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  27977. var parsedMaterial = parsedData.materials[index];
  27978. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  27979. log += (index === 0 ? "\n\tMaterials:" : "");
  27980. log += "\n\t\t" + mat.toString(fullDetails);
  27981. }
  27982. }
  27983. if (parsedData.multiMaterials) {
  27984. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  27985. var parsedMultiMaterial = parsedData.multiMaterials[index];
  27986. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  27987. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  27988. log += "\n\t\t" + mmat.toString(fullDetails);
  27989. }
  27990. }
  27991. // Skeletons
  27992. if (parsedData.skeletons) {
  27993. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  27994. var parsedSkeleton = parsedData.skeletons[index];
  27995. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27996. log += (index === 0 ? "\n\tSkeletons:" : "");
  27997. log += "\n\t\t" + skeleton.toString(fullDetails);
  27998. }
  27999. }
  28000. // Geometries
  28001. var geometries = parsedData.geometries;
  28002. if (geometries) {
  28003. // Boxes
  28004. var boxes = geometries.boxes;
  28005. if (boxes) {
  28006. for (index = 0, cache = boxes.length; index < cache; index++) {
  28007. var parsedBox = boxes[index];
  28008. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  28009. }
  28010. }
  28011. // Spheres
  28012. var spheres = geometries.spheres;
  28013. if (spheres) {
  28014. for (index = 0, cache = spheres.length; index < cache; index++) {
  28015. var parsedSphere = spheres[index];
  28016. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  28017. }
  28018. }
  28019. // Cylinders
  28020. var cylinders = geometries.cylinders;
  28021. if (cylinders) {
  28022. for (index = 0, cache = cylinders.length; index < cache; index++) {
  28023. var parsedCylinder = cylinders[index];
  28024. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  28025. }
  28026. }
  28027. // Toruses
  28028. var toruses = geometries.toruses;
  28029. if (toruses) {
  28030. for (index = 0, cache = toruses.length; index < cache; index++) {
  28031. var parsedTorus = toruses[index];
  28032. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  28033. }
  28034. }
  28035. // Grounds
  28036. var grounds = geometries.grounds;
  28037. if (grounds) {
  28038. for (index = 0, cache = grounds.length; index < cache; index++) {
  28039. var parsedGround = grounds[index];
  28040. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  28041. }
  28042. }
  28043. // Planes
  28044. var planes = geometries.planes;
  28045. if (planes) {
  28046. for (index = 0, cache = planes.length; index < cache; index++) {
  28047. var parsedPlane = planes[index];
  28048. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  28049. }
  28050. }
  28051. // TorusKnots
  28052. var torusKnots = geometries.torusKnots;
  28053. if (torusKnots) {
  28054. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  28055. var parsedTorusKnot = torusKnots[index];
  28056. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  28057. }
  28058. }
  28059. // VertexData
  28060. var vertexData = geometries.vertexData;
  28061. if (vertexData) {
  28062. for (index = 0, cache = vertexData.length; index < cache; index++) {
  28063. var parsedVertexData = vertexData[index];
  28064. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  28065. }
  28066. }
  28067. }
  28068. // Meshes
  28069. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  28070. var parsedMesh = parsedData.meshes[index];
  28071. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  28072. log += (index === 0 ? "\n\tMeshes:" : "");
  28073. log += "\n\t\t" + mesh.toString(fullDetails);
  28074. }
  28075. // Cameras
  28076. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  28077. var parsedCamera = parsedData.cameras[index];
  28078. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  28079. log += (index === 0 ? "\n\tCameras:" : "");
  28080. log += "\n\t\t" + camera.toString(fullDetails);
  28081. }
  28082. if (parsedData.activeCameraID) {
  28083. scene.setActiveCameraByID(parsedData.activeCameraID);
  28084. }
  28085. // Browsing all the graph to connect the dots
  28086. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  28087. var camera = scene.cameras[index];
  28088. if (camera._waitingParentId) {
  28089. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  28090. camera._waitingParentId = undefined;
  28091. }
  28092. }
  28093. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  28094. var light = scene.lights[index];
  28095. if (light._waitingParentId) {
  28096. light.parent = scene.getLastEntryByID(light._waitingParentId);
  28097. light._waitingParentId = undefined;
  28098. }
  28099. }
  28100. // Sounds
  28101. var loadedSounds = [];
  28102. var loadedSound;
  28103. if (BABYLON.AudioEngine && parsedData.sounds) {
  28104. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  28105. var parsedSound = parsedData.sounds[index];
  28106. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28107. if (!parsedSound.url)
  28108. parsedSound.url = parsedSound.name;
  28109. if (!loadedSounds[parsedSound.url]) {
  28110. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  28111. loadedSounds[parsedSound.url] = loadedSound;
  28112. }
  28113. else {
  28114. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  28115. }
  28116. }
  28117. else {
  28118. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  28119. }
  28120. }
  28121. }
  28122. loadedSounds = [];
  28123. // Connect parents & children and parse actions
  28124. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28125. var mesh = scene.meshes[index];
  28126. if (mesh._waitingParentId) {
  28127. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  28128. mesh._waitingParentId = undefined;
  28129. }
  28130. if (mesh._waitingActions) {
  28131. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  28132. mesh._waitingActions = undefined;
  28133. }
  28134. }
  28135. // freeze world matrix application
  28136. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28137. var currentMesh = scene.meshes[index];
  28138. if (currentMesh._waitingFreezeWorldMatrix) {
  28139. currentMesh.freezeWorldMatrix();
  28140. currentMesh._waitingFreezeWorldMatrix = undefined;
  28141. }
  28142. else {
  28143. currentMesh.computeWorldMatrix(true);
  28144. }
  28145. }
  28146. // Particles Systems
  28147. if (parsedData.particleSystems) {
  28148. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  28149. var parsedParticleSystem = parsedData.particleSystems[index];
  28150. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  28151. }
  28152. }
  28153. // Lens flares
  28154. if (parsedData.lensFlareSystems) {
  28155. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  28156. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  28157. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  28158. }
  28159. }
  28160. // Shadows
  28161. if (parsedData.shadowGenerators) {
  28162. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  28163. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  28164. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  28165. }
  28166. }
  28167. // Actions (scene)
  28168. if (parsedData.actions) {
  28169. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  28170. }
  28171. // Finish
  28172. return true;
  28173. }
  28174. catch (err) {
  28175. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  28176. log = null;
  28177. throw err;
  28178. }
  28179. finally {
  28180. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  28181. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  28182. }
  28183. }
  28184. }
  28185. });
  28186. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28187. })(BABYLON || (BABYLON = {}));
  28188. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  28189. var BABYLON;
  28190. (function (BABYLON) {
  28191. var SpriteManager = (function () {
  28192. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  28193. if (epsilon === void 0) { epsilon = 0.01; }
  28194. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28195. this.name = name;
  28196. this.sprites = new Array();
  28197. this.renderingGroupId = 0;
  28198. this.layerMask = 0x0FFFFFFF;
  28199. this.fogEnabled = true;
  28200. this.isPickable = false;
  28201. /**
  28202. * An event triggered when the manager is disposed.
  28203. * @type {BABYLON.Observable}
  28204. */
  28205. this.onDisposeObservable = new BABYLON.Observable();
  28206. this._vertexBuffers = {};
  28207. this._capacity = capacity;
  28208. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  28209. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28210. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28211. if (cellSize.width && cellSize.height) {
  28212. this.cellWidth = cellSize.width;
  28213. this.cellHeight = cellSize.height;
  28214. }
  28215. else if (cellSize !== undefined) {
  28216. this.cellWidth = cellSize;
  28217. this.cellHeight = cellSize;
  28218. }
  28219. else {
  28220. return;
  28221. }
  28222. this._epsilon = epsilon;
  28223. this._scene = scene;
  28224. this._scene.spriteManagers.push(this);
  28225. var indices = [];
  28226. var index = 0;
  28227. for (var count = 0; count < capacity; count++) {
  28228. indices.push(index);
  28229. indices.push(index + 1);
  28230. indices.push(index + 2);
  28231. indices.push(index);
  28232. indices.push(index + 2);
  28233. indices.push(index + 3);
  28234. index += 4;
  28235. }
  28236. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  28237. // VBO
  28238. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  28239. this._vertexData = new Float32Array(capacity * 16 * 4);
  28240. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  28241. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  28242. var options = this._buffer.createVertexBuffer("options", 4, 4);
  28243. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  28244. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  28245. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  28246. this._vertexBuffers["options"] = options;
  28247. this._vertexBuffers["cellInfo"] = cellInfo;
  28248. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  28249. // Effects
  28250. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  28251. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  28252. }
  28253. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  28254. set: function (callback) {
  28255. if (this._onDisposeObserver) {
  28256. this.onDisposeObservable.remove(this._onDisposeObserver);
  28257. }
  28258. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28259. },
  28260. enumerable: true,
  28261. configurable: true
  28262. });
  28263. Object.defineProperty(SpriteManager.prototype, "texture", {
  28264. get: function () {
  28265. return this._spriteTexture;
  28266. },
  28267. set: function (value) {
  28268. this._spriteTexture = value;
  28269. },
  28270. enumerable: true,
  28271. configurable: true
  28272. });
  28273. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  28274. var arrayOffset = index * 16;
  28275. if (offsetX === 0)
  28276. offsetX = this._epsilon;
  28277. else if (offsetX === 1)
  28278. offsetX = 1 - this._epsilon;
  28279. if (offsetY === 0)
  28280. offsetY = this._epsilon;
  28281. else if (offsetY === 1)
  28282. offsetY = 1 - this._epsilon;
  28283. this._vertexData[arrayOffset] = sprite.position.x;
  28284. this._vertexData[arrayOffset + 1] = sprite.position.y;
  28285. this._vertexData[arrayOffset + 2] = sprite.position.z;
  28286. this._vertexData[arrayOffset + 3] = sprite.angle;
  28287. this._vertexData[arrayOffset + 4] = sprite.width;
  28288. this._vertexData[arrayOffset + 5] = sprite.height;
  28289. this._vertexData[arrayOffset + 6] = offsetX;
  28290. this._vertexData[arrayOffset + 7] = offsetY;
  28291. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  28292. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  28293. var offset = (sprite.cellIndex / rowSize) >> 0;
  28294. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  28295. this._vertexData[arrayOffset + 11] = offset;
  28296. // Color
  28297. this._vertexData[arrayOffset + 12] = sprite.color.r;
  28298. this._vertexData[arrayOffset + 13] = sprite.color.g;
  28299. this._vertexData[arrayOffset + 14] = sprite.color.b;
  28300. this._vertexData[arrayOffset + 15] = sprite.color.a;
  28301. };
  28302. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  28303. var count = Math.min(this._capacity, this.sprites.length);
  28304. var min = BABYLON.Vector3.Zero();
  28305. var max = BABYLON.Vector3.Zero();
  28306. var distance = Number.MAX_VALUE;
  28307. var currentSprite;
  28308. var cameraSpacePosition = BABYLON.Vector3.Zero();
  28309. var cameraView = camera.getViewMatrix();
  28310. for (var index = 0; index < count; index++) {
  28311. var sprite = this.sprites[index];
  28312. if (!sprite) {
  28313. continue;
  28314. }
  28315. if (predicate) {
  28316. if (!predicate(sprite)) {
  28317. continue;
  28318. }
  28319. }
  28320. else if (!sprite.isPickable) {
  28321. continue;
  28322. }
  28323. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  28324. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  28325. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  28326. if (ray.intersectsBoxMinMax(min, max)) {
  28327. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  28328. if (distance > currentDistance) {
  28329. distance = currentDistance;
  28330. currentSprite = sprite;
  28331. if (fastCheck) {
  28332. break;
  28333. }
  28334. }
  28335. }
  28336. }
  28337. if (currentSprite) {
  28338. var result = new BABYLON.PickingInfo();
  28339. result.hit = true;
  28340. result.pickedSprite = currentSprite;
  28341. result.distance = distance;
  28342. return result;
  28343. }
  28344. return null;
  28345. };
  28346. SpriteManager.prototype.render = function () {
  28347. // Check
  28348. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  28349. return;
  28350. var engine = this._scene.getEngine();
  28351. var baseSize = this._spriteTexture.getBaseSize();
  28352. // Sprites
  28353. var deltaTime = engine.getDeltaTime();
  28354. var max = Math.min(this._capacity, this.sprites.length);
  28355. var rowSize = baseSize.width / this.cellWidth;
  28356. var offset = 0;
  28357. for (var index = 0; index < max; index++) {
  28358. var sprite = this.sprites[index];
  28359. if (!sprite) {
  28360. continue;
  28361. }
  28362. sprite._animate(deltaTime);
  28363. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  28364. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  28365. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  28366. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  28367. }
  28368. this._buffer.update(this._vertexData);
  28369. // Render
  28370. var effect = this._effectBase;
  28371. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28372. effect = this._effectFog;
  28373. }
  28374. engine.enableEffect(effect);
  28375. var viewMatrix = this._scene.getViewMatrix();
  28376. effect.setTexture("diffuseSampler", this._spriteTexture);
  28377. effect.setMatrix("view", viewMatrix);
  28378. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  28379. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  28380. // Fog
  28381. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28382. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  28383. effect.setColor3("vFogColor", this._scene.fogColor);
  28384. }
  28385. // VBOs
  28386. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28387. // Draw order
  28388. engine.setDepthFunctionToLessOrEqual();
  28389. effect.setBool("alphaTest", true);
  28390. engine.setColorWrite(false);
  28391. engine.draw(true, 0, max * 6);
  28392. engine.setColorWrite(true);
  28393. effect.setBool("alphaTest", false);
  28394. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28395. engine.draw(true, 0, max * 6);
  28396. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28397. };
  28398. SpriteManager.prototype.dispose = function () {
  28399. if (this._buffer) {
  28400. this._buffer.dispose();
  28401. this._buffer = null;
  28402. }
  28403. if (this._indexBuffer) {
  28404. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28405. this._indexBuffer = null;
  28406. }
  28407. if (this._spriteTexture) {
  28408. this._spriteTexture.dispose();
  28409. this._spriteTexture = null;
  28410. }
  28411. // Remove from scene
  28412. var index = this._scene.spriteManagers.indexOf(this);
  28413. this._scene.spriteManagers.splice(index, 1);
  28414. // Callback
  28415. this.onDisposeObservable.notifyObservers(this);
  28416. this.onDisposeObservable.clear();
  28417. };
  28418. return SpriteManager;
  28419. }());
  28420. BABYLON.SpriteManager = SpriteManager;
  28421. })(BABYLON || (BABYLON = {}));
  28422. //# sourceMappingURL=babylon.spriteManager.js.map
  28423. var BABYLON;
  28424. (function (BABYLON) {
  28425. var Sprite = (function () {
  28426. function Sprite(name, manager) {
  28427. this.name = name;
  28428. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28429. this.width = 1.0;
  28430. this.height = 1.0;
  28431. this.angle = 0;
  28432. this.cellIndex = 0;
  28433. this.invertU = 0;
  28434. this.invertV = 0;
  28435. this.animations = new Array();
  28436. this.isPickable = false;
  28437. this._animationStarted = false;
  28438. this._loopAnimation = false;
  28439. this._fromIndex = 0;
  28440. this._toIndex = 0;
  28441. this._delay = 0;
  28442. this._direction = 1;
  28443. this._frameCount = 0;
  28444. this._time = 0;
  28445. this._manager = manager;
  28446. this._manager.sprites.push(this);
  28447. this.position = BABYLON.Vector3.Zero();
  28448. }
  28449. Object.defineProperty(Sprite.prototype, "size", {
  28450. get: function () {
  28451. return this.width;
  28452. },
  28453. set: function (value) {
  28454. this.width = value;
  28455. this.height = value;
  28456. },
  28457. enumerable: true,
  28458. configurable: true
  28459. });
  28460. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  28461. this._fromIndex = from;
  28462. this._toIndex = to;
  28463. this._loopAnimation = loop;
  28464. this._delay = delay;
  28465. this._animationStarted = true;
  28466. this._direction = from < to ? 1 : -1;
  28467. this.cellIndex = from;
  28468. this._time = 0;
  28469. this._onAnimationEnd = onAnimationEnd;
  28470. };
  28471. Sprite.prototype.stopAnimation = function () {
  28472. this._animationStarted = false;
  28473. };
  28474. Sprite.prototype._animate = function (deltaTime) {
  28475. if (!this._animationStarted)
  28476. return;
  28477. this._time += deltaTime;
  28478. if (this._time > this._delay) {
  28479. this._time = this._time % this._delay;
  28480. this.cellIndex += this._direction;
  28481. if (this.cellIndex === this._toIndex) {
  28482. if (this._loopAnimation) {
  28483. this.cellIndex = this._fromIndex;
  28484. }
  28485. else {
  28486. this._animationStarted = false;
  28487. if (this._onAnimationEnd) {
  28488. this._onAnimationEnd();
  28489. }
  28490. if (this.disposeWhenFinishedAnimating) {
  28491. this.dispose();
  28492. }
  28493. }
  28494. }
  28495. }
  28496. };
  28497. Sprite.prototype.dispose = function () {
  28498. for (var i = 0; i < this._manager.sprites.length; i++) {
  28499. if (this._manager.sprites[i] == this) {
  28500. this._manager.sprites.splice(i, 1);
  28501. }
  28502. }
  28503. };
  28504. return Sprite;
  28505. }());
  28506. BABYLON.Sprite = Sprite;
  28507. })(BABYLON || (BABYLON = {}));
  28508. //# sourceMappingURL=babylon.sprite.js.map
  28509. var BABYLON;
  28510. (function (BABYLON) {
  28511. var Layer = (function () {
  28512. function Layer(name, imgUrl, scene, isBackground, color) {
  28513. this.name = name;
  28514. this.scale = new BABYLON.Vector2(1, 1);
  28515. this.offset = new BABYLON.Vector2(0, 0);
  28516. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  28517. this._vertexBuffers = {};
  28518. // Events
  28519. /**
  28520. * An event triggered when the layer is disposed.
  28521. * @type {BABYLON.Observable}
  28522. */
  28523. this.onDisposeObservable = new BABYLON.Observable();
  28524. /**
  28525. * An event triggered before rendering the scene
  28526. * @type {BABYLON.Observable}
  28527. */
  28528. this.onBeforeRenderObservable = new BABYLON.Observable();
  28529. /**
  28530. * An event triggered after rendering the scene
  28531. * @type {BABYLON.Observable}
  28532. */
  28533. this.onAfterRenderObservable = new BABYLON.Observable();
  28534. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  28535. this.isBackground = isBackground === undefined ? true : isBackground;
  28536. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  28537. this._scene = scene;
  28538. this._scene.layers.push(this);
  28539. var engine = scene.getEngine();
  28540. // VBO
  28541. var vertices = [];
  28542. vertices.push(1, 1);
  28543. vertices.push(-1, 1);
  28544. vertices.push(-1, -1);
  28545. vertices.push(1, -1);
  28546. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28547. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  28548. // Indices
  28549. var indices = [];
  28550. indices.push(0);
  28551. indices.push(1);
  28552. indices.push(2);
  28553. indices.push(0);
  28554. indices.push(2);
  28555. indices.push(3);
  28556. this._indexBuffer = engine.createIndexBuffer(indices);
  28557. // Effects
  28558. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  28559. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  28560. }
  28561. Object.defineProperty(Layer.prototype, "onDispose", {
  28562. set: function (callback) {
  28563. if (this._onDisposeObserver) {
  28564. this.onDisposeObservable.remove(this._onDisposeObserver);
  28565. }
  28566. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28567. },
  28568. enumerable: true,
  28569. configurable: true
  28570. });
  28571. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  28572. set: function (callback) {
  28573. if (this._onBeforeRenderObserver) {
  28574. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  28575. }
  28576. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  28577. },
  28578. enumerable: true,
  28579. configurable: true
  28580. });
  28581. Object.defineProperty(Layer.prototype, "onAfterRender", {
  28582. set: function (callback) {
  28583. if (this._onAfterRenderObserver) {
  28584. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  28585. }
  28586. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  28587. },
  28588. enumerable: true,
  28589. configurable: true
  28590. });
  28591. Layer.prototype.render = function () {
  28592. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  28593. // Check
  28594. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  28595. return;
  28596. var engine = this._scene.getEngine();
  28597. this.onBeforeRenderObservable.notifyObservers(this);
  28598. // Render
  28599. engine.enableEffect(currentEffect);
  28600. engine.setState(false);
  28601. // Texture
  28602. currentEffect.setTexture("textureSampler", this.texture);
  28603. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  28604. // Color
  28605. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  28606. // Scale / offset
  28607. currentEffect.setVector2("offset", this.offset);
  28608. currentEffect.setVector2("scale", this.scale);
  28609. // VBOs
  28610. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  28611. // Draw order
  28612. if (!this.alphaTest) {
  28613. engine.setAlphaMode(this.alphaBlendingMode);
  28614. engine.draw(true, 0, 6);
  28615. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28616. }
  28617. else {
  28618. engine.draw(true, 0, 6);
  28619. }
  28620. this.onAfterRenderObservable.notifyObservers(this);
  28621. };
  28622. Layer.prototype.dispose = function () {
  28623. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28624. if (vertexBuffer) {
  28625. vertexBuffer.dispose();
  28626. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28627. }
  28628. if (this._indexBuffer) {
  28629. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28630. this._indexBuffer = null;
  28631. }
  28632. if (this.texture) {
  28633. this.texture.dispose();
  28634. this.texture = null;
  28635. }
  28636. // Remove from scene
  28637. var index = this._scene.layers.indexOf(this);
  28638. this._scene.layers.splice(index, 1);
  28639. // Callback
  28640. this.onDisposeObservable.notifyObservers(this);
  28641. this.onDisposeObservable.clear();
  28642. this.onAfterRenderObservable.clear();
  28643. this.onBeforeRenderObservable.clear();
  28644. };
  28645. return Layer;
  28646. }());
  28647. BABYLON.Layer = Layer;
  28648. })(BABYLON || (BABYLON = {}));
  28649. //# sourceMappingURL=babylon.layer.js.map
  28650. var BABYLON;
  28651. (function (BABYLON) {
  28652. var Particle = (function () {
  28653. function Particle() {
  28654. this.position = BABYLON.Vector3.Zero();
  28655. this.direction = BABYLON.Vector3.Zero();
  28656. this.color = new BABYLON.Color4(0, 0, 0, 0);
  28657. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  28658. this.lifeTime = 1.0;
  28659. this.age = 0;
  28660. this.size = 0;
  28661. this.angle = 0;
  28662. this.angularSpeed = 0;
  28663. }
  28664. Particle.prototype.copyTo = function (other) {
  28665. other.position.copyFrom(this.position);
  28666. other.direction.copyFrom(this.direction);
  28667. other.color.copyFrom(this.color);
  28668. other.colorStep.copyFrom(this.colorStep);
  28669. other.lifeTime = this.lifeTime;
  28670. other.age = this.age;
  28671. other.size = this.size;
  28672. other.angle = this.angle;
  28673. other.angularSpeed = this.angularSpeed;
  28674. };
  28675. return Particle;
  28676. }());
  28677. BABYLON.Particle = Particle;
  28678. })(BABYLON || (BABYLON = {}));
  28679. //# sourceMappingURL=babylon.particle.js.map
  28680. var BABYLON;
  28681. (function (BABYLON) {
  28682. var randomNumber = function (min, max) {
  28683. if (min === max) {
  28684. return (min);
  28685. }
  28686. var random = Math.random();
  28687. return ((random * (max - min)) + min);
  28688. };
  28689. var ParticleSystem = (function () {
  28690. function ParticleSystem(name, capacity, scene, customEffect) {
  28691. var _this = this;
  28692. this.name = name;
  28693. // Members
  28694. this.animations = [];
  28695. this.renderingGroupId = 0;
  28696. this.emitter = null;
  28697. this.emitRate = 10;
  28698. this.manualEmitCount = -1;
  28699. this.updateSpeed = 0.01;
  28700. this.targetStopDuration = 0;
  28701. this.disposeOnStop = false;
  28702. this.minEmitPower = 1;
  28703. this.maxEmitPower = 1;
  28704. this.minLifeTime = 1;
  28705. this.maxLifeTime = 1;
  28706. this.minSize = 1;
  28707. this.maxSize = 1;
  28708. this.minAngularSpeed = 0;
  28709. this.maxAngularSpeed = 0;
  28710. this.layerMask = 0x0FFFFFFF;
  28711. /**
  28712. * An event triggered when the system is disposed.
  28713. * @type {BABYLON.Observable}
  28714. */
  28715. this.onDisposeObservable = new BABYLON.Observable();
  28716. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  28717. this.forceDepthWrite = false;
  28718. this.gravity = BABYLON.Vector3.Zero();
  28719. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  28720. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  28721. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  28722. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  28723. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28724. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28725. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  28726. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28727. this.particles = new Array();
  28728. this._stockParticles = new Array();
  28729. this._newPartsExcess = 0;
  28730. this._vertexBuffers = {};
  28731. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  28732. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  28733. this._scaledDirection = BABYLON.Vector3.Zero();
  28734. this._scaledGravity = BABYLON.Vector3.Zero();
  28735. this._currentRenderId = -1;
  28736. this._started = false;
  28737. this._stopped = false;
  28738. this._actualFrame = 0;
  28739. this.id = name;
  28740. this._capacity = capacity;
  28741. this._scene = scene;
  28742. this._customEffect = customEffect;
  28743. scene.particleSystems.push(this);
  28744. var indices = [];
  28745. var index = 0;
  28746. for (var count = 0; count < capacity; count++) {
  28747. indices.push(index);
  28748. indices.push(index + 1);
  28749. indices.push(index + 2);
  28750. indices.push(index);
  28751. indices.push(index + 2);
  28752. indices.push(index + 3);
  28753. index += 4;
  28754. }
  28755. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  28756. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  28757. this._vertexData = new Float32Array(capacity * 11 * 4);
  28758. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  28759. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  28760. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  28761. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  28762. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  28763. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  28764. this._vertexBuffers["options"] = options;
  28765. // Default behaviors
  28766. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  28767. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  28768. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  28769. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  28770. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  28771. };
  28772. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  28773. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  28774. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  28775. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  28776. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  28777. };
  28778. this.updateFunction = function (particles) {
  28779. for (var index = 0; index < particles.length; index++) {
  28780. var particle = particles[index];
  28781. particle.age += _this._scaledUpdateSpeed;
  28782. if (particle.age >= particle.lifeTime) {
  28783. _this.recycleParticle(particle);
  28784. index--;
  28785. continue;
  28786. }
  28787. else {
  28788. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  28789. particle.color.addInPlace(_this._scaledColorStep);
  28790. if (particle.color.a < 0)
  28791. particle.color.a = 0;
  28792. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  28793. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  28794. particle.position.addInPlace(_this._scaledDirection);
  28795. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  28796. particle.direction.addInPlace(_this._scaledGravity);
  28797. }
  28798. }
  28799. };
  28800. }
  28801. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  28802. set: function (callback) {
  28803. if (this._onDisposeObserver) {
  28804. this.onDisposeObservable.remove(this._onDisposeObserver);
  28805. }
  28806. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28807. },
  28808. enumerable: true,
  28809. configurable: true
  28810. });
  28811. ParticleSystem.prototype.recycleParticle = function (particle) {
  28812. var lastParticle = this.particles.pop();
  28813. if (lastParticle !== particle) {
  28814. lastParticle.copyTo(particle);
  28815. this._stockParticles.push(lastParticle);
  28816. }
  28817. };
  28818. ParticleSystem.prototype.getCapacity = function () {
  28819. return this._capacity;
  28820. };
  28821. ParticleSystem.prototype.isAlive = function () {
  28822. return this._alive;
  28823. };
  28824. ParticleSystem.prototype.isStarted = function () {
  28825. return this._started;
  28826. };
  28827. ParticleSystem.prototype.start = function () {
  28828. this._started = true;
  28829. this._stopped = false;
  28830. this._actualFrame = 0;
  28831. };
  28832. ParticleSystem.prototype.stop = function () {
  28833. this._stopped = true;
  28834. };
  28835. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  28836. var offset = index * 11;
  28837. this._vertexData[offset] = particle.position.x;
  28838. this._vertexData[offset + 1] = particle.position.y;
  28839. this._vertexData[offset + 2] = particle.position.z;
  28840. this._vertexData[offset + 3] = particle.color.r;
  28841. this._vertexData[offset + 4] = particle.color.g;
  28842. this._vertexData[offset + 5] = particle.color.b;
  28843. this._vertexData[offset + 6] = particle.color.a;
  28844. this._vertexData[offset + 7] = particle.angle;
  28845. this._vertexData[offset + 8] = particle.size;
  28846. this._vertexData[offset + 9] = offsetX;
  28847. this._vertexData[offset + 10] = offsetY;
  28848. };
  28849. ParticleSystem.prototype._update = function (newParticles) {
  28850. // Update current
  28851. this._alive = this.particles.length > 0;
  28852. this.updateFunction(this.particles);
  28853. // Add new ones
  28854. var worldMatrix;
  28855. if (this.emitter.position) {
  28856. worldMatrix = this.emitter.getWorldMatrix();
  28857. }
  28858. else {
  28859. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  28860. }
  28861. var particle;
  28862. for (var index = 0; index < newParticles; index++) {
  28863. if (this.particles.length === this._capacity) {
  28864. break;
  28865. }
  28866. if (this._stockParticles.length !== 0) {
  28867. particle = this._stockParticles.pop();
  28868. particle.age = 0;
  28869. }
  28870. else {
  28871. particle = new BABYLON.Particle();
  28872. }
  28873. this.particles.push(particle);
  28874. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  28875. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  28876. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  28877. particle.size = randomNumber(this.minSize, this.maxSize);
  28878. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  28879. this.startPositionFunction(worldMatrix, particle.position, particle);
  28880. var step = randomNumber(0, 1.0);
  28881. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  28882. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  28883. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  28884. }
  28885. };
  28886. ParticleSystem.prototype._getEffect = function () {
  28887. if (this._customEffect) {
  28888. return this._customEffect;
  28889. }
  28890. ;
  28891. var defines = [];
  28892. if (this._scene.clipPlane) {
  28893. defines.push("#define CLIPPLANE");
  28894. }
  28895. // Effect
  28896. var join = defines.join("\n");
  28897. if (this._cachedDefines !== join) {
  28898. this._cachedDefines = join;
  28899. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  28900. }
  28901. return this._effect;
  28902. };
  28903. ParticleSystem.prototype.animate = function () {
  28904. if (!this._started)
  28905. return;
  28906. var effect = this._getEffect();
  28907. // Check
  28908. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  28909. return;
  28910. if (this._currentRenderId === this._scene.getRenderId()) {
  28911. return;
  28912. }
  28913. this._currentRenderId = this._scene.getRenderId();
  28914. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  28915. // determine the number of particles we need to create
  28916. var newParticles;
  28917. if (this.manualEmitCount > -1) {
  28918. newParticles = this.manualEmitCount;
  28919. this._newPartsExcess = 0;
  28920. this.manualEmitCount = 0;
  28921. }
  28922. else {
  28923. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  28924. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  28925. }
  28926. if (this._newPartsExcess > 1.0) {
  28927. newParticles += this._newPartsExcess >> 0;
  28928. this._newPartsExcess -= this._newPartsExcess >> 0;
  28929. }
  28930. this._alive = false;
  28931. if (!this._stopped) {
  28932. this._actualFrame += this._scaledUpdateSpeed;
  28933. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  28934. this.stop();
  28935. }
  28936. else {
  28937. newParticles = 0;
  28938. }
  28939. this._update(newParticles);
  28940. // Stopped?
  28941. if (this._stopped) {
  28942. if (!this._alive) {
  28943. this._started = false;
  28944. if (this.disposeOnStop) {
  28945. this._scene._toBeDisposed.push(this);
  28946. }
  28947. }
  28948. }
  28949. // Update VBO
  28950. var offset = 0;
  28951. for (var index = 0; index < this.particles.length; index++) {
  28952. var particle = this.particles[index];
  28953. this._appendParticleVertex(offset++, particle, 0, 0);
  28954. this._appendParticleVertex(offset++, particle, 1, 0);
  28955. this._appendParticleVertex(offset++, particle, 1, 1);
  28956. this._appendParticleVertex(offset++, particle, 0, 1);
  28957. }
  28958. this._vertexBuffer.update(this._vertexData);
  28959. };
  28960. ParticleSystem.prototype.render = function () {
  28961. var effect = this._getEffect();
  28962. // Check
  28963. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  28964. return 0;
  28965. var engine = this._scene.getEngine();
  28966. // Render
  28967. engine.enableEffect(effect);
  28968. engine.setState(false);
  28969. var viewMatrix = this._scene.getViewMatrix();
  28970. effect.setTexture("diffuseSampler", this.particleTexture);
  28971. effect.setMatrix("view", viewMatrix);
  28972. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  28973. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  28974. if (this._scene.clipPlane) {
  28975. var clipPlane = this._scene.clipPlane;
  28976. var invView = viewMatrix.clone();
  28977. invView.invert();
  28978. effect.setMatrix("invView", invView);
  28979. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  28980. }
  28981. // VBOs
  28982. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28983. // Draw order
  28984. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  28985. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  28986. }
  28987. else {
  28988. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28989. }
  28990. if (this.forceDepthWrite) {
  28991. engine.setDepthWrite(true);
  28992. }
  28993. engine.draw(true, 0, this.particles.length * 6);
  28994. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28995. return this.particles.length;
  28996. };
  28997. ParticleSystem.prototype.dispose = function () {
  28998. if (this._vertexBuffer) {
  28999. this._vertexBuffer.dispose();
  29000. this._vertexBuffer = null;
  29001. }
  29002. if (this._indexBuffer) {
  29003. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29004. this._indexBuffer = null;
  29005. }
  29006. if (this.particleTexture) {
  29007. this.particleTexture.dispose();
  29008. this.particleTexture = null;
  29009. }
  29010. // Remove from scene
  29011. var index = this._scene.particleSystems.indexOf(this);
  29012. this._scene.particleSystems.splice(index, 1);
  29013. // Callback
  29014. this.onDisposeObservable.notifyObservers(this);
  29015. this.onDisposeObservable.clear();
  29016. };
  29017. // Clone
  29018. ParticleSystem.prototype.clone = function (name, newEmitter) {
  29019. var result = new ParticleSystem(name, this._capacity, this._scene);
  29020. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  29021. if (newEmitter === undefined) {
  29022. newEmitter = this.emitter;
  29023. }
  29024. result.emitter = newEmitter;
  29025. if (this.particleTexture) {
  29026. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  29027. }
  29028. result.start();
  29029. return result;
  29030. };
  29031. ParticleSystem.prototype.serialize = function () {
  29032. var serializationObject = {};
  29033. serializationObject.name = this.name;
  29034. serializationObject.id = this.id;
  29035. // Emitter
  29036. if (this.emitter.position) {
  29037. serializationObject.emitterId = this.emitter.id;
  29038. }
  29039. else {
  29040. serializationObject.emitter = this.emitter.asArray();
  29041. }
  29042. serializationObject.capacity = this.getCapacity();
  29043. if (this.particleTexture) {
  29044. serializationObject.textureName = this.particleTexture.name;
  29045. }
  29046. // Animations
  29047. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29048. // Particle system
  29049. serializationObject.minAngularSpeed = this.minAngularSpeed;
  29050. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  29051. serializationObject.minSize = this.minSize;
  29052. serializationObject.maxSize = this.maxSize;
  29053. serializationObject.minEmitPower = this.minEmitPower;
  29054. serializationObject.maxEmitPower = this.maxEmitPower;
  29055. serializationObject.minLifeTime = this.minLifeTime;
  29056. serializationObject.maxLifeTime = this.maxLifeTime;
  29057. serializationObject.emitRate = this.emitRate;
  29058. serializationObject.minEmitBox = this.minEmitBox.asArray();
  29059. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  29060. serializationObject.gravity = this.gravity.asArray();
  29061. serializationObject.direction1 = this.direction1.asArray();
  29062. serializationObject.direction2 = this.direction2.asArray();
  29063. serializationObject.color1 = this.color1.asArray();
  29064. serializationObject.color2 = this.color2.asArray();
  29065. serializationObject.colorDead = this.colorDead.asArray();
  29066. serializationObject.updateSpeed = this.updateSpeed;
  29067. serializationObject.targetStopDuration = this.targetStopDuration;
  29068. serializationObject.textureMask = this.textureMask.asArray();
  29069. serializationObject.blendMode = this.blendMode;
  29070. return serializationObject;
  29071. };
  29072. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  29073. var name = parsedParticleSystem.name;
  29074. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  29075. if (parsedParticleSystem.id) {
  29076. particleSystem.id = parsedParticleSystem.id;
  29077. }
  29078. // Texture
  29079. if (parsedParticleSystem.textureName) {
  29080. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  29081. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  29082. }
  29083. // Emitter
  29084. if (parsedParticleSystem.emitterId) {
  29085. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  29086. }
  29087. else {
  29088. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  29089. }
  29090. // Animations
  29091. if (parsedParticleSystem.animations) {
  29092. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  29093. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  29094. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29095. }
  29096. }
  29097. if (parsedParticleSystem.autoAnimate) {
  29098. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  29099. }
  29100. // Particle system
  29101. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  29102. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  29103. particleSystem.minSize = parsedParticleSystem.minSize;
  29104. particleSystem.maxSize = parsedParticleSystem.maxSize;
  29105. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  29106. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  29107. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  29108. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  29109. particleSystem.emitRate = parsedParticleSystem.emitRate;
  29110. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  29111. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  29112. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  29113. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  29114. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  29115. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  29116. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  29117. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  29118. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  29119. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  29120. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  29121. particleSystem.blendMode = parsedParticleSystem.blendMode;
  29122. if (!parsedParticleSystem.preventAutoStart) {
  29123. particleSystem.start();
  29124. }
  29125. return particleSystem;
  29126. };
  29127. return ParticleSystem;
  29128. }());
  29129. // Statics
  29130. ParticleSystem.BLENDMODE_ONEONE = 0;
  29131. ParticleSystem.BLENDMODE_STANDARD = 1;
  29132. BABYLON.ParticleSystem = ParticleSystem;
  29133. })(BABYLON || (BABYLON = {}));
  29134. //# sourceMappingURL=babylon.particleSystem.js.map
  29135. var BABYLON;
  29136. (function (BABYLON) {
  29137. var AnimationRange = (function () {
  29138. function AnimationRange(name, from, to) {
  29139. this.name = name;
  29140. this.from = from;
  29141. this.to = to;
  29142. }
  29143. AnimationRange.prototype.clone = function () {
  29144. return new AnimationRange(this.name, this.from, this.to);
  29145. };
  29146. return AnimationRange;
  29147. }());
  29148. BABYLON.AnimationRange = AnimationRange;
  29149. /**
  29150. * Composed of a frame, and an action function
  29151. */
  29152. var AnimationEvent = (function () {
  29153. function AnimationEvent(frame, action, onlyOnce) {
  29154. this.frame = frame;
  29155. this.action = action;
  29156. this.onlyOnce = onlyOnce;
  29157. this.isDone = false;
  29158. }
  29159. return AnimationEvent;
  29160. }());
  29161. BABYLON.AnimationEvent = AnimationEvent;
  29162. var PathCursor = (function () {
  29163. function PathCursor(path) {
  29164. this.path = path;
  29165. this._onchange = new Array();
  29166. this.value = 0;
  29167. this.animations = new Array();
  29168. }
  29169. PathCursor.prototype.getPoint = function () {
  29170. var point = this.path.getPointAtLengthPosition(this.value);
  29171. return new BABYLON.Vector3(point.x, 0, point.y);
  29172. };
  29173. PathCursor.prototype.moveAhead = function (step) {
  29174. if (step === void 0) { step = 0.002; }
  29175. this.move(step);
  29176. return this;
  29177. };
  29178. PathCursor.prototype.moveBack = function (step) {
  29179. if (step === void 0) { step = 0.002; }
  29180. this.move(-step);
  29181. return this;
  29182. };
  29183. PathCursor.prototype.move = function (step) {
  29184. if (Math.abs(step) > 1) {
  29185. throw "step size should be less than 1.";
  29186. }
  29187. this.value += step;
  29188. this.ensureLimits();
  29189. this.raiseOnChange();
  29190. return this;
  29191. };
  29192. PathCursor.prototype.ensureLimits = function () {
  29193. while (this.value > 1) {
  29194. this.value -= 1;
  29195. }
  29196. while (this.value < 0) {
  29197. this.value += 1;
  29198. }
  29199. return this;
  29200. };
  29201. // used by animation engine
  29202. PathCursor.prototype.markAsDirty = function (propertyName) {
  29203. this.ensureLimits();
  29204. this.raiseOnChange();
  29205. return this;
  29206. };
  29207. PathCursor.prototype.raiseOnChange = function () {
  29208. var _this = this;
  29209. this._onchange.forEach(function (f) { return f(_this); });
  29210. return this;
  29211. };
  29212. PathCursor.prototype.onchange = function (f) {
  29213. this._onchange.push(f);
  29214. return this;
  29215. };
  29216. return PathCursor;
  29217. }());
  29218. BABYLON.PathCursor = PathCursor;
  29219. var Animation = (function () {
  29220. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  29221. this.name = name;
  29222. this.targetProperty = targetProperty;
  29223. this.framePerSecond = framePerSecond;
  29224. this.dataType = dataType;
  29225. this.loopMode = loopMode;
  29226. this.enableBlending = enableBlending;
  29227. this._offsetsCache = {};
  29228. this._highLimitsCache = {};
  29229. this._stopped = false;
  29230. this._blendingFactor = 0;
  29231. // The set of event that will be linked to this animation
  29232. this._events = new Array();
  29233. this.allowMatricesInterpolation = false;
  29234. this.blendingSpeed = 0.01;
  29235. this._ranges = {};
  29236. this.targetPropertyPath = targetProperty.split(".");
  29237. this.dataType = dataType;
  29238. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  29239. }
  29240. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  29241. var dataType = undefined;
  29242. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  29243. dataType = Animation.ANIMATIONTYPE_FLOAT;
  29244. }
  29245. else if (from instanceof BABYLON.Quaternion) {
  29246. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  29247. }
  29248. else if (from instanceof BABYLON.Vector3) {
  29249. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  29250. }
  29251. else if (from instanceof BABYLON.Vector2) {
  29252. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  29253. }
  29254. else if (from instanceof BABYLON.Color3) {
  29255. dataType = Animation.ANIMATIONTYPE_COLOR3;
  29256. }
  29257. else if (from instanceof BABYLON.Size) {
  29258. dataType = Animation.ANIMATIONTYPE_SIZE;
  29259. }
  29260. if (dataType == undefined) {
  29261. return null;
  29262. }
  29263. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  29264. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  29265. animation.setKeys(keys);
  29266. if (easingFunction !== undefined) {
  29267. animation.setEasingFunction(easingFunction);
  29268. }
  29269. return animation;
  29270. };
  29271. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29272. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29273. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29274. };
  29275. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29276. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29277. node.animations.push(animation);
  29278. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29279. };
  29280. // Methods
  29281. /**
  29282. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29283. */
  29284. Animation.prototype.toString = function (fullDetails) {
  29285. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  29286. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  29287. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  29288. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29289. if (fullDetails) {
  29290. ret += ", Ranges: {";
  29291. var first = true;
  29292. for (var name in this._ranges) {
  29293. if (first) {
  29294. ret += ", ";
  29295. first = false;
  29296. }
  29297. ret += name;
  29298. }
  29299. ret += "}";
  29300. }
  29301. return ret;
  29302. };
  29303. /**
  29304. * Add an event to this animation.
  29305. */
  29306. Animation.prototype.addEvent = function (event) {
  29307. this._events.push(event);
  29308. };
  29309. /**
  29310. * Remove all events found at the given frame
  29311. * @param frame
  29312. */
  29313. Animation.prototype.removeEvents = function (frame) {
  29314. for (var index = 0; index < this._events.length; index++) {
  29315. if (this._events[index].frame === frame) {
  29316. this._events.splice(index, 1);
  29317. index--;
  29318. }
  29319. }
  29320. };
  29321. Animation.prototype.createRange = function (name, from, to) {
  29322. // check name not already in use; could happen for bones after serialized
  29323. if (!this._ranges[name]) {
  29324. this._ranges[name] = new AnimationRange(name, from, to);
  29325. }
  29326. };
  29327. Animation.prototype.deleteRange = function (name, deleteFrames) {
  29328. if (deleteFrames === void 0) { deleteFrames = true; }
  29329. if (this._ranges[name]) {
  29330. if (deleteFrames) {
  29331. var from = this._ranges[name].from;
  29332. var to = this._ranges[name].to;
  29333. // this loop MUST go high to low for multiple splices to work
  29334. for (var key = this._keys.length - 1; key >= 0; key--) {
  29335. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  29336. this._keys.splice(key, 1);
  29337. }
  29338. }
  29339. }
  29340. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  29341. }
  29342. };
  29343. Animation.prototype.getRange = function (name) {
  29344. return this._ranges[name];
  29345. };
  29346. Animation.prototype.reset = function () {
  29347. this._offsetsCache = {};
  29348. this._highLimitsCache = {};
  29349. this.currentFrame = 0;
  29350. this._blendingFactor = 0;
  29351. this._originalBlendValue = null;
  29352. };
  29353. Animation.prototype.isStopped = function () {
  29354. return this._stopped;
  29355. };
  29356. Animation.prototype.getKeys = function () {
  29357. return this._keys;
  29358. };
  29359. Animation.prototype.getHighestFrame = function () {
  29360. var ret = 0;
  29361. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  29362. if (ret < this._keys[key].frame) {
  29363. ret = this._keys[key].frame;
  29364. }
  29365. }
  29366. return ret;
  29367. };
  29368. Animation.prototype.getEasingFunction = function () {
  29369. return this._easingFunction;
  29370. };
  29371. Animation.prototype.setEasingFunction = function (easingFunction) {
  29372. this._easingFunction = easingFunction;
  29373. };
  29374. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  29375. return startValue + (endValue - startValue) * gradient;
  29376. };
  29377. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  29378. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  29379. };
  29380. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  29381. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  29382. };
  29383. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  29384. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  29385. };
  29386. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  29387. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  29388. };
  29389. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  29390. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  29391. };
  29392. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  29393. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  29394. };
  29395. Animation.prototype.clone = function () {
  29396. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  29397. if (this._keys) {
  29398. clone.setKeys(this._keys);
  29399. }
  29400. if (this._ranges) {
  29401. clone._ranges = {};
  29402. for (var name in this._ranges) {
  29403. clone._ranges[name] = this._ranges[name].clone();
  29404. }
  29405. }
  29406. return clone;
  29407. };
  29408. Animation.prototype.setKeys = function (values) {
  29409. this._keys = values.slice(0);
  29410. this._offsetsCache = {};
  29411. this._highLimitsCache = {};
  29412. };
  29413. Animation.prototype._getKeyValue = function (value) {
  29414. if (typeof value === "function") {
  29415. return value();
  29416. }
  29417. return value;
  29418. };
  29419. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  29420. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  29421. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  29422. }
  29423. this.currentFrame = currentFrame;
  29424. // Try to get a hash to find the right key
  29425. var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  29426. if (this._keys[startKey].frame >= currentFrame) {
  29427. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  29428. startKey--;
  29429. }
  29430. }
  29431. for (var key = startKey; key < this._keys.length; key++) {
  29432. if (this._keys[key + 1].frame >= currentFrame) {
  29433. var startValue = this._getKeyValue(this._keys[key].value);
  29434. var endValue = this._getKeyValue(this._keys[key + 1].value);
  29435. // gradient : percent of currentFrame between the frame inf and the frame sup
  29436. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  29437. // check for easingFunction and correction of gradient
  29438. if (this._easingFunction != null) {
  29439. gradient = this._easingFunction.ease(gradient);
  29440. }
  29441. switch (this.dataType) {
  29442. // Float
  29443. case Animation.ANIMATIONTYPE_FLOAT:
  29444. switch (loopMode) {
  29445. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29446. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29447. return this.floatInterpolateFunction(startValue, endValue, gradient);
  29448. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29449. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  29450. }
  29451. break;
  29452. // Quaternion
  29453. case Animation.ANIMATIONTYPE_QUATERNION:
  29454. var quaternion = null;
  29455. switch (loopMode) {
  29456. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29457. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29458. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  29459. break;
  29460. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29461. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29462. break;
  29463. }
  29464. return quaternion;
  29465. // Vector3
  29466. case Animation.ANIMATIONTYPE_VECTOR3:
  29467. switch (loopMode) {
  29468. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29469. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29470. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  29471. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29472. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29473. }
  29474. // Vector2
  29475. case Animation.ANIMATIONTYPE_VECTOR2:
  29476. switch (loopMode) {
  29477. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29478. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29479. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  29480. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29481. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29482. }
  29483. // Size
  29484. case Animation.ANIMATIONTYPE_SIZE:
  29485. switch (loopMode) {
  29486. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29487. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29488. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  29489. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29490. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29491. }
  29492. // Color3
  29493. case Animation.ANIMATIONTYPE_COLOR3:
  29494. switch (loopMode) {
  29495. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29496. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29497. return this.color3InterpolateFunction(startValue, endValue, gradient);
  29498. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29499. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29500. }
  29501. // Matrix
  29502. case Animation.ANIMATIONTYPE_MATRIX:
  29503. switch (loopMode) {
  29504. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29505. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29506. if (this.allowMatricesInterpolation) {
  29507. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  29508. }
  29509. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29510. return startValue;
  29511. }
  29512. default:
  29513. break;
  29514. }
  29515. break;
  29516. }
  29517. }
  29518. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  29519. };
  29520. Animation.prototype.setValue = function (currentValue, blend) {
  29521. if (blend === void 0) { blend = false; }
  29522. // Set value
  29523. var path;
  29524. var destination;
  29525. if (this.targetPropertyPath.length > 1) {
  29526. var property = this._target[this.targetPropertyPath[0]];
  29527. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  29528. property = property[this.targetPropertyPath[index]];
  29529. }
  29530. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  29531. destination = property;
  29532. }
  29533. else {
  29534. path = this.targetPropertyPath[0];
  29535. destination = this._target;
  29536. }
  29537. // Blending
  29538. if (this.enableBlending && this._blendingFactor <= 1.0) {
  29539. if (!this._originalBlendValue) {
  29540. if (destination[path].clone) {
  29541. this._originalBlendValue = destination[path].clone();
  29542. }
  29543. else {
  29544. this._originalBlendValue = destination[path];
  29545. }
  29546. }
  29547. if (this._originalBlendValue.prototype) {
  29548. if (this._originalBlendValue.prototype.Lerp) {
  29549. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  29550. }
  29551. else {
  29552. destination[path] = currentValue;
  29553. }
  29554. }
  29555. else if (this._originalBlendValue.m) {
  29556. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  29557. }
  29558. else {
  29559. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  29560. }
  29561. this._blendingFactor += this.blendingSpeed;
  29562. }
  29563. else {
  29564. destination[path] = currentValue;
  29565. }
  29566. if (this._target.markAsDirty) {
  29567. this._target.markAsDirty(this.targetProperty);
  29568. }
  29569. };
  29570. Animation.prototype.goToFrame = function (frame) {
  29571. if (frame < this._keys[0].frame) {
  29572. frame = this._keys[0].frame;
  29573. }
  29574. else if (frame > this._keys[this._keys.length - 1].frame) {
  29575. frame = this._keys[this._keys.length - 1].frame;
  29576. }
  29577. var currentValue = this._interpolate(frame, 0, this.loopMode);
  29578. this.setValue(currentValue);
  29579. };
  29580. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  29581. if (blend === void 0) { blend = false; }
  29582. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  29583. this._stopped = true;
  29584. return false;
  29585. }
  29586. var returnValue = true;
  29587. // Adding a start key at frame 0 if missing
  29588. if (this._keys[0].frame !== 0) {
  29589. var newKey = { frame: 0, value: this._keys[0].value };
  29590. this._keys.splice(0, 0, newKey);
  29591. }
  29592. // Check limits
  29593. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  29594. from = this._keys[0].frame;
  29595. }
  29596. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  29597. to = this._keys[this._keys.length - 1].frame;
  29598. }
  29599. //to and from cannot be the same key
  29600. if (from === to) {
  29601. from++;
  29602. }
  29603. // Compute ratio
  29604. var range = to - from;
  29605. var offsetValue;
  29606. // ratio represents the frame delta between from and to
  29607. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  29608. var highLimitValue = 0;
  29609. if (ratio > range && !loop) {
  29610. returnValue = false;
  29611. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  29612. }
  29613. else {
  29614. // Get max value if required
  29615. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  29616. var keyOffset = to.toString() + from.toString();
  29617. if (!this._offsetsCache[keyOffset]) {
  29618. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  29619. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  29620. switch (this.dataType) {
  29621. // Float
  29622. case Animation.ANIMATIONTYPE_FLOAT:
  29623. this._offsetsCache[keyOffset] = toValue - fromValue;
  29624. break;
  29625. // Quaternion
  29626. case Animation.ANIMATIONTYPE_QUATERNION:
  29627. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29628. break;
  29629. // Vector3
  29630. case Animation.ANIMATIONTYPE_VECTOR3:
  29631. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29632. // Vector2
  29633. case Animation.ANIMATIONTYPE_VECTOR2:
  29634. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29635. // Size
  29636. case Animation.ANIMATIONTYPE_SIZE:
  29637. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29638. // Color3
  29639. case Animation.ANIMATIONTYPE_COLOR3:
  29640. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29641. default:
  29642. break;
  29643. }
  29644. this._highLimitsCache[keyOffset] = toValue;
  29645. }
  29646. highLimitValue = this._highLimitsCache[keyOffset];
  29647. offsetValue = this._offsetsCache[keyOffset];
  29648. }
  29649. }
  29650. if (offsetValue === undefined) {
  29651. switch (this.dataType) {
  29652. // Float
  29653. case Animation.ANIMATIONTYPE_FLOAT:
  29654. offsetValue = 0;
  29655. break;
  29656. // Quaternion
  29657. case Animation.ANIMATIONTYPE_QUATERNION:
  29658. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  29659. break;
  29660. // Vector3
  29661. case Animation.ANIMATIONTYPE_VECTOR3:
  29662. offsetValue = BABYLON.Vector3.Zero();
  29663. break;
  29664. // Vector2
  29665. case Animation.ANIMATIONTYPE_VECTOR2:
  29666. offsetValue = BABYLON.Vector2.Zero();
  29667. break;
  29668. // Size
  29669. case Animation.ANIMATIONTYPE_SIZE:
  29670. offsetValue = BABYLON.Size.Zero();
  29671. break;
  29672. // Color3
  29673. case Animation.ANIMATIONTYPE_COLOR3:
  29674. offsetValue = BABYLON.Color3.Black();
  29675. }
  29676. }
  29677. // Compute value
  29678. var repeatCount = (ratio / range) >> 0;
  29679. var currentFrame = returnValue ? from + ratio % range : to;
  29680. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  29681. // Set value
  29682. this.setValue(currentValue);
  29683. // Check events
  29684. for (var index = 0; index < this._events.length; index++) {
  29685. if (currentFrame >= this._events[index].frame) {
  29686. var event = this._events[index];
  29687. if (!event.isDone) {
  29688. // If event should be done only once, remove it.
  29689. if (event.onlyOnce) {
  29690. this._events.splice(index, 1);
  29691. index--;
  29692. }
  29693. event.isDone = true;
  29694. event.action();
  29695. } // Don't do anything if the event has already be done.
  29696. }
  29697. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  29698. // reset event, the animation is looping
  29699. this._events[index].isDone = false;
  29700. }
  29701. }
  29702. if (!returnValue) {
  29703. this._stopped = true;
  29704. }
  29705. return returnValue;
  29706. };
  29707. Animation.prototype.serialize = function () {
  29708. var serializationObject = {};
  29709. serializationObject.name = this.name;
  29710. serializationObject.property = this.targetProperty;
  29711. serializationObject.framePerSecond = this.framePerSecond;
  29712. serializationObject.dataType = this.dataType;
  29713. serializationObject.loopBehavior = this.loopMode;
  29714. var dataType = this.dataType;
  29715. serializationObject.keys = [];
  29716. var keys = this.getKeys();
  29717. for (var index = 0; index < keys.length; index++) {
  29718. var animationKey = keys[index];
  29719. var key = {};
  29720. key.frame = animationKey.frame;
  29721. switch (dataType) {
  29722. case Animation.ANIMATIONTYPE_FLOAT:
  29723. key.values = [animationKey.value];
  29724. break;
  29725. case Animation.ANIMATIONTYPE_QUATERNION:
  29726. case Animation.ANIMATIONTYPE_MATRIX:
  29727. case Animation.ANIMATIONTYPE_VECTOR3:
  29728. case Animation.ANIMATIONTYPE_COLOR3:
  29729. key.values = animationKey.value.asArray();
  29730. break;
  29731. }
  29732. serializationObject.keys.push(key);
  29733. }
  29734. serializationObject.ranges = [];
  29735. for (var name in this._ranges) {
  29736. var range = {};
  29737. range.name = name;
  29738. range.from = this._ranges[name].from;
  29739. range.to = this._ranges[name].to;
  29740. serializationObject.ranges.push(range);
  29741. }
  29742. return serializationObject;
  29743. };
  29744. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  29745. get: function () {
  29746. return Animation._ANIMATIONTYPE_FLOAT;
  29747. },
  29748. enumerable: true,
  29749. configurable: true
  29750. });
  29751. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  29752. get: function () {
  29753. return Animation._ANIMATIONTYPE_VECTOR3;
  29754. },
  29755. enumerable: true,
  29756. configurable: true
  29757. });
  29758. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  29759. get: function () {
  29760. return Animation._ANIMATIONTYPE_VECTOR2;
  29761. },
  29762. enumerable: true,
  29763. configurable: true
  29764. });
  29765. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  29766. get: function () {
  29767. return Animation._ANIMATIONTYPE_SIZE;
  29768. },
  29769. enumerable: true,
  29770. configurable: true
  29771. });
  29772. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  29773. get: function () {
  29774. return Animation._ANIMATIONTYPE_QUATERNION;
  29775. },
  29776. enumerable: true,
  29777. configurable: true
  29778. });
  29779. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  29780. get: function () {
  29781. return Animation._ANIMATIONTYPE_MATRIX;
  29782. },
  29783. enumerable: true,
  29784. configurable: true
  29785. });
  29786. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  29787. get: function () {
  29788. return Animation._ANIMATIONTYPE_COLOR3;
  29789. },
  29790. enumerable: true,
  29791. configurable: true
  29792. });
  29793. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  29794. get: function () {
  29795. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  29796. },
  29797. enumerable: true,
  29798. configurable: true
  29799. });
  29800. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  29801. get: function () {
  29802. return Animation._ANIMATIONLOOPMODE_CYCLE;
  29803. },
  29804. enumerable: true,
  29805. configurable: true
  29806. });
  29807. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  29808. get: function () {
  29809. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  29810. },
  29811. enumerable: true,
  29812. configurable: true
  29813. });
  29814. Animation.Parse = function (parsedAnimation) {
  29815. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  29816. var dataType = parsedAnimation.dataType;
  29817. var keys = [];
  29818. var data;
  29819. var index;
  29820. for (index = 0; index < parsedAnimation.keys.length; index++) {
  29821. var key = parsedAnimation.keys[index];
  29822. switch (dataType) {
  29823. case Animation.ANIMATIONTYPE_FLOAT:
  29824. data = key.values[0];
  29825. break;
  29826. case Animation.ANIMATIONTYPE_QUATERNION:
  29827. data = BABYLON.Quaternion.FromArray(key.values);
  29828. break;
  29829. case Animation.ANIMATIONTYPE_MATRIX:
  29830. data = BABYLON.Matrix.FromArray(key.values);
  29831. break;
  29832. case Animation.ANIMATIONTYPE_COLOR3:
  29833. data = BABYLON.Color3.FromArray(key.values);
  29834. break;
  29835. case Animation.ANIMATIONTYPE_VECTOR3:
  29836. default:
  29837. data = BABYLON.Vector3.FromArray(key.values);
  29838. break;
  29839. }
  29840. keys.push({
  29841. frame: key.frame,
  29842. value: data
  29843. });
  29844. }
  29845. animation.setKeys(keys);
  29846. if (parsedAnimation.ranges) {
  29847. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  29848. data = parsedAnimation.ranges[index];
  29849. animation.createRange(data.name, data.from, data.to);
  29850. }
  29851. }
  29852. return animation;
  29853. };
  29854. Animation.AppendSerializedAnimations = function (source, destination) {
  29855. if (source.animations) {
  29856. destination.animations = [];
  29857. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29858. var animation = source.animations[animationIndex];
  29859. destination.animations.push(animation.serialize());
  29860. }
  29861. }
  29862. };
  29863. return Animation;
  29864. }());
  29865. // Statics
  29866. Animation._ANIMATIONTYPE_FLOAT = 0;
  29867. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  29868. Animation._ANIMATIONTYPE_QUATERNION = 2;
  29869. Animation._ANIMATIONTYPE_MATRIX = 3;
  29870. Animation._ANIMATIONTYPE_COLOR3 = 4;
  29871. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  29872. Animation._ANIMATIONTYPE_SIZE = 6;
  29873. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  29874. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  29875. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  29876. BABYLON.Animation = Animation;
  29877. })(BABYLON || (BABYLON = {}));
  29878. //# sourceMappingURL=babylon.animation.js.map
  29879. var BABYLON;
  29880. (function (BABYLON) {
  29881. var Animatable = (function () {
  29882. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  29883. if (fromFrame === void 0) { fromFrame = 0; }
  29884. if (toFrame === void 0) { toFrame = 100; }
  29885. if (loopAnimation === void 0) { loopAnimation = false; }
  29886. if (speedRatio === void 0) { speedRatio = 1.0; }
  29887. this.target = target;
  29888. this.fromFrame = fromFrame;
  29889. this.toFrame = toFrame;
  29890. this.loopAnimation = loopAnimation;
  29891. this.speedRatio = speedRatio;
  29892. this.onAnimationEnd = onAnimationEnd;
  29893. this._animations = new Array();
  29894. this._paused = false;
  29895. this.animationStarted = false;
  29896. if (animations) {
  29897. this.appendAnimations(target, animations);
  29898. }
  29899. this._scene = scene;
  29900. scene._activeAnimatables.push(this);
  29901. }
  29902. // Methods
  29903. Animatable.prototype.getAnimations = function () {
  29904. return this._animations;
  29905. };
  29906. Animatable.prototype.appendAnimations = function (target, animations) {
  29907. for (var index = 0; index < animations.length; index++) {
  29908. var animation = animations[index];
  29909. animation._target = target;
  29910. this._animations.push(animation);
  29911. }
  29912. };
  29913. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  29914. var animations = this._animations;
  29915. for (var index = 0; index < animations.length; index++) {
  29916. if (animations[index].targetProperty === property) {
  29917. return animations[index];
  29918. }
  29919. }
  29920. return null;
  29921. };
  29922. Animatable.prototype.reset = function () {
  29923. var animations = this._animations;
  29924. for (var index = 0; index < animations.length; index++) {
  29925. animations[index].reset();
  29926. }
  29927. this._localDelayOffset = null;
  29928. this._pausedDelay = null;
  29929. };
  29930. Animatable.prototype.enableBlending = function (blendingSpeed) {
  29931. var animations = this._animations;
  29932. for (var index = 0; index < animations.length; index++) {
  29933. animations[index].enableBlending = true;
  29934. animations[index].blendingSpeed = blendingSpeed;
  29935. }
  29936. };
  29937. Animatable.prototype.disableBlending = function () {
  29938. var animations = this._animations;
  29939. for (var index = 0; index < animations.length; index++) {
  29940. animations[index].enableBlending = false;
  29941. }
  29942. };
  29943. Animatable.prototype.goToFrame = function (frame) {
  29944. var animations = this._animations;
  29945. if (animations[0]) {
  29946. var fps = animations[0].framePerSecond;
  29947. var currentFrame = animations[0].currentFrame;
  29948. var adjustTime = frame - currentFrame;
  29949. var delay = adjustTime * 1000 / fps;
  29950. this._localDelayOffset -= delay;
  29951. }
  29952. for (var index = 0; index < animations.length; index++) {
  29953. animations[index].goToFrame(frame);
  29954. }
  29955. };
  29956. Animatable.prototype.pause = function () {
  29957. if (this._paused) {
  29958. return;
  29959. }
  29960. this._paused = true;
  29961. };
  29962. Animatable.prototype.restart = function () {
  29963. this._paused = false;
  29964. };
  29965. Animatable.prototype.stop = function (animationName) {
  29966. var idx = this._scene._activeAnimatables.indexOf(this);
  29967. if (idx > -1) {
  29968. var animations = this._animations;
  29969. var numberOfAnimationsStopped = 0;
  29970. for (var index = animations.length - 1; index >= 0; index--) {
  29971. if (typeof animationName === "string" && animations[index].name != animationName) {
  29972. continue;
  29973. }
  29974. animations[index].reset();
  29975. animations.splice(index, 1);
  29976. numberOfAnimationsStopped++;
  29977. }
  29978. if (animations.length == numberOfAnimationsStopped) {
  29979. this._scene._activeAnimatables.splice(idx, 1);
  29980. if (this.onAnimationEnd) {
  29981. this.onAnimationEnd();
  29982. }
  29983. }
  29984. }
  29985. };
  29986. Animatable.prototype._animate = function (delay) {
  29987. if (this._paused) {
  29988. this.animationStarted = false;
  29989. if (!this._pausedDelay) {
  29990. this._pausedDelay = delay;
  29991. }
  29992. return true;
  29993. }
  29994. if (!this._localDelayOffset) {
  29995. this._localDelayOffset = delay;
  29996. }
  29997. else if (this._pausedDelay) {
  29998. this._localDelayOffset += delay - this._pausedDelay;
  29999. this._pausedDelay = null;
  30000. }
  30001. // Animating
  30002. var running = false;
  30003. var animations = this._animations;
  30004. var index;
  30005. for (index = 0; index < animations.length; index++) {
  30006. var animation = animations[index];
  30007. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  30008. running = running || isRunning;
  30009. }
  30010. this.animationStarted = running;
  30011. if (!running) {
  30012. // Remove from active animatables
  30013. index = this._scene._activeAnimatables.indexOf(this);
  30014. this._scene._activeAnimatables.splice(index, 1);
  30015. }
  30016. if (!running && this.onAnimationEnd) {
  30017. this.onAnimationEnd();
  30018. this.onAnimationEnd = null;
  30019. }
  30020. return running;
  30021. };
  30022. return Animatable;
  30023. }());
  30024. BABYLON.Animatable = Animatable;
  30025. })(BABYLON || (BABYLON = {}));
  30026. //# sourceMappingURL=babylon.animatable.js.map
  30027. var BABYLON;
  30028. (function (BABYLON) {
  30029. var EasingFunction = (function () {
  30030. function EasingFunction() {
  30031. // Properties
  30032. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  30033. }
  30034. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  30035. get: function () {
  30036. return EasingFunction._EASINGMODE_EASEIN;
  30037. },
  30038. enumerable: true,
  30039. configurable: true
  30040. });
  30041. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  30042. get: function () {
  30043. return EasingFunction._EASINGMODE_EASEOUT;
  30044. },
  30045. enumerable: true,
  30046. configurable: true
  30047. });
  30048. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  30049. get: function () {
  30050. return EasingFunction._EASINGMODE_EASEINOUT;
  30051. },
  30052. enumerable: true,
  30053. configurable: true
  30054. });
  30055. EasingFunction.prototype.setEasingMode = function (easingMode) {
  30056. var n = Math.min(Math.max(easingMode, 0), 2);
  30057. this._easingMode = n;
  30058. };
  30059. EasingFunction.prototype.getEasingMode = function () {
  30060. return this._easingMode;
  30061. };
  30062. EasingFunction.prototype.easeInCore = function (gradient) {
  30063. throw new Error('You must implement this method');
  30064. };
  30065. EasingFunction.prototype.ease = function (gradient) {
  30066. switch (this._easingMode) {
  30067. case EasingFunction.EASINGMODE_EASEIN:
  30068. return this.easeInCore(gradient);
  30069. case EasingFunction.EASINGMODE_EASEOUT:
  30070. return (1 - this.easeInCore(1 - gradient));
  30071. }
  30072. if (gradient >= 0.5) {
  30073. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  30074. }
  30075. return (this.easeInCore(gradient * 2) * 0.5);
  30076. };
  30077. return EasingFunction;
  30078. }());
  30079. //Statics
  30080. EasingFunction._EASINGMODE_EASEIN = 0;
  30081. EasingFunction._EASINGMODE_EASEOUT = 1;
  30082. EasingFunction._EASINGMODE_EASEINOUT = 2;
  30083. BABYLON.EasingFunction = EasingFunction;
  30084. var CircleEase = (function (_super) {
  30085. __extends(CircleEase, _super);
  30086. function CircleEase() {
  30087. return _super.apply(this, arguments) || this;
  30088. }
  30089. CircleEase.prototype.easeInCore = function (gradient) {
  30090. gradient = Math.max(0, Math.min(1, gradient));
  30091. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  30092. };
  30093. return CircleEase;
  30094. }(EasingFunction));
  30095. BABYLON.CircleEase = CircleEase;
  30096. var BackEase = (function (_super) {
  30097. __extends(BackEase, _super);
  30098. function BackEase(amplitude) {
  30099. if (amplitude === void 0) { amplitude = 1; }
  30100. var _this = _super.call(this) || this;
  30101. _this.amplitude = amplitude;
  30102. return _this;
  30103. }
  30104. BackEase.prototype.easeInCore = function (gradient) {
  30105. var num = Math.max(0, this.amplitude);
  30106. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  30107. };
  30108. return BackEase;
  30109. }(EasingFunction));
  30110. BABYLON.BackEase = BackEase;
  30111. var BounceEase = (function (_super) {
  30112. __extends(BounceEase, _super);
  30113. function BounceEase(bounces, bounciness) {
  30114. if (bounces === void 0) { bounces = 3; }
  30115. if (bounciness === void 0) { bounciness = 2; }
  30116. var _this = _super.call(this) || this;
  30117. _this.bounces = bounces;
  30118. _this.bounciness = bounciness;
  30119. return _this;
  30120. }
  30121. BounceEase.prototype.easeInCore = function (gradient) {
  30122. var y = Math.max(0.0, this.bounces);
  30123. var bounciness = this.bounciness;
  30124. if (bounciness <= 1.0) {
  30125. bounciness = 1.001;
  30126. }
  30127. var num9 = Math.pow(bounciness, y);
  30128. var num5 = 1.0 - bounciness;
  30129. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  30130. var num15 = gradient * num4;
  30131. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  30132. var num3 = Math.floor(num65);
  30133. var num13 = num3 + 1.0;
  30134. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  30135. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  30136. var num7 = (num8 + num12) * 0.5;
  30137. var num6 = gradient - num7;
  30138. var num2 = num7 - num8;
  30139. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  30140. };
  30141. return BounceEase;
  30142. }(EasingFunction));
  30143. BABYLON.BounceEase = BounceEase;
  30144. var CubicEase = (function (_super) {
  30145. __extends(CubicEase, _super);
  30146. function CubicEase() {
  30147. return _super.apply(this, arguments) || this;
  30148. }
  30149. CubicEase.prototype.easeInCore = function (gradient) {
  30150. return (gradient * gradient * gradient);
  30151. };
  30152. return CubicEase;
  30153. }(EasingFunction));
  30154. BABYLON.CubicEase = CubicEase;
  30155. var ElasticEase = (function (_super) {
  30156. __extends(ElasticEase, _super);
  30157. function ElasticEase(oscillations, springiness) {
  30158. if (oscillations === void 0) { oscillations = 3; }
  30159. if (springiness === void 0) { springiness = 3; }
  30160. var _this = _super.call(this) || this;
  30161. _this.oscillations = oscillations;
  30162. _this.springiness = springiness;
  30163. return _this;
  30164. }
  30165. ElasticEase.prototype.easeInCore = function (gradient) {
  30166. var num2;
  30167. var num3 = Math.max(0.0, this.oscillations);
  30168. var num = Math.max(0.0, this.springiness);
  30169. if (num == 0) {
  30170. num2 = gradient;
  30171. }
  30172. else {
  30173. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  30174. }
  30175. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  30176. };
  30177. return ElasticEase;
  30178. }(EasingFunction));
  30179. BABYLON.ElasticEase = ElasticEase;
  30180. var ExponentialEase = (function (_super) {
  30181. __extends(ExponentialEase, _super);
  30182. function ExponentialEase(exponent) {
  30183. if (exponent === void 0) { exponent = 2; }
  30184. var _this = _super.call(this) || this;
  30185. _this.exponent = exponent;
  30186. return _this;
  30187. }
  30188. ExponentialEase.prototype.easeInCore = function (gradient) {
  30189. if (this.exponent <= 0) {
  30190. return gradient;
  30191. }
  30192. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  30193. };
  30194. return ExponentialEase;
  30195. }(EasingFunction));
  30196. BABYLON.ExponentialEase = ExponentialEase;
  30197. var PowerEase = (function (_super) {
  30198. __extends(PowerEase, _super);
  30199. function PowerEase(power) {
  30200. if (power === void 0) { power = 2; }
  30201. var _this = _super.call(this) || this;
  30202. _this.power = power;
  30203. return _this;
  30204. }
  30205. PowerEase.prototype.easeInCore = function (gradient) {
  30206. var y = Math.max(0.0, this.power);
  30207. return Math.pow(gradient, y);
  30208. };
  30209. return PowerEase;
  30210. }(EasingFunction));
  30211. BABYLON.PowerEase = PowerEase;
  30212. var QuadraticEase = (function (_super) {
  30213. __extends(QuadraticEase, _super);
  30214. function QuadraticEase() {
  30215. return _super.apply(this, arguments) || this;
  30216. }
  30217. QuadraticEase.prototype.easeInCore = function (gradient) {
  30218. return (gradient * gradient);
  30219. };
  30220. return QuadraticEase;
  30221. }(EasingFunction));
  30222. BABYLON.QuadraticEase = QuadraticEase;
  30223. var QuarticEase = (function (_super) {
  30224. __extends(QuarticEase, _super);
  30225. function QuarticEase() {
  30226. return _super.apply(this, arguments) || this;
  30227. }
  30228. QuarticEase.prototype.easeInCore = function (gradient) {
  30229. return (gradient * gradient * gradient * gradient);
  30230. };
  30231. return QuarticEase;
  30232. }(EasingFunction));
  30233. BABYLON.QuarticEase = QuarticEase;
  30234. var QuinticEase = (function (_super) {
  30235. __extends(QuinticEase, _super);
  30236. function QuinticEase() {
  30237. return _super.apply(this, arguments) || this;
  30238. }
  30239. QuinticEase.prototype.easeInCore = function (gradient) {
  30240. return (gradient * gradient * gradient * gradient * gradient);
  30241. };
  30242. return QuinticEase;
  30243. }(EasingFunction));
  30244. BABYLON.QuinticEase = QuinticEase;
  30245. var SineEase = (function (_super) {
  30246. __extends(SineEase, _super);
  30247. function SineEase() {
  30248. return _super.apply(this, arguments) || this;
  30249. }
  30250. SineEase.prototype.easeInCore = function (gradient) {
  30251. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  30252. };
  30253. return SineEase;
  30254. }(EasingFunction));
  30255. BABYLON.SineEase = SineEase;
  30256. var BezierCurveEase = (function (_super) {
  30257. __extends(BezierCurveEase, _super);
  30258. function BezierCurveEase(x1, y1, x2, y2) {
  30259. if (x1 === void 0) { x1 = 0; }
  30260. if (y1 === void 0) { y1 = 0; }
  30261. if (x2 === void 0) { x2 = 1; }
  30262. if (y2 === void 0) { y2 = 1; }
  30263. var _this = _super.call(this) || this;
  30264. _this.x1 = x1;
  30265. _this.y1 = y1;
  30266. _this.x2 = x2;
  30267. _this.y2 = y2;
  30268. return _this;
  30269. }
  30270. BezierCurveEase.prototype.easeInCore = function (gradient) {
  30271. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  30272. };
  30273. return BezierCurveEase;
  30274. }(EasingFunction));
  30275. BABYLON.BezierCurveEase = BezierCurveEase;
  30276. })(BABYLON || (BABYLON = {}));
  30277. //# sourceMappingURL=babylon.easing.js.map
  30278. var BABYLON;
  30279. (function (BABYLON) {
  30280. var Bone = (function (_super) {
  30281. __extends(Bone, _super);
  30282. function Bone(name, skeleton, parentBone, matrix, restPose) {
  30283. var _this = _super.call(this, name, skeleton.getScene()) || this;
  30284. _this.name = name;
  30285. _this.children = new Array();
  30286. _this.animations = new Array();
  30287. _this._worldTransform = new BABYLON.Matrix();
  30288. _this._absoluteTransform = new BABYLON.Matrix();
  30289. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  30290. _this._scaleMatrix = BABYLON.Matrix.Identity();
  30291. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  30292. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  30293. _this._scalingDeterminant = 1;
  30294. _this._syncScaleVector = function () {
  30295. var lm = this.getLocalMatrix();
  30296. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  30297. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  30298. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  30299. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  30300. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  30301. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  30302. this._scaleVector.x = xs * Math.sqrt(xsq);
  30303. this._scaleVector.y = ys * Math.sqrt(ysq);
  30304. this._scaleVector.z = zs * Math.sqrt(zsq);
  30305. if (this._parent) {
  30306. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  30307. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  30308. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  30309. }
  30310. 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);
  30311. };
  30312. _this._skeleton = skeleton;
  30313. _this._matrix = matrix;
  30314. _this._baseMatrix = matrix;
  30315. _this._restPose = restPose ? restPose : matrix.clone();
  30316. skeleton.bones.push(_this);
  30317. if (parentBone) {
  30318. _this._parent = parentBone;
  30319. parentBone.children.push(_this);
  30320. }
  30321. else {
  30322. _this._parent = null;
  30323. }
  30324. _this._updateDifferenceMatrix();
  30325. if (_this.getAbsoluteTransform().determinant() < 0) {
  30326. _this._scalingDeterminant *= -1;
  30327. }
  30328. return _this;
  30329. }
  30330. // Members
  30331. Bone.prototype.getParent = function () {
  30332. return this._parent;
  30333. };
  30334. Bone.prototype.getLocalMatrix = function () {
  30335. return this._matrix;
  30336. };
  30337. Bone.prototype.getBaseMatrix = function () {
  30338. return this._baseMatrix;
  30339. };
  30340. Bone.prototype.getRestPose = function () {
  30341. return this._restPose;
  30342. };
  30343. Bone.prototype.returnToRest = function () {
  30344. this.updateMatrix(this._restPose.clone());
  30345. };
  30346. Bone.prototype.getWorldMatrix = function () {
  30347. return this._worldTransform;
  30348. };
  30349. Bone.prototype.getInvertedAbsoluteTransform = function () {
  30350. return this._invertedAbsoluteTransform;
  30351. };
  30352. Bone.prototype.getAbsoluteTransform = function () {
  30353. return this._absoluteTransform;
  30354. };
  30355. // Methods
  30356. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  30357. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  30358. this._baseMatrix = matrix.clone();
  30359. this._matrix = matrix.clone();
  30360. this._skeleton._markAsDirty();
  30361. if (updateDifferenceMatrix) {
  30362. this._updateDifferenceMatrix();
  30363. }
  30364. };
  30365. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  30366. if (!rootMatrix) {
  30367. rootMatrix = this._baseMatrix;
  30368. }
  30369. if (this._parent) {
  30370. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  30371. }
  30372. else {
  30373. this._absoluteTransform.copyFrom(rootMatrix);
  30374. }
  30375. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  30376. for (var index = 0; index < this.children.length; index++) {
  30377. this.children[index]._updateDifferenceMatrix();
  30378. }
  30379. };
  30380. Bone.prototype.markAsDirty = function () {
  30381. this._currentRenderId++;
  30382. this._skeleton._markAsDirty();
  30383. };
  30384. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  30385. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  30386. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  30387. // all animation may be coming from a library skeleton, so may need to create animation
  30388. if (this.animations.length === 0) {
  30389. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  30390. this.animations[0].setKeys([]);
  30391. }
  30392. // get animation info / verify there is such a range from the source bone
  30393. var sourceRange = source.animations[0].getRange(rangeName);
  30394. if (!sourceRange) {
  30395. return false;
  30396. }
  30397. var from = sourceRange.from;
  30398. var to = sourceRange.to;
  30399. var sourceKeys = source.animations[0].getKeys();
  30400. // rescaling prep
  30401. var sourceBoneLength = source.length;
  30402. var sourceParent = source.getParent();
  30403. var parent = this.getParent();
  30404. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  30405. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  30406. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  30407. var destKeys = this.animations[0].getKeys();
  30408. // loop vars declaration
  30409. var orig;
  30410. var origTranslation;
  30411. var mat;
  30412. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  30413. orig = sourceKeys[key];
  30414. if (orig.frame >= from && orig.frame <= to) {
  30415. if (rescaleAsRequired) {
  30416. mat = orig.value.clone();
  30417. // scale based on parent ratio, when bone has parent
  30418. if (parentScalingReqd) {
  30419. origTranslation = mat.getTranslation();
  30420. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  30421. }
  30422. else if (dimensionsScalingReqd) {
  30423. origTranslation = mat.getTranslation();
  30424. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  30425. }
  30426. else {
  30427. mat = orig.value;
  30428. }
  30429. }
  30430. else {
  30431. mat = orig.value;
  30432. }
  30433. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  30434. }
  30435. }
  30436. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  30437. return true;
  30438. };
  30439. Bone.prototype.translate = function (vec, space, mesh) {
  30440. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30441. var lm = this.getLocalMatrix();
  30442. if (space == BABYLON.Space.LOCAL) {
  30443. lm.m[12] += vec.x;
  30444. lm.m[13] += vec.y;
  30445. lm.m[14] += vec.z;
  30446. }
  30447. else {
  30448. this._skeleton.computeAbsoluteTransforms();
  30449. var tmat = BABYLON.Tmp.Matrix[0];
  30450. var tvec = BABYLON.Tmp.Vector3[0];
  30451. if (mesh) {
  30452. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30453. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30454. }
  30455. else {
  30456. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30457. }
  30458. tmat.m[12] = 0;
  30459. tmat.m[13] = 0;
  30460. tmat.m[14] = 0;
  30461. tmat.invert();
  30462. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  30463. lm.m[12] += tvec.x;
  30464. lm.m[13] += tvec.y;
  30465. lm.m[14] += tvec.z;
  30466. }
  30467. this.markAsDirty();
  30468. };
  30469. Bone.prototype.setPosition = function (position, space, mesh) {
  30470. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30471. var lm = this.getLocalMatrix();
  30472. if (space == BABYLON.Space.LOCAL) {
  30473. lm.m[12] = position.x;
  30474. lm.m[13] = position.y;
  30475. lm.m[14] = position.z;
  30476. }
  30477. else {
  30478. this._skeleton.computeAbsoluteTransforms();
  30479. var tmat = BABYLON.Tmp.Matrix[0];
  30480. var vec = BABYLON.Tmp.Vector3[0];
  30481. if (mesh) {
  30482. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30483. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30484. }
  30485. else {
  30486. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30487. }
  30488. tmat.invert();
  30489. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  30490. lm.m[12] = vec.x;
  30491. lm.m[13] = vec.y;
  30492. lm.m[14] = vec.z;
  30493. }
  30494. this.markAsDirty();
  30495. };
  30496. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  30497. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  30498. };
  30499. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  30500. if (scaleChildren === void 0) { scaleChildren = false; }
  30501. if (this.animations[0] && !this.animations[0].isStopped()) {
  30502. if (!scaleChildren) {
  30503. this._negateScaleChildren.x = 1 / x;
  30504. this._negateScaleChildren.y = 1 / y;
  30505. this._negateScaleChildren.z = 1 / z;
  30506. }
  30507. this._syncScaleVector();
  30508. }
  30509. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  30510. };
  30511. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  30512. if (scaleChildren === void 0) { scaleChildren = false; }
  30513. var locMat = this.getLocalMatrix();
  30514. var origLocMat = BABYLON.Tmp.Matrix[0];
  30515. origLocMat.copyFrom(locMat);
  30516. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  30517. origLocMatInv.copyFrom(origLocMat);
  30518. origLocMatInv.invert();
  30519. var scaleMat = BABYLON.Tmp.Matrix[2];
  30520. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  30521. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  30522. this._scaleVector.x *= x;
  30523. this._scaleVector.y *= y;
  30524. this._scaleVector.z *= z;
  30525. locMat.multiplyToRef(origLocMatInv, locMat);
  30526. locMat.multiplyToRef(scaleMat, locMat);
  30527. locMat.multiplyToRef(origLocMat, locMat);
  30528. var parent = this.getParent();
  30529. if (parent) {
  30530. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  30531. }
  30532. else {
  30533. this.getAbsoluteTransform().copyFrom(locMat);
  30534. }
  30535. var len = this.children.length;
  30536. scaleMat.invert();
  30537. for (var i = 0; i < len; i++) {
  30538. var child = this.children[i];
  30539. var cm = child.getLocalMatrix();
  30540. cm.multiplyToRef(scaleMat, cm);
  30541. var lm = child.getLocalMatrix();
  30542. lm.m[12] *= x;
  30543. lm.m[13] *= y;
  30544. lm.m[14] *= z;
  30545. }
  30546. this.computeAbsoluteTransforms();
  30547. if (scaleChildren) {
  30548. for (var i = 0; i < len; i++) {
  30549. this.children[i].scale(x, y, z, scaleChildren);
  30550. }
  30551. }
  30552. this.markAsDirty();
  30553. };
  30554. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  30555. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30556. var rotMat = BABYLON.Tmp.Matrix[0];
  30557. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  30558. var rotMatInv = BABYLON.Tmp.Matrix[1];
  30559. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30560. rotMatInv.multiplyToRef(rotMat, rotMat);
  30561. this._rotateWithMatrix(rotMat, space, mesh);
  30562. };
  30563. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  30564. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30565. var rmat = BABYLON.Tmp.Matrix[0];
  30566. rmat.m[12] = 0;
  30567. rmat.m[13] = 0;
  30568. rmat.m[14] = 0;
  30569. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  30570. this._rotateWithMatrix(rmat, space, mesh);
  30571. };
  30572. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  30573. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30574. var rotMat = BABYLON.Tmp.Matrix[0];
  30575. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  30576. var rotMatInv = BABYLON.Tmp.Matrix[1];
  30577. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30578. rotMatInv.multiplyToRef(rotMat, rotMat);
  30579. this._rotateWithMatrix(rotMat, space, mesh);
  30580. };
  30581. Bone.prototype.setRotation = function (rotation, space, mesh) {
  30582. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30583. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  30584. };
  30585. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  30586. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30587. var rotMatInv = BABYLON.Tmp.Matrix[0];
  30588. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30589. var rotMat = BABYLON.Tmp.Matrix[1];
  30590. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  30591. rotMatInv.multiplyToRef(rotMat, rotMat);
  30592. this._rotateWithMatrix(rotMat, space, mesh);
  30593. };
  30594. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  30595. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30596. var rotMatInv = BABYLON.Tmp.Matrix[0];
  30597. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30598. var rotMat2 = BABYLON.Tmp.Matrix[1];
  30599. rotMat2.copyFrom(rotMat);
  30600. rotMatInv.multiplyToRef(rotMat, rotMat2);
  30601. this._rotateWithMatrix(rotMat2, space, mesh);
  30602. };
  30603. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  30604. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30605. var lmat = this.getLocalMatrix();
  30606. var lx = lmat.m[12];
  30607. var ly = lmat.m[13];
  30608. var lz = lmat.m[14];
  30609. var parent = this.getParent();
  30610. var parentScale = BABYLON.Tmp.Matrix[3];
  30611. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  30612. if (parent) {
  30613. if (space == BABYLON.Space.WORLD) {
  30614. if (mesh) {
  30615. parentScale.copyFrom(mesh.getWorldMatrix());
  30616. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  30617. }
  30618. else {
  30619. parentScale.copyFrom(parent.getAbsoluteTransform());
  30620. }
  30621. }
  30622. else {
  30623. parentScale = parent._scaleMatrix;
  30624. }
  30625. parentScaleInv.copyFrom(parentScale);
  30626. parentScaleInv.invert();
  30627. lmat.multiplyToRef(parentScale, lmat);
  30628. lmat.multiplyToRef(rmat, lmat);
  30629. lmat.multiplyToRef(parentScaleInv, lmat);
  30630. }
  30631. else {
  30632. if (space == BABYLON.Space.WORLD && mesh) {
  30633. parentScale.copyFrom(mesh.getWorldMatrix());
  30634. parentScaleInv.copyFrom(parentScale);
  30635. parentScaleInv.invert();
  30636. lmat.multiplyToRef(parentScale, lmat);
  30637. lmat.multiplyToRef(rmat, lmat);
  30638. lmat.multiplyToRef(parentScaleInv, lmat);
  30639. }
  30640. else {
  30641. lmat.multiplyToRef(rmat, lmat);
  30642. }
  30643. }
  30644. lmat.m[12] = lx;
  30645. lmat.m[13] = ly;
  30646. lmat.m[14] = lz;
  30647. this.computeAbsoluteTransforms();
  30648. this.markAsDirty();
  30649. };
  30650. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  30651. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30652. if (space == BABYLON.Space.WORLD) {
  30653. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  30654. scaleMatrix.copyFrom(this._scaleMatrix);
  30655. rotMatInv.copyFrom(this.getAbsoluteTransform());
  30656. if (mesh) {
  30657. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  30658. var meshScale = BABYLON.Tmp.Matrix[3];
  30659. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  30660. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  30661. }
  30662. rotMatInv.invert();
  30663. scaleMatrix.m[0] *= this._scalingDeterminant;
  30664. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  30665. }
  30666. else {
  30667. rotMatInv.copyFrom(this.getLocalMatrix());
  30668. rotMatInv.invert();
  30669. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  30670. scaleMatrix.copyFrom(this._scaleMatrix);
  30671. if (this._parent) {
  30672. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  30673. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  30674. pscaleMatrix.invert();
  30675. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  30676. }
  30677. else {
  30678. scaleMatrix.m[0] *= this._scalingDeterminant;
  30679. }
  30680. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  30681. }
  30682. };
  30683. Bone.prototype.getScale = function () {
  30684. return this._scaleVector.clone();
  30685. };
  30686. Bone.prototype.getScaleToRef = function (result) {
  30687. result.copyFrom(this._scaleVector);
  30688. };
  30689. Bone.prototype.getPosition = function (space, mesh) {
  30690. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30691. var pos = BABYLON.Vector3.Zero();
  30692. this.getPositionToRef(space, mesh, pos);
  30693. return pos;
  30694. };
  30695. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  30696. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30697. if (space == BABYLON.Space.LOCAL) {
  30698. var lm = this.getLocalMatrix();
  30699. result.x = lm.m[12];
  30700. result.y = lm.m[13];
  30701. result.z = lm.m[14];
  30702. }
  30703. else {
  30704. this._skeleton.computeAbsoluteTransforms();
  30705. var tmat = BABYLON.Tmp.Matrix[0];
  30706. if (mesh) {
  30707. tmat.copyFrom(this.getAbsoluteTransform());
  30708. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30709. }
  30710. else {
  30711. tmat = this.getAbsoluteTransform();
  30712. }
  30713. result.x = tmat.m[12];
  30714. result.y = tmat.m[13];
  30715. result.z = tmat.m[14];
  30716. }
  30717. };
  30718. Bone.prototype.getAbsolutePosition = function (mesh) {
  30719. var pos = BABYLON.Vector3.Zero();
  30720. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  30721. return pos;
  30722. };
  30723. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  30724. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  30725. };
  30726. Bone.prototype.computeAbsoluteTransforms = function () {
  30727. if (this._parent) {
  30728. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  30729. }
  30730. else {
  30731. this._absoluteTransform.copyFrom(this._matrix);
  30732. var poseMatrix = this._skeleton.getPoseMatrix();
  30733. if (poseMatrix) {
  30734. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  30735. }
  30736. }
  30737. var children = this.children;
  30738. var len = children.length;
  30739. for (var i = 0; i < len; i++) {
  30740. children[i].computeAbsoluteTransforms();
  30741. }
  30742. };
  30743. Bone.prototype.getDirection = function (localAxis, mesh) {
  30744. var result = BABYLON.Vector3.Zero();
  30745. this.getDirectionToRef(localAxis, mesh, result);
  30746. return result;
  30747. };
  30748. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  30749. this._skeleton.computeAbsoluteTransforms();
  30750. var mat = BABYLON.Tmp.Matrix[0];
  30751. mat.copyFrom(this.getAbsoluteTransform());
  30752. if (mesh) {
  30753. mat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30754. }
  30755. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  30756. result.normalize();
  30757. };
  30758. Bone.prototype.getRotation = function (space, mesh) {
  30759. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30760. var result = BABYLON.Vector3.Zero();
  30761. this.getRotationToRef(space, mesh, result);
  30762. return result;
  30763. };
  30764. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  30765. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30766. var quat = BABYLON.Tmp.Quaternion[0];
  30767. this.getRotationQuaternionToRef(space, mesh, quat);
  30768. quat.toEulerAnglesToRef(result);
  30769. };
  30770. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  30771. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30772. var result = BABYLON.Quaternion.Identity();
  30773. this.getRotationQuaternionToRef(space, mesh, result);
  30774. return result;
  30775. };
  30776. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  30777. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30778. if (space == BABYLON.Space.LOCAL) {
  30779. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  30780. }
  30781. else {
  30782. var mat = BABYLON.Tmp.Matrix[0];
  30783. var amat = this.getAbsoluteTransform();
  30784. if (mesh) {
  30785. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30786. }
  30787. else {
  30788. mat.copyFrom(amat);
  30789. }
  30790. mat.m[0] *= this._scalingDeterminant;
  30791. mat.m[1] *= this._scalingDeterminant;
  30792. mat.m[2] *= this._scalingDeterminant;
  30793. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  30794. }
  30795. };
  30796. Bone.prototype.getRotationMatrix = function (space, mesh) {
  30797. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30798. var result = BABYLON.Matrix.Identity();
  30799. this.getRotationMatrixToRef(space, mesh, result);
  30800. return result;
  30801. };
  30802. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  30803. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30804. if (space == BABYLON.Space.LOCAL) {
  30805. this.getLocalMatrix().getRotationMatrixToRef(result);
  30806. }
  30807. else {
  30808. var mat = BABYLON.Tmp.Matrix[0];
  30809. var amat = this.getAbsoluteTransform();
  30810. if (mesh) {
  30811. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30812. }
  30813. else {
  30814. mat.copyFrom(amat);
  30815. }
  30816. mat.m[0] *= this._scalingDeterminant;
  30817. mat.m[1] *= this._scalingDeterminant;
  30818. mat.m[2] *= this._scalingDeterminant;
  30819. mat.getRotationMatrixToRef(result);
  30820. }
  30821. };
  30822. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  30823. var result = BABYLON.Vector3.Zero();
  30824. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  30825. return result;
  30826. };
  30827. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  30828. this._skeleton.computeAbsoluteTransforms();
  30829. var tmat = BABYLON.Tmp.Matrix[0];
  30830. if (mesh) {
  30831. tmat.copyFrom(this.getAbsoluteTransform());
  30832. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30833. }
  30834. else {
  30835. tmat = this.getAbsoluteTransform();
  30836. }
  30837. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  30838. };
  30839. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  30840. var result = BABYLON.Vector3.Zero();
  30841. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  30842. return result;
  30843. };
  30844. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  30845. this._skeleton.computeAbsoluteTransforms();
  30846. var tmat = BABYLON.Tmp.Matrix[0];
  30847. tmat.copyFrom(this.getAbsoluteTransform());
  30848. if (mesh) {
  30849. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30850. }
  30851. tmat.invert();
  30852. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  30853. };
  30854. return Bone;
  30855. }(BABYLON.Node));
  30856. BABYLON.Bone = Bone;
  30857. })(BABYLON || (BABYLON = {}));
  30858. //# sourceMappingURL=babylon.bone.js.map
  30859. var BABYLON;
  30860. (function (BABYLON) {
  30861. var BoneIKController = (function () {
  30862. function BoneIKController(mesh, bone, options) {
  30863. this.targetPosition = BABYLON.Vector3.Zero();
  30864. this.poleTargetPosition = BABYLON.Vector3.Zero();
  30865. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  30866. this.poleAngle = 0;
  30867. this.slerpAmount = 1;
  30868. this._bone1Quat = BABYLON.Quaternion.Identity();
  30869. this._bone1Mat = BABYLON.Matrix.Identity();
  30870. this._bone2Ang = Math.PI;
  30871. this._maxAngle = Math.PI;
  30872. this._tmpVec1 = BABYLON.Vector3.Zero();
  30873. this._tmpVec2 = BABYLON.Vector3.Zero();
  30874. this._tmpVec3 = BABYLON.Vector3.Zero();
  30875. this._tmpVec4 = BABYLON.Vector3.Zero();
  30876. this._tmpVec5 = BABYLON.Vector3.Zero();
  30877. this._tmpMat1 = BABYLON.Matrix.Identity();
  30878. this._tmpMat2 = BABYLON.Matrix.Identity();
  30879. this._tmpQuat1 = BABYLON.Quaternion.Identity();
  30880. this._rightHandedSystem = false;
  30881. this._bendAxis = BABYLON.Vector3.Right();
  30882. this._slerping = false;
  30883. this._bone2 = bone;
  30884. this._bone1 = bone.getParent();
  30885. this.mesh = mesh;
  30886. if (bone.getAbsoluteTransform().determinant() > 0) {
  30887. this._rightHandedSystem = true;
  30888. this._bendAxis.x = 0;
  30889. this._bendAxis.y = 0;
  30890. this._bendAxis.z = 1;
  30891. }
  30892. if (this._bone1.length) {
  30893. var boneScale1 = this._bone1.getScale();
  30894. var boneScale2 = this._bone2.getScale();
  30895. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  30896. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  30897. }
  30898. else if (this._bone1.children[0]) {
  30899. mesh.computeWorldMatrix(true);
  30900. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  30901. var pos2 = this._bone2.getAbsolutePosition(mesh);
  30902. var pos3 = this._bone1.getAbsolutePosition(mesh);
  30903. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  30904. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  30905. }
  30906. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  30907. this.maxAngle = Math.PI;
  30908. if (options) {
  30909. if (options.targetMesh) {
  30910. this.targetMesh = options.targetMesh;
  30911. this.targetMesh.computeWorldMatrix(true);
  30912. }
  30913. if (options.poleTargetMesh) {
  30914. this.poleTargetMesh = options.poleTargetMesh;
  30915. this.poleTargetMesh.computeWorldMatrix(true);
  30916. }
  30917. else if (options.poleTargetBone) {
  30918. this.poleTargetBone = options.poleTargetBone;
  30919. }
  30920. else if (this._bone1.getParent()) {
  30921. this.poleTargetBone = this._bone1.getParent();
  30922. }
  30923. if (options.poleTargetLocalOffset) {
  30924. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  30925. }
  30926. if (options.poleAngle) {
  30927. this.poleAngle = options.poleAngle;
  30928. }
  30929. if (options.bendAxis) {
  30930. this._bendAxis.copyFrom(options.bendAxis);
  30931. }
  30932. if (options.maxAngle) {
  30933. this.maxAngle = options.maxAngle;
  30934. }
  30935. if (options.slerpAmount) {
  30936. this.slerpAmount = options.slerpAmount;
  30937. }
  30938. }
  30939. }
  30940. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  30941. get: function () {
  30942. return this._maxAngle;
  30943. },
  30944. set: function (value) {
  30945. this._setMaxAngle(value);
  30946. },
  30947. enumerable: true,
  30948. configurable: true
  30949. });
  30950. BoneIKController.prototype._setMaxAngle = function (ang) {
  30951. if (ang < 0) {
  30952. ang = 0;
  30953. }
  30954. if (ang > Math.PI || ang == undefined) {
  30955. ang = Math.PI;
  30956. }
  30957. this._maxAngle = ang;
  30958. var a = this._bone1Length;
  30959. var b = this._bone2Length;
  30960. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  30961. };
  30962. BoneIKController.prototype.update = function () {
  30963. var bone1 = this._bone1;
  30964. var target = this.targetPosition;
  30965. var poleTarget = this.poleTargetPosition;
  30966. var mat1 = this._tmpMat1;
  30967. var mat2 = this._tmpMat2;
  30968. if (this.targetMesh) {
  30969. target.copyFrom(this.targetMesh.getAbsolutePosition());
  30970. }
  30971. if (this.poleTargetBone) {
  30972. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  30973. }
  30974. else if (this.poleTargetMesh) {
  30975. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  30976. }
  30977. var bonePos = this._tmpVec1;
  30978. var zaxis = this._tmpVec2;
  30979. var xaxis = this._tmpVec3;
  30980. var yaxis = this._tmpVec4;
  30981. var upAxis = this._tmpVec5;
  30982. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  30983. poleTarget.subtractToRef(bonePos, upAxis);
  30984. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  30985. upAxis.y = 1;
  30986. }
  30987. else {
  30988. upAxis.normalize();
  30989. }
  30990. target.subtractToRef(bonePos, yaxis);
  30991. yaxis.normalize();
  30992. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  30993. zaxis.normalize();
  30994. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  30995. xaxis.normalize();
  30996. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  30997. var a = this._bone1Length;
  30998. var b = this._bone2Length;
  30999. var c = BABYLON.Vector3.Distance(bonePos, target);
  31000. if (this._maxReach > 0) {
  31001. c = Math.min(this._maxReach, c);
  31002. }
  31003. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  31004. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  31005. if (acosa > 1) {
  31006. acosa = 1;
  31007. }
  31008. if (acosb > 1) {
  31009. acosb = 1;
  31010. }
  31011. if (acosa < -1) {
  31012. acosa = -1;
  31013. }
  31014. if (acosb < -1) {
  31015. acosb = -1;
  31016. }
  31017. var angA = Math.acos(acosa);
  31018. var angB = Math.acos(acosb);
  31019. var angC = -angA - angB;
  31020. if (this._rightHandedSystem) {
  31021. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, Math.PI * .5, mat2);
  31022. mat2.multiplyToRef(mat1, mat1);
  31023. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  31024. mat2.multiplyToRef(mat1, mat1);
  31025. }
  31026. else {
  31027. this._tmpVec1.copyFrom(this._bendAxis);
  31028. this._tmpVec1.x *= -1;
  31029. BABYLON.Matrix.RotationAxisToRef(this._tmpVec1, -angB, mat2);
  31030. mat2.multiplyToRef(mat1, mat1);
  31031. }
  31032. if (this.poleAngle) {
  31033. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  31034. mat1.multiplyToRef(mat2, mat1);
  31035. }
  31036. if (this.slerpAmount < 1) {
  31037. if (!this._slerping) {
  31038. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  31039. }
  31040. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, this._tmpQuat1);
  31041. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, this._tmpQuat1, this.slerpAmount, this._bone1Quat);
  31042. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  31043. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  31044. this._slerping = true;
  31045. }
  31046. else {
  31047. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  31048. this._bone1Mat.copyFrom(mat1);
  31049. this._slerping = false;
  31050. }
  31051. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  31052. this._bone2Ang = angC;
  31053. };
  31054. return BoneIKController;
  31055. }());
  31056. BABYLON.BoneIKController = BoneIKController;
  31057. })(BABYLON || (BABYLON = {}));
  31058. //# sourceMappingURL=babylon.boneIKController.js.map
  31059. var BABYLON;
  31060. (function (BABYLON) {
  31061. var BoneLookController = (function () {
  31062. function BoneLookController(mesh, bone, target, options) {
  31063. this.upAxis = BABYLON.Vector3.Up();
  31064. this.adjustYaw = 0;
  31065. this.adjustPitch = 0;
  31066. this.adjustRoll = 0;
  31067. this._tmpVec1 = BABYLON.Vector3.Zero();
  31068. this._tmpVec2 = BABYLON.Vector3.Zero();
  31069. this._tmpVec3 = BABYLON.Vector3.Zero();
  31070. this._tmpVec4 = BABYLON.Vector3.Zero();
  31071. this._tmpMat1 = BABYLON.Matrix.Identity();
  31072. this._tmpMat2 = BABYLON.Matrix.Identity();
  31073. this.mesh = mesh;
  31074. this.bone = bone;
  31075. this.target = target;
  31076. if (options) {
  31077. if (options.adjustYaw) {
  31078. this.adjustYaw = options.adjustYaw;
  31079. }
  31080. if (options.adjustPitch) {
  31081. this.adjustPitch = options.adjustPitch;
  31082. }
  31083. if (options.adjustRoll) {
  31084. this.adjustRoll = options.adjustRoll;
  31085. }
  31086. }
  31087. }
  31088. BoneLookController.prototype.update = function () {
  31089. var bone = this.bone;
  31090. var target = this.target;
  31091. var bonePos = this._tmpVec1;
  31092. var zaxis = this._tmpVec2;
  31093. var xaxis = this._tmpVec3;
  31094. var yaxis = this._tmpVec4;
  31095. var mat1 = this._tmpMat1;
  31096. var mat2 = this._tmpMat2;
  31097. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  31098. target.subtractToRef(bonePos, zaxis);
  31099. zaxis.normalize();
  31100. BABYLON.Vector3.CrossToRef(this.upAxis, zaxis, xaxis);
  31101. xaxis.normalize();
  31102. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  31103. yaxis.normalize();
  31104. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  31105. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  31106. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, mat2);
  31107. mat2.multiplyToRef(mat1, mat1);
  31108. }
  31109. this.bone.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  31110. };
  31111. return BoneLookController;
  31112. }());
  31113. BABYLON.BoneLookController = BoneLookController;
  31114. })(BABYLON || (BABYLON = {}));
  31115. //# sourceMappingURL=babylon.boneLookController.js.map
  31116. var BABYLON;
  31117. (function (BABYLON) {
  31118. var Skeleton = (function () {
  31119. function Skeleton(name, id, scene) {
  31120. this.name = name;
  31121. this.id = id;
  31122. this.bones = new Array();
  31123. this.needInitialSkinMatrix = false;
  31124. this._isDirty = true;
  31125. this._meshesWithPoseMatrix = new Array();
  31126. this._identity = BABYLON.Matrix.Identity();
  31127. this._ranges = {};
  31128. this._lastAbsoluteTransformsUpdateId = -1;
  31129. this.bones = [];
  31130. this._scene = scene;
  31131. scene.skeletons.push(this);
  31132. //make sure it will recalculate the matrix next time prepare is called.
  31133. this._isDirty = true;
  31134. }
  31135. // Members
  31136. Skeleton.prototype.getTransformMatrices = function (mesh) {
  31137. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  31138. return mesh._bonesTransformMatrices;
  31139. }
  31140. if (!this._transformMatrices) {
  31141. this.prepare();
  31142. }
  31143. return this._transformMatrices;
  31144. };
  31145. Skeleton.prototype.getScene = function () {
  31146. return this._scene;
  31147. };
  31148. // Methods
  31149. /**
  31150. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31151. */
  31152. Skeleton.prototype.toString = function (fullDetails) {
  31153. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  31154. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  31155. if (fullDetails) {
  31156. ret += ", Ranges: {";
  31157. var first = true;
  31158. for (var name_1 in this._ranges) {
  31159. if (first) {
  31160. ret += ", ";
  31161. first = false;
  31162. }
  31163. ret += name_1;
  31164. }
  31165. ret += "}";
  31166. }
  31167. return ret;
  31168. };
  31169. /**
  31170. * Get bone's index searching by name
  31171. * @param {string} name is bone's name to search for
  31172. * @return {number} Indice of the bone. Returns -1 if not found
  31173. */
  31174. Skeleton.prototype.getBoneIndexByName = function (name) {
  31175. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  31176. if (this.bones[boneIndex].name === name) {
  31177. return boneIndex;
  31178. }
  31179. }
  31180. return -1;
  31181. };
  31182. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  31183. // check name not already in use
  31184. if (!this._ranges[name]) {
  31185. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  31186. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31187. if (this.bones[i].animations[0]) {
  31188. this.bones[i].animations[0].createRange(name, from, to);
  31189. }
  31190. }
  31191. }
  31192. };
  31193. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  31194. if (deleteFrames === void 0) { deleteFrames = true; }
  31195. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31196. if (this.bones[i].animations[0]) {
  31197. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  31198. }
  31199. }
  31200. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  31201. };
  31202. Skeleton.prototype.getAnimationRange = function (name) {
  31203. return this._ranges[name];
  31204. };
  31205. /**
  31206. * Returns as an Array, all AnimationRanges defined on this skeleton
  31207. */
  31208. Skeleton.prototype.getAnimationRanges = function () {
  31209. var animationRanges = [];
  31210. var name;
  31211. var i = 0;
  31212. for (name in this._ranges) {
  31213. animationRanges[i] = this._ranges[name];
  31214. i++;
  31215. }
  31216. return animationRanges;
  31217. };
  31218. /**
  31219. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  31220. */
  31221. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  31222. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  31223. if (this._ranges[name] || !source.getAnimationRange(name)) {
  31224. return false;
  31225. }
  31226. var ret = true;
  31227. var frameOffset = this._getHighestAnimationFrame() + 1;
  31228. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  31229. var boneDict = {};
  31230. var sourceBones = source.bones;
  31231. var nBones;
  31232. var i;
  31233. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  31234. boneDict[sourceBones[i].name] = sourceBones[i];
  31235. }
  31236. if (this.bones.length !== sourceBones.length) {
  31237. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  31238. ret = false;
  31239. }
  31240. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  31241. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  31242. var boneName = this.bones[i].name;
  31243. var sourceBone = boneDict[boneName];
  31244. if (sourceBone) {
  31245. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  31246. }
  31247. else {
  31248. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  31249. ret = false;
  31250. }
  31251. }
  31252. // do not call createAnimationRange(), since it also is done to bones, which was already done
  31253. var range = source.getAnimationRange(name);
  31254. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  31255. return ret;
  31256. };
  31257. Skeleton.prototype.returnToRest = function () {
  31258. for (var index = 0; index < this.bones.length; index++) {
  31259. this.bones[index].returnToRest();
  31260. }
  31261. };
  31262. Skeleton.prototype._getHighestAnimationFrame = function () {
  31263. var ret = 0;
  31264. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31265. if (this.bones[i].animations[0]) {
  31266. var highest = this.bones[i].animations[0].getHighestFrame();
  31267. if (ret < highest) {
  31268. ret = highest;
  31269. }
  31270. }
  31271. }
  31272. return ret;
  31273. };
  31274. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  31275. var range = this.getAnimationRange(name);
  31276. if (!range) {
  31277. return null;
  31278. }
  31279. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  31280. };
  31281. Skeleton.prototype._markAsDirty = function () {
  31282. this._isDirty = true;
  31283. };
  31284. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  31285. this._meshesWithPoseMatrix.push(mesh);
  31286. };
  31287. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  31288. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  31289. if (index > -1) {
  31290. this._meshesWithPoseMatrix.splice(index, 1);
  31291. }
  31292. };
  31293. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  31294. for (var index = 0; index < this.bones.length; index++) {
  31295. var bone = this.bones[index];
  31296. var parentBone = bone.getParent();
  31297. if (parentBone) {
  31298. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  31299. }
  31300. else {
  31301. if (initialSkinMatrix) {
  31302. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  31303. }
  31304. else {
  31305. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  31306. }
  31307. }
  31308. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  31309. }
  31310. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  31311. };
  31312. Skeleton.prototype.prepare = function () {
  31313. if (!this._isDirty) {
  31314. return;
  31315. }
  31316. if (this.needInitialSkinMatrix) {
  31317. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  31318. var mesh = this._meshesWithPoseMatrix[index];
  31319. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  31320. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  31321. }
  31322. var poseMatrix = mesh.getPoseMatrix();
  31323. // Prepare bones
  31324. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  31325. var bone = this.bones[boneIndex];
  31326. if (!bone.getParent()) {
  31327. var matrix = bone.getBaseMatrix();
  31328. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  31329. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  31330. }
  31331. }
  31332. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  31333. }
  31334. }
  31335. else {
  31336. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  31337. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  31338. }
  31339. this._computeTransformMatrices(this._transformMatrices, null);
  31340. }
  31341. this._isDirty = false;
  31342. this._scene._activeBones.addCount(this.bones.length, false);
  31343. };
  31344. Skeleton.prototype.getAnimatables = function () {
  31345. if (!this._animatables || this._animatables.length !== this.bones.length) {
  31346. this._animatables = [];
  31347. for (var index = 0; index < this.bones.length; index++) {
  31348. this._animatables.push(this.bones[index]);
  31349. }
  31350. }
  31351. return this._animatables;
  31352. };
  31353. Skeleton.prototype.clone = function (name, id) {
  31354. var result = new Skeleton(name, id || name, this._scene);
  31355. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  31356. for (var index = 0; index < this.bones.length; index++) {
  31357. var source = this.bones[index];
  31358. var parentBone = null;
  31359. if (source.getParent()) {
  31360. var parentIndex = this.bones.indexOf(source.getParent());
  31361. parentBone = result.bones[parentIndex];
  31362. }
  31363. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  31364. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  31365. }
  31366. if (this._ranges) {
  31367. result._ranges = {};
  31368. for (var rangeName in this._ranges) {
  31369. result._ranges[rangeName] = this._ranges[rangeName].clone();
  31370. }
  31371. }
  31372. this._isDirty = true;
  31373. return result;
  31374. };
  31375. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  31376. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  31377. this.bones.forEach(function (bone) {
  31378. bone.animations.forEach(function (animation) {
  31379. animation.enableBlending = true;
  31380. animation.blendingSpeed = blendingSpeed;
  31381. });
  31382. });
  31383. };
  31384. Skeleton.prototype.dispose = function () {
  31385. this._meshesWithPoseMatrix = [];
  31386. // Animations
  31387. this.getScene().stopAnimation(this);
  31388. // Remove from scene
  31389. this.getScene().removeSkeleton(this);
  31390. };
  31391. Skeleton.prototype.serialize = function () {
  31392. var serializationObject = {};
  31393. serializationObject.name = this.name;
  31394. serializationObject.id = this.id;
  31395. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  31396. serializationObject.bones = [];
  31397. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  31398. for (var index = 0; index < this.bones.length; index++) {
  31399. var bone = this.bones[index];
  31400. var serializedBone = {
  31401. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  31402. name: bone.name,
  31403. matrix: bone.getLocalMatrix().toArray(),
  31404. rest: bone.getRestPose().toArray()
  31405. };
  31406. serializationObject.bones.push(serializedBone);
  31407. if (bone.length) {
  31408. serializedBone.length = bone.length;
  31409. }
  31410. if (bone.animations && bone.animations.length > 0) {
  31411. serializedBone.animation = bone.animations[0].serialize();
  31412. }
  31413. serializationObject.ranges = [];
  31414. for (var name in this._ranges) {
  31415. var range = {};
  31416. range.name = name;
  31417. range.from = this._ranges[name].from;
  31418. range.to = this._ranges[name].to;
  31419. serializationObject.ranges.push(range);
  31420. }
  31421. }
  31422. return serializationObject;
  31423. };
  31424. Skeleton.Parse = function (parsedSkeleton, scene) {
  31425. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  31426. if (parsedSkeleton.dimensionsAtRest) {
  31427. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  31428. }
  31429. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  31430. var index;
  31431. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  31432. var parsedBone = parsedSkeleton.bones[index];
  31433. var parentBone = null;
  31434. if (parsedBone.parentBoneIndex > -1) {
  31435. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  31436. }
  31437. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  31438. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  31439. if (parsedBone.length) {
  31440. bone.length = parsedBone.length;
  31441. }
  31442. if (parsedBone.animation) {
  31443. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  31444. }
  31445. }
  31446. // placed after bones, so createAnimationRange can cascade down
  31447. if (parsedSkeleton.ranges) {
  31448. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  31449. var data = parsedSkeleton.ranges[index];
  31450. skeleton.createAnimationRange(data.name, data.from, data.to);
  31451. }
  31452. }
  31453. return skeleton;
  31454. };
  31455. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  31456. if (forceUpdate === void 0) { forceUpdate = false; }
  31457. var renderId = this._scene.getRenderId();
  31458. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  31459. this.bones[0].computeAbsoluteTransforms();
  31460. this._lastAbsoluteTransformsUpdateId = renderId;
  31461. }
  31462. };
  31463. Skeleton.prototype.getPoseMatrix = function () {
  31464. var poseMatrix;
  31465. if (this._meshesWithPoseMatrix.length > 0) {
  31466. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  31467. }
  31468. return poseMatrix;
  31469. };
  31470. return Skeleton;
  31471. }());
  31472. BABYLON.Skeleton = Skeleton;
  31473. })(BABYLON || (BABYLON = {}));
  31474. //# sourceMappingURL=babylon.skeleton.js.map
  31475. var BABYLON;
  31476. (function (BABYLON) {
  31477. var PostProcess = (function () {
  31478. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  31479. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  31480. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  31481. this.name = name;
  31482. this.width = -1;
  31483. this.height = -1;
  31484. /*
  31485. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  31486. Can only be used on a single postprocess or on the last one of a chain.
  31487. */
  31488. this.enablePixelPerfectMode = false;
  31489. this._reusable = false;
  31490. this._textures = new BABYLON.SmartArray(2);
  31491. this._currentRenderTextureInd = 0;
  31492. this._scaleRatio = new BABYLON.Vector2(1, 1);
  31493. // Events
  31494. /**
  31495. * An event triggered when the postprocess is activated.
  31496. * @type {BABYLON.Observable}
  31497. */
  31498. this.onActivateObservable = new BABYLON.Observable();
  31499. /**
  31500. * An event triggered when the postprocess changes its size.
  31501. * @type {BABYLON.Observable}
  31502. */
  31503. this.onSizeChangedObservable = new BABYLON.Observable();
  31504. /**
  31505. * An event triggered when the postprocess applies its effect.
  31506. * @type {BABYLON.Observable}
  31507. */
  31508. this.onApplyObservable = new BABYLON.Observable();
  31509. /**
  31510. * An event triggered before rendering the postprocess
  31511. * @type {BABYLON.Observable}
  31512. */
  31513. this.onBeforeRenderObservable = new BABYLON.Observable();
  31514. /**
  31515. * An event triggered after rendering the postprocess
  31516. * @type {BABYLON.Observable}
  31517. */
  31518. this.onAfterRenderObservable = new BABYLON.Observable();
  31519. if (camera != null) {
  31520. this._camera = camera;
  31521. this._scene = camera.getScene();
  31522. camera.attachPostProcess(this);
  31523. this._engine = this._scene.getEngine();
  31524. }
  31525. else {
  31526. this._engine = engine;
  31527. }
  31528. this._options = options;
  31529. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  31530. this._reusable = reusable || false;
  31531. this._textureType = textureType;
  31532. this._samplers = samplers || [];
  31533. this._samplers.push("textureSampler");
  31534. this._fragmentUrl = fragmentUrl;
  31535. this._parameters = parameters || [];
  31536. this._parameters.push("scale");
  31537. this.updateEffect(defines);
  31538. }
  31539. Object.defineProperty(PostProcess.prototype, "onActivate", {
  31540. set: function (callback) {
  31541. if (this._onActivateObserver) {
  31542. this.onActivateObservable.remove(this._onActivateObserver);
  31543. }
  31544. this._onActivateObserver = this.onActivateObservable.add(callback);
  31545. },
  31546. enumerable: true,
  31547. configurable: true
  31548. });
  31549. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  31550. set: function (callback) {
  31551. if (this._onSizeChangedObserver) {
  31552. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  31553. }
  31554. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  31555. },
  31556. enumerable: true,
  31557. configurable: true
  31558. });
  31559. Object.defineProperty(PostProcess.prototype, "onApply", {
  31560. set: function (callback) {
  31561. if (this._onApplyObserver) {
  31562. this.onApplyObservable.remove(this._onApplyObserver);
  31563. }
  31564. this._onApplyObserver = this.onApplyObservable.add(callback);
  31565. },
  31566. enumerable: true,
  31567. configurable: true
  31568. });
  31569. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  31570. set: function (callback) {
  31571. if (this._onBeforeRenderObserver) {
  31572. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  31573. }
  31574. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  31575. },
  31576. enumerable: true,
  31577. configurable: true
  31578. });
  31579. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  31580. set: function (callback) {
  31581. if (this._onAfterRenderObserver) {
  31582. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  31583. }
  31584. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  31585. },
  31586. enumerable: true,
  31587. configurable: true
  31588. });
  31589. PostProcess.prototype.updateEffect = function (defines) {
  31590. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  31591. };
  31592. PostProcess.prototype.isReusable = function () {
  31593. return this._reusable;
  31594. };
  31595. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  31596. PostProcess.prototype.markTextureDirty = function () {
  31597. this.width = -1;
  31598. };
  31599. PostProcess.prototype.activate = function (camera, sourceTexture) {
  31600. camera = camera || this._camera;
  31601. var scene = camera.getScene();
  31602. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  31603. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  31604. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  31605. var desiredWidth = this._options.width || requiredWidth;
  31606. var desiredHeight = this._options.height || requiredHeight;
  31607. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  31608. if (!this._options.width) {
  31609. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  31610. }
  31611. if (!this._options.height) {
  31612. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  31613. }
  31614. }
  31615. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  31616. if (this._textures.length > 0) {
  31617. for (var i = 0; i < this._textures.length; i++) {
  31618. this._engine._releaseTexture(this._textures.data[i]);
  31619. }
  31620. this._textures.reset();
  31621. }
  31622. this.width = desiredWidth;
  31623. this.height = desiredHeight;
  31624. var textureSize = { width: this.width, height: this.height };
  31625. var textureOptions = {
  31626. generateMipMaps: false,
  31627. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  31628. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  31629. samplingMode: this.renderTargetSamplingMode,
  31630. type: this._textureType
  31631. };
  31632. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  31633. if (this._reusable) {
  31634. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  31635. }
  31636. this.onSizeChangedObservable.notifyObservers(this);
  31637. }
  31638. if (this.enablePixelPerfectMode) {
  31639. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  31640. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  31641. }
  31642. else {
  31643. this._scaleRatio.copyFromFloats(1, 1);
  31644. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  31645. }
  31646. this.onActivateObservable.notifyObservers(camera);
  31647. // Clear
  31648. if (this.clearColor) {
  31649. this._engine.clear(this.clearColor, true, true, true);
  31650. }
  31651. else {
  31652. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  31653. }
  31654. if (this._reusable) {
  31655. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  31656. }
  31657. };
  31658. Object.defineProperty(PostProcess.prototype, "isSupported", {
  31659. get: function () {
  31660. return this._effect.isSupported;
  31661. },
  31662. enumerable: true,
  31663. configurable: true
  31664. });
  31665. PostProcess.prototype.apply = function () {
  31666. // Check
  31667. if (!this._effect.isReady())
  31668. return null;
  31669. // States
  31670. this._engine.enableEffect(this._effect);
  31671. this._engine.setState(false);
  31672. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31673. this._engine.setDepthBuffer(false);
  31674. this._engine.setDepthWrite(false);
  31675. // Texture
  31676. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  31677. // Parameters
  31678. this._effect.setVector2("scale", this._scaleRatio);
  31679. this.onApplyObservable.notifyObservers(this._effect);
  31680. return this._effect;
  31681. };
  31682. PostProcess.prototype.dispose = function (camera) {
  31683. camera = camera || this._camera;
  31684. if (this._textures.length > 0) {
  31685. for (var i = 0; i < this._textures.length; i++) {
  31686. this._engine._releaseTexture(this._textures.data[i]);
  31687. }
  31688. this._textures.reset();
  31689. }
  31690. if (!camera) {
  31691. return;
  31692. }
  31693. camera.detachPostProcess(this);
  31694. var index = camera._postProcesses.indexOf(this);
  31695. if (index === 0 && camera._postProcesses.length > 0) {
  31696. this._camera._postProcesses[0].markTextureDirty();
  31697. }
  31698. this.onActivateObservable.clear();
  31699. this.onAfterRenderObservable.clear();
  31700. this.onApplyObservable.clear();
  31701. this.onBeforeRenderObservable.clear();
  31702. this.onSizeChangedObservable.clear();
  31703. };
  31704. return PostProcess;
  31705. }());
  31706. BABYLON.PostProcess = PostProcess;
  31707. })(BABYLON || (BABYLON = {}));
  31708. //# sourceMappingURL=babylon.postProcess.js.map
  31709. var BABYLON;
  31710. (function (BABYLON) {
  31711. var PostProcessManager = (function () {
  31712. function PostProcessManager(scene) {
  31713. this._vertexBuffers = {};
  31714. this._scene = scene;
  31715. }
  31716. PostProcessManager.prototype._prepareBuffers = function () {
  31717. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  31718. return;
  31719. }
  31720. // VBO
  31721. var vertices = [];
  31722. vertices.push(1, 1);
  31723. vertices.push(-1, 1);
  31724. vertices.push(-1, -1);
  31725. vertices.push(1, -1);
  31726. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31727. // Indices
  31728. var indices = [];
  31729. indices.push(0);
  31730. indices.push(1);
  31731. indices.push(2);
  31732. indices.push(0);
  31733. indices.push(2);
  31734. indices.push(3);
  31735. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  31736. };
  31737. // Methods
  31738. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  31739. var postProcesses = this._scene.activeCamera._postProcesses;
  31740. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31741. return false;
  31742. }
  31743. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  31744. return true;
  31745. };
  31746. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  31747. var engine = this._scene.getEngine();
  31748. for (var index = 0; index < postProcesses.length; index++) {
  31749. if (index < postProcesses.length - 1) {
  31750. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31751. }
  31752. else {
  31753. if (targetTexture) {
  31754. engine.bindFramebuffer(targetTexture);
  31755. }
  31756. else {
  31757. engine.restoreDefaultFramebuffer();
  31758. }
  31759. }
  31760. var pp = postProcesses[index];
  31761. var effect = pp.apply();
  31762. if (effect) {
  31763. pp.onBeforeRenderObservable.notifyObservers(effect);
  31764. // VBOs
  31765. this._prepareBuffers();
  31766. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31767. // Draw order
  31768. engine.draw(true, 0, 6);
  31769. pp.onAfterRenderObservable.notifyObservers(effect);
  31770. }
  31771. }
  31772. // Restore depth buffer
  31773. engine.setDepthBuffer(true);
  31774. engine.setDepthWrite(true);
  31775. };
  31776. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  31777. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  31778. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31779. return;
  31780. }
  31781. var engine = this._scene.getEngine();
  31782. for (var index = 0, len = postProcesses.length; index < len; index++) {
  31783. if (index < len - 1) {
  31784. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31785. }
  31786. else {
  31787. if (targetTexture) {
  31788. engine.bindFramebuffer(targetTexture, faceIndex);
  31789. }
  31790. else {
  31791. engine.restoreDefaultFramebuffer();
  31792. }
  31793. }
  31794. if (doNotPresent) {
  31795. break;
  31796. }
  31797. var pp = postProcesses[index];
  31798. var effect = pp.apply();
  31799. if (effect) {
  31800. pp.onBeforeRenderObservable.notifyObservers(effect);
  31801. // VBOs
  31802. this._prepareBuffers();
  31803. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31804. // Draw order
  31805. engine.draw(true, 0, 6);
  31806. pp.onAfterRenderObservable.notifyObservers(effect);
  31807. }
  31808. }
  31809. // Restore depth buffer
  31810. engine.setDepthBuffer(true);
  31811. engine.setDepthWrite(true);
  31812. };
  31813. PostProcessManager.prototype.dispose = function () {
  31814. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31815. if (buffer) {
  31816. buffer.dispose();
  31817. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31818. }
  31819. if (this._indexBuffer) {
  31820. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31821. this._indexBuffer = null;
  31822. }
  31823. };
  31824. return PostProcessManager;
  31825. }());
  31826. BABYLON.PostProcessManager = PostProcessManager;
  31827. })(BABYLON || (BABYLON = {}));
  31828. //# sourceMappingURL=babylon.postProcessManager.js.map
  31829. var BABYLON;
  31830. (function (BABYLON) {
  31831. var PassPostProcess = (function (_super) {
  31832. __extends(PassPostProcess, _super);
  31833. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  31834. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable) || this;
  31835. }
  31836. return PassPostProcess;
  31837. }(BABYLON.PostProcess));
  31838. BABYLON.PassPostProcess = PassPostProcess;
  31839. })(BABYLON || (BABYLON = {}));
  31840. //# sourceMappingURL=babylon.passPostProcess.js.map
  31841. var BABYLON;
  31842. (function (BABYLON) {
  31843. /**
  31844. * This is a holder class for the physics joint created by the physics plugin.
  31845. * It holds a set of functions to control the underlying joint.
  31846. */
  31847. var PhysicsJoint = (function () {
  31848. function PhysicsJoint(type, jointData) {
  31849. this.type = type;
  31850. this.jointData = jointData;
  31851. jointData.nativeParams = jointData.nativeParams || {};
  31852. }
  31853. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  31854. get: function () {
  31855. return this._physicsJoint;
  31856. },
  31857. set: function (newJoint) {
  31858. if (this._physicsJoint) {
  31859. }
  31860. this._physicsJoint = newJoint;
  31861. },
  31862. enumerable: true,
  31863. configurable: true
  31864. });
  31865. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  31866. set: function (physicsPlugin) {
  31867. this._physicsPlugin = physicsPlugin;
  31868. },
  31869. enumerable: true,
  31870. configurable: true
  31871. });
  31872. /**
  31873. * Execute a function that is physics-plugin specific.
  31874. * @param {Function} func the function that will be executed.
  31875. * It accepts two parameters: the physics world and the physics joint.
  31876. */
  31877. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  31878. func(this._physicsPlugin.world, this._physicsJoint);
  31879. };
  31880. return PhysicsJoint;
  31881. }());
  31882. //TODO check if the native joints are the same
  31883. //Joint Types
  31884. PhysicsJoint.DistanceJoint = 0;
  31885. PhysicsJoint.HingeJoint = 1;
  31886. PhysicsJoint.BallAndSocketJoint = 2;
  31887. PhysicsJoint.WheelJoint = 3;
  31888. PhysicsJoint.SliderJoint = 4;
  31889. //OIMO
  31890. PhysicsJoint.PrismaticJoint = 5;
  31891. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  31892. PhysicsJoint.UniversalJoint = 6;
  31893. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  31894. //Cannon
  31895. //Similar to a Ball-Joint. Different in params
  31896. PhysicsJoint.PointToPointJoint = 8;
  31897. //Cannon only at the moment
  31898. PhysicsJoint.SpringJoint = 9;
  31899. PhysicsJoint.LockJoint = 10;
  31900. BABYLON.PhysicsJoint = PhysicsJoint;
  31901. /**
  31902. * A class representing a physics distance joint.
  31903. */
  31904. var DistanceJoint = (function (_super) {
  31905. __extends(DistanceJoint, _super);
  31906. function DistanceJoint(jointData) {
  31907. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  31908. }
  31909. /**
  31910. * Update the predefined distance.
  31911. */
  31912. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  31913. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  31914. };
  31915. return DistanceJoint;
  31916. }(PhysicsJoint));
  31917. BABYLON.DistanceJoint = DistanceJoint;
  31918. var MotorEnabledJoint = (function (_super) {
  31919. __extends(MotorEnabledJoint, _super);
  31920. function MotorEnabledJoint(type, jointData) {
  31921. return _super.call(this, type, jointData) || this;
  31922. }
  31923. /**
  31924. * Set the motor values.
  31925. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31926. * @param {number} force the force to apply
  31927. * @param {number} maxForce max force for this motor.
  31928. */
  31929. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  31930. this._physicsPlugin.setMotor(this, force, maxForce);
  31931. };
  31932. /**
  31933. * Set the motor's limits.
  31934. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31935. */
  31936. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  31937. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  31938. };
  31939. return MotorEnabledJoint;
  31940. }(PhysicsJoint));
  31941. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  31942. /**
  31943. * This class represents a single hinge physics joint
  31944. */
  31945. var HingeJoint = (function (_super) {
  31946. __extends(HingeJoint, _super);
  31947. function HingeJoint(jointData) {
  31948. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  31949. }
  31950. /**
  31951. * Set the motor values.
  31952. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31953. * @param {number} force the force to apply
  31954. * @param {number} maxForce max force for this motor.
  31955. */
  31956. HingeJoint.prototype.setMotor = function (force, maxForce) {
  31957. this._physicsPlugin.setMotor(this, force, maxForce);
  31958. };
  31959. /**
  31960. * Set the motor's limits.
  31961. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31962. */
  31963. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  31964. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  31965. };
  31966. return HingeJoint;
  31967. }(MotorEnabledJoint));
  31968. BABYLON.HingeJoint = HingeJoint;
  31969. /**
  31970. * This class represents a dual hinge physics joint (same as wheel joint)
  31971. */
  31972. var Hinge2Joint = (function (_super) {
  31973. __extends(Hinge2Joint, _super);
  31974. function Hinge2Joint(jointData) {
  31975. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  31976. }
  31977. /**
  31978. * Set the motor values.
  31979. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31980. * @param {number} force the force to apply
  31981. * @param {number} maxForce max force for this motor.
  31982. * @param {motorIndex} the motor's index, 0 or 1.
  31983. */
  31984. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  31985. if (motorIndex === void 0) { motorIndex = 0; }
  31986. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  31987. };
  31988. /**
  31989. * Set the motor limits.
  31990. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31991. * @param {number} upperLimit the upper limit
  31992. * @param {number} lowerLimit lower limit
  31993. * @param {motorIndex} the motor's index, 0 or 1.
  31994. */
  31995. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  31996. if (motorIndex === void 0) { motorIndex = 0; }
  31997. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  31998. };
  31999. return Hinge2Joint;
  32000. }(MotorEnabledJoint));
  32001. BABYLON.Hinge2Joint = Hinge2Joint;
  32002. })(BABYLON || (BABYLON = {}));
  32003. //# sourceMappingURL=babylon.physicsJoint.js.map
  32004. var BABYLON;
  32005. (function (BABYLON) {
  32006. var PhysicsImpostor = (function () {
  32007. function PhysicsImpostor(object, type, _options, _scene) {
  32008. if (_options === void 0) { _options = { mass: 0 }; }
  32009. var _this = this;
  32010. this.object = object;
  32011. this.type = type;
  32012. this._options = _options;
  32013. this._scene = _scene;
  32014. this._bodyUpdateRequired = false;
  32015. this._onBeforePhysicsStepCallbacks = new Array();
  32016. this._onAfterPhysicsStepCallbacks = new Array();
  32017. this._onPhysicsCollideCallbacks = [];
  32018. this._deltaPosition = BABYLON.Vector3.Zero();
  32019. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  32020. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  32021. /**
  32022. * this function is executed by the physics engine.
  32023. */
  32024. this.beforeStep = function () {
  32025. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  32026. //conjugate deltaRotation
  32027. if (_this._deltaRotationConjugated) {
  32028. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  32029. }
  32030. else {
  32031. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  32032. }
  32033. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  32034. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  32035. func(_this);
  32036. });
  32037. };
  32038. /**
  32039. * this function is executed by the physics engine.
  32040. */
  32041. this.afterStep = function () {
  32042. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  32043. func(_this);
  32044. });
  32045. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  32046. _this.object.position.addInPlace(_this._deltaPosition);
  32047. if (_this._deltaRotation) {
  32048. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  32049. }
  32050. };
  32051. //event and body object due to cannon's event-based architecture.
  32052. this.onCollide = function (e) {
  32053. if (!_this._onPhysicsCollideCallbacks.length)
  32054. return;
  32055. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  32056. if (otherImpostor) {
  32057. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  32058. return (obj.otherImpostors.length === 0 || obj.otherImpostors.indexOf(otherImpostor) !== -1);
  32059. }).forEach(function (obj) {
  32060. obj.callback(_this, otherImpostor);
  32061. });
  32062. }
  32063. };
  32064. //sanity check!
  32065. if (!this.object) {
  32066. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  32067. return;
  32068. }
  32069. //legacy support for old syntax.
  32070. if (!this._scene && object.getScene) {
  32071. this._scene = object.getScene();
  32072. }
  32073. this._physicsEngine = this._scene.getPhysicsEngine();
  32074. if (!this._physicsEngine) {
  32075. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  32076. }
  32077. else {
  32078. //set the object's quaternion, if not set
  32079. if (!this.object.rotationQuaternion) {
  32080. if (this.object.rotation) {
  32081. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  32082. }
  32083. else {
  32084. this.object.rotationQuaternion = new BABYLON.Quaternion();
  32085. }
  32086. }
  32087. //default options params
  32088. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  32089. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  32090. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  32091. this._joints = [];
  32092. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  32093. if (!this.object.parent) {
  32094. this._init();
  32095. }
  32096. }
  32097. }
  32098. /**
  32099. * This function will completly initialize this impostor.
  32100. * It will create a new body - but only if this mesh has no parent.
  32101. * If it has, this impostor will not be used other than to define the impostor
  32102. * of the child mesh.
  32103. */
  32104. PhysicsImpostor.prototype._init = function () {
  32105. this._physicsEngine.removeImpostor(this);
  32106. this.physicsBody = null;
  32107. this._parent = this._parent || this._getPhysicsParent();
  32108. if (!this.parent) {
  32109. this._physicsEngine.addImpostor(this);
  32110. }
  32111. };
  32112. PhysicsImpostor.prototype._getPhysicsParent = function () {
  32113. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  32114. var parentMesh = this.object.parent;
  32115. return parentMesh.physicsImpostor;
  32116. }
  32117. return;
  32118. };
  32119. /**
  32120. * Should a new body be generated.
  32121. */
  32122. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  32123. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  32124. };
  32125. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  32126. this.forceUpdate();
  32127. };
  32128. /**
  32129. * Force a regeneration of this or the parent's impostor's body.
  32130. * Use under cautious - This will remove all joints already implemented.
  32131. */
  32132. PhysicsImpostor.prototype.forceUpdate = function () {
  32133. this._init();
  32134. if (this.parent) {
  32135. this.parent.forceUpdate();
  32136. }
  32137. };
  32138. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  32139. /*public get mesh(): AbstractMesh {
  32140. return this._mesh;
  32141. }*/
  32142. /**
  32143. * Gets the body that holds this impostor. Either its own, or its parent.
  32144. */
  32145. get: function () {
  32146. return this._parent ? this._parent.physicsBody : this._physicsBody;
  32147. },
  32148. /**
  32149. * Set the physics body. Used mainly by the physics engine/plugin
  32150. */
  32151. set: function (physicsBody) {
  32152. if (this._physicsBody) {
  32153. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  32154. }
  32155. this._physicsBody = physicsBody;
  32156. this.resetUpdateFlags();
  32157. },
  32158. enumerable: true,
  32159. configurable: true
  32160. });
  32161. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  32162. get: function () {
  32163. return this._parent;
  32164. },
  32165. set: function (value) {
  32166. this._parent = value;
  32167. },
  32168. enumerable: true,
  32169. configurable: true
  32170. });
  32171. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  32172. this._bodyUpdateRequired = false;
  32173. };
  32174. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  32175. if (this.object.getBoundingInfo) {
  32176. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  32177. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  32178. }
  32179. else {
  32180. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  32181. }
  32182. };
  32183. PhysicsImpostor.prototype.getObjectCenter = function () {
  32184. if (this.object.getBoundingInfo) {
  32185. return this.object.getBoundingInfo().boundingBox.center;
  32186. }
  32187. else {
  32188. return this.object.position;
  32189. }
  32190. };
  32191. /**
  32192. * Get a specific parametes from the options parameter.
  32193. */
  32194. PhysicsImpostor.prototype.getParam = function (paramName) {
  32195. return this._options[paramName];
  32196. };
  32197. /**
  32198. * Sets a specific parameter in the options given to the physics plugin
  32199. */
  32200. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  32201. this._options[paramName] = value;
  32202. this._bodyUpdateRequired = true;
  32203. };
  32204. /**
  32205. * Specifically change the body's mass option. Won't recreate the physics body object
  32206. */
  32207. PhysicsImpostor.prototype.setMass = function (mass) {
  32208. if (this.getParam("mass") !== mass) {
  32209. this.setParam("mass", mass);
  32210. }
  32211. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  32212. };
  32213. PhysicsImpostor.prototype.getLinearVelocity = function () {
  32214. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  32215. };
  32216. /**
  32217. * Set the body's linear velocity.
  32218. */
  32219. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  32220. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  32221. };
  32222. PhysicsImpostor.prototype.getAngularVelocity = function () {
  32223. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  32224. };
  32225. /**
  32226. * Set the body's linear velocity.
  32227. */
  32228. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  32229. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  32230. };
  32231. /**
  32232. * Execute a function with the physics plugin native code.
  32233. * Provide a function the will have two variables - the world object and the physics body object.
  32234. */
  32235. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  32236. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  32237. };
  32238. /**
  32239. * Register a function that will be executed before the physics world is stepping forward.
  32240. */
  32241. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  32242. this._onBeforePhysicsStepCallbacks.push(func);
  32243. };
  32244. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  32245. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  32246. if (index > -1) {
  32247. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  32248. }
  32249. else {
  32250. BABYLON.Tools.Warn("Function to remove was not found");
  32251. }
  32252. };
  32253. /**
  32254. * Register a function that will be executed after the physics step
  32255. */
  32256. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  32257. this._onAfterPhysicsStepCallbacks.push(func);
  32258. };
  32259. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  32260. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  32261. if (index > -1) {
  32262. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  32263. }
  32264. else {
  32265. BABYLON.Tools.Warn("Function to remove was not found");
  32266. }
  32267. };
  32268. /**
  32269. * register a function that will be executed when this impostor collides against a different body.
  32270. */
  32271. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  32272. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  32273. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  32274. };
  32275. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  32276. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  32277. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  32278. if (index > -1) {
  32279. this._onPhysicsCollideCallbacks.splice(index, 1);
  32280. }
  32281. else {
  32282. BABYLON.Tools.Warn("Function to remove was not found");
  32283. }
  32284. };
  32285. /**
  32286. * Apply a force
  32287. */
  32288. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  32289. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  32290. };
  32291. /**
  32292. * Apply an impulse
  32293. */
  32294. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  32295. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  32296. };
  32297. /**
  32298. * A help function to create a joint.
  32299. */
  32300. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  32301. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  32302. this.addJoint(otherImpostor, joint);
  32303. };
  32304. /**
  32305. * Add a joint to this impostor with a different impostor.
  32306. */
  32307. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  32308. this._joints.push({
  32309. otherImpostor: otherImpostor,
  32310. joint: joint
  32311. });
  32312. this._physicsEngine.addJoint(this, otherImpostor, joint);
  32313. };
  32314. /**
  32315. * Will keep this body still, in a sleep mode.
  32316. */
  32317. PhysicsImpostor.prototype.sleep = function () {
  32318. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  32319. };
  32320. /**
  32321. * Wake the body up.
  32322. */
  32323. PhysicsImpostor.prototype.wakeUp = function () {
  32324. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  32325. };
  32326. PhysicsImpostor.prototype.clone = function (newObject) {
  32327. if (!newObject)
  32328. return null;
  32329. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  32330. };
  32331. PhysicsImpostor.prototype.dispose = function () {
  32332. var _this = this;
  32333. //no dispose if no physics engine is available.
  32334. if (!this._physicsEngine) {
  32335. return;
  32336. }
  32337. this._joints.forEach(function (j) {
  32338. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  32339. });
  32340. //dispose the physics body
  32341. this._physicsEngine.removeImpostor(this);
  32342. if (this.parent) {
  32343. this.parent.forceUpdate();
  32344. }
  32345. else {
  32346. }
  32347. };
  32348. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  32349. this._deltaPosition.copyFrom(position);
  32350. };
  32351. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  32352. if (!this._deltaRotation) {
  32353. this._deltaRotation = new BABYLON.Quaternion();
  32354. }
  32355. this._deltaRotation.copyFrom(rotation);
  32356. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  32357. };
  32358. return PhysicsImpostor;
  32359. }());
  32360. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  32361. //Impostor types
  32362. PhysicsImpostor.NoImpostor = 0;
  32363. PhysicsImpostor.SphereImpostor = 1;
  32364. PhysicsImpostor.BoxImpostor = 2;
  32365. PhysicsImpostor.PlaneImpostor = 3;
  32366. PhysicsImpostor.MeshImpostor = 4;
  32367. PhysicsImpostor.CylinderImpostor = 7;
  32368. PhysicsImpostor.ParticleImpostor = 8;
  32369. PhysicsImpostor.HeightmapImpostor = 9;
  32370. BABYLON.PhysicsImpostor = PhysicsImpostor;
  32371. })(BABYLON || (BABYLON = {}));
  32372. //# sourceMappingURL=babylon.physicsImpostor.js.map
  32373. var BABYLON;
  32374. (function (BABYLON) {
  32375. var PhysicsEngine = (function () {
  32376. function PhysicsEngine(gravity, _physicsPlugin) {
  32377. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  32378. this._physicsPlugin = _physicsPlugin;
  32379. //new methods and parameters
  32380. this._impostors = [];
  32381. this._joints = [];
  32382. if (!this._physicsPlugin.isSupported()) {
  32383. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  32384. + "Please make sure it is included.");
  32385. }
  32386. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  32387. this.setGravity(gravity);
  32388. this.setTimeStep();
  32389. }
  32390. PhysicsEngine.prototype.setGravity = function (gravity) {
  32391. this.gravity = gravity;
  32392. this._physicsPlugin.setGravity(this.gravity);
  32393. };
  32394. /**
  32395. * Set the time step of the physics engine.
  32396. * default is 1/60.
  32397. * To slow it down, enter 1/600 for example.
  32398. * To speed it up, 1/30
  32399. * @param {number} newTimeStep the new timestep to apply to this world.
  32400. */
  32401. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  32402. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  32403. this._physicsPlugin.setTimeStep(newTimeStep);
  32404. };
  32405. PhysicsEngine.prototype.dispose = function () {
  32406. this._impostors.forEach(function (impostor) {
  32407. impostor.dispose();
  32408. });
  32409. this._physicsPlugin.dispose();
  32410. };
  32411. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  32412. return this._physicsPlugin.name;
  32413. };
  32414. /**
  32415. * Adding a new impostor for the impostor tracking.
  32416. * This will be done by the impostor itself.
  32417. * @param {PhysicsImpostor} impostor the impostor to add
  32418. */
  32419. PhysicsEngine.prototype.addImpostor = function (impostor) {
  32420. impostor.uniqueId = this._impostors.push(impostor);
  32421. //if no parent, generate the body
  32422. if (!impostor.parent) {
  32423. this._physicsPlugin.generatePhysicsBody(impostor);
  32424. }
  32425. };
  32426. /**
  32427. * Remove an impostor from the engine.
  32428. * This impostor and its mesh will not longer be updated by the physics engine.
  32429. * @param {PhysicsImpostor} impostor the impostor to remove
  32430. */
  32431. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  32432. var index = this._impostors.indexOf(impostor);
  32433. if (index > -1) {
  32434. var removed = this._impostors.splice(index, 1);
  32435. //Is it needed?
  32436. if (removed.length) {
  32437. //this will also remove it from the world.
  32438. removed[0].physicsBody = null;
  32439. }
  32440. }
  32441. };
  32442. /**
  32443. * Add a joint to the physics engine
  32444. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  32445. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  32446. * @param {PhysicsJoint} the joint that will connect both impostors.
  32447. */
  32448. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  32449. var impostorJoint = {
  32450. mainImpostor: mainImpostor,
  32451. connectedImpostor: connectedImpostor,
  32452. joint: joint
  32453. };
  32454. joint.physicsPlugin = this._physicsPlugin;
  32455. this._joints.push(impostorJoint);
  32456. this._physicsPlugin.generateJoint(impostorJoint);
  32457. };
  32458. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  32459. var matchingJoints = this._joints.filter(function (impostorJoint) {
  32460. return (impostorJoint.connectedImpostor === connectedImpostor
  32461. && impostorJoint.joint === joint
  32462. && impostorJoint.mainImpostor === mainImpostor);
  32463. });
  32464. if (matchingJoints.length) {
  32465. this._physicsPlugin.removeJoint(matchingJoints[0]);
  32466. }
  32467. };
  32468. /**
  32469. * Called by the scene. no need to call it.
  32470. */
  32471. PhysicsEngine.prototype._step = function (delta) {
  32472. var _this = this;
  32473. //check if any mesh has no body / requires an update
  32474. this._impostors.forEach(function (impostor) {
  32475. if (impostor.isBodyInitRequired()) {
  32476. _this._physicsPlugin.generatePhysicsBody(impostor);
  32477. }
  32478. });
  32479. if (delta > 0.1) {
  32480. delta = 0.1;
  32481. }
  32482. else if (delta <= 0) {
  32483. delta = 1.0 / 60.0;
  32484. }
  32485. this._physicsPlugin.executeStep(delta, this._impostors);
  32486. };
  32487. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  32488. return this._physicsPlugin;
  32489. };
  32490. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  32491. for (var i = 0; i < this._impostors.length; ++i) {
  32492. if (this._impostors[i].object === object) {
  32493. return this._impostors[i];
  32494. }
  32495. }
  32496. };
  32497. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  32498. for (var i = 0; i < this._impostors.length; ++i) {
  32499. if (this._impostors[i].physicsBody === body) {
  32500. return this._impostors[i];
  32501. }
  32502. }
  32503. };
  32504. return PhysicsEngine;
  32505. }());
  32506. // Statics, Legacy support.
  32507. /**
  32508. * @Deprecated
  32509. *
  32510. */
  32511. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  32512. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  32513. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  32514. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  32515. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  32516. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  32517. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  32518. PhysicsEngine.CapsuleImpostor = -1;
  32519. PhysicsEngine.ConeImpostor = -1;
  32520. PhysicsEngine.ConvexHullImpostor = -1;
  32521. PhysicsEngine.Epsilon = 0.001;
  32522. BABYLON.PhysicsEngine = PhysicsEngine;
  32523. })(BABYLON || (BABYLON = {}));
  32524. //# sourceMappingURL=babylon.physicsEngine.js.map
  32525. var BABYLON;
  32526. (function (BABYLON) {
  32527. var VertexData = (function () {
  32528. function VertexData() {
  32529. }
  32530. VertexData.prototype.set = function (data, kind) {
  32531. switch (kind) {
  32532. case BABYLON.VertexBuffer.PositionKind:
  32533. this.positions = data;
  32534. break;
  32535. case BABYLON.VertexBuffer.NormalKind:
  32536. this.normals = data;
  32537. break;
  32538. case BABYLON.VertexBuffer.UVKind:
  32539. this.uvs = data;
  32540. break;
  32541. case BABYLON.VertexBuffer.UV2Kind:
  32542. this.uvs2 = data;
  32543. break;
  32544. case BABYLON.VertexBuffer.UV3Kind:
  32545. this.uvs3 = data;
  32546. break;
  32547. case BABYLON.VertexBuffer.UV4Kind:
  32548. this.uvs4 = data;
  32549. break;
  32550. case BABYLON.VertexBuffer.UV5Kind:
  32551. this.uvs5 = data;
  32552. break;
  32553. case BABYLON.VertexBuffer.UV6Kind:
  32554. this.uvs6 = data;
  32555. break;
  32556. case BABYLON.VertexBuffer.ColorKind:
  32557. this.colors = data;
  32558. break;
  32559. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32560. this.matricesIndices = data;
  32561. break;
  32562. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32563. this.matricesWeights = data;
  32564. break;
  32565. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32566. this.matricesIndicesExtra = data;
  32567. break;
  32568. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32569. this.matricesWeightsExtra = data;
  32570. break;
  32571. }
  32572. };
  32573. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32574. this._applyTo(mesh, updatable);
  32575. };
  32576. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32577. this._applyTo(geometry, updatable);
  32578. };
  32579. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32580. this._update(mesh);
  32581. };
  32582. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32583. this._update(geometry);
  32584. };
  32585. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32586. if (this.positions) {
  32587. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32588. }
  32589. if (this.normals) {
  32590. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32591. }
  32592. if (this.uvs) {
  32593. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32594. }
  32595. if (this.uvs2) {
  32596. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32597. }
  32598. if (this.uvs3) {
  32599. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32600. }
  32601. if (this.uvs4) {
  32602. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32603. }
  32604. if (this.uvs5) {
  32605. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32606. }
  32607. if (this.uvs6) {
  32608. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32609. }
  32610. if (this.colors) {
  32611. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32612. }
  32613. if (this.matricesIndices) {
  32614. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32615. }
  32616. if (this.matricesWeights) {
  32617. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32618. }
  32619. if (this.matricesIndicesExtra) {
  32620. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32621. }
  32622. if (this.matricesWeightsExtra) {
  32623. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32624. }
  32625. if (this.indices) {
  32626. meshOrGeometry.setIndices(this.indices);
  32627. }
  32628. };
  32629. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32630. if (this.positions) {
  32631. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32632. }
  32633. if (this.normals) {
  32634. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32635. }
  32636. if (this.uvs) {
  32637. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32638. }
  32639. if (this.uvs2) {
  32640. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32641. }
  32642. if (this.uvs3) {
  32643. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32644. }
  32645. if (this.uvs4) {
  32646. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32647. }
  32648. if (this.uvs5) {
  32649. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32650. }
  32651. if (this.uvs6) {
  32652. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32653. }
  32654. if (this.colors) {
  32655. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32656. }
  32657. if (this.matricesIndices) {
  32658. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32659. }
  32660. if (this.matricesWeights) {
  32661. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32662. }
  32663. if (this.matricesIndicesExtra) {
  32664. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32665. }
  32666. if (this.matricesWeightsExtra) {
  32667. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32668. }
  32669. if (this.indices) {
  32670. meshOrGeometry.setIndices(this.indices);
  32671. }
  32672. };
  32673. VertexData.prototype.transform = function (matrix) {
  32674. var transformed = BABYLON.Vector3.Zero();
  32675. var index;
  32676. if (this.positions) {
  32677. var position = BABYLON.Vector3.Zero();
  32678. for (index = 0; index < this.positions.length; index += 3) {
  32679. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32680. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32681. this.positions[index] = transformed.x;
  32682. this.positions[index + 1] = transformed.y;
  32683. this.positions[index + 2] = transformed.z;
  32684. }
  32685. }
  32686. if (this.normals) {
  32687. var normal = BABYLON.Vector3.Zero();
  32688. for (index = 0; index < this.normals.length; index += 3) {
  32689. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32690. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32691. this.normals[index] = transformed.x;
  32692. this.normals[index + 1] = transformed.y;
  32693. this.normals[index + 2] = transformed.z;
  32694. }
  32695. }
  32696. };
  32697. VertexData.prototype.merge = function (other) {
  32698. if (other.indices) {
  32699. if (!this.indices) {
  32700. this.indices = [];
  32701. }
  32702. var offset = this.positions ? this.positions.length / 3 : 0;
  32703. for (var index = 0; index < other.indices.length; index++) {
  32704. //TODO check type - if Int32Array!
  32705. this.indices.push(other.indices[index] + offset);
  32706. }
  32707. }
  32708. this.positions = this._mergeElement(this.positions, other.positions);
  32709. this.normals = this._mergeElement(this.normals, other.normals);
  32710. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32711. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32712. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32713. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32714. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32715. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32716. this.colors = this._mergeElement(this.colors, other.colors);
  32717. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32718. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32719. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32720. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32721. };
  32722. VertexData.prototype._mergeElement = function (source, other) {
  32723. if (!other)
  32724. return source;
  32725. if (!source)
  32726. return other;
  32727. var len = other.length + source.length;
  32728. var isSrcTypedArray = source instanceof Float32Array;
  32729. var isOthTypedArray = other instanceof Float32Array;
  32730. // use non-loop method when the source is Float32Array
  32731. if (isSrcTypedArray) {
  32732. var ret32 = new Float32Array(len);
  32733. ret32.set(source);
  32734. ret32.set(other, source.length);
  32735. return ret32;
  32736. }
  32737. else if (!isOthTypedArray) {
  32738. return source.concat(other);
  32739. }
  32740. else {
  32741. var ret = source.slice(0); // copy source to a separate array
  32742. for (var i = 0, len = other.length; i < len; i++) {
  32743. ret.push(other[i]);
  32744. }
  32745. return ret;
  32746. }
  32747. };
  32748. VertexData.prototype.serialize = function () {
  32749. var serializationObject = this.serialize();
  32750. if (this.positions) {
  32751. serializationObject.positions = this.positions;
  32752. }
  32753. if (this.normals) {
  32754. serializationObject.normals = this.normals;
  32755. }
  32756. if (this.uvs) {
  32757. serializationObject.uvs = this.uvs;
  32758. }
  32759. if (this.uvs2) {
  32760. serializationObject.uvs2 = this.uvs2;
  32761. }
  32762. if (this.uvs3) {
  32763. serializationObject.uvs3 = this.uvs3;
  32764. }
  32765. if (this.uvs4) {
  32766. serializationObject.uvs4 = this.uvs4;
  32767. }
  32768. if (this.uvs5) {
  32769. serializationObject.uvs5 = this.uvs5;
  32770. }
  32771. if (this.uvs6) {
  32772. serializationObject.uvs6 = this.uvs6;
  32773. }
  32774. if (this.colors) {
  32775. serializationObject.colors = this.colors;
  32776. }
  32777. if (this.matricesIndices) {
  32778. serializationObject.matricesIndices = this.matricesIndices;
  32779. serializationObject.matricesIndices._isExpanded = true;
  32780. }
  32781. if (this.matricesWeights) {
  32782. serializationObject.matricesWeights = this.matricesWeights;
  32783. }
  32784. if (this.matricesIndicesExtra) {
  32785. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32786. serializationObject.matricesIndicesExtra._isExpanded = true;
  32787. }
  32788. if (this.matricesWeightsExtra) {
  32789. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32790. }
  32791. serializationObject.indices = this.indices;
  32792. return serializationObject;
  32793. };
  32794. // Statics
  32795. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  32796. return VertexData._ExtractFrom(mesh, copyWhenShared);
  32797. };
  32798. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  32799. return VertexData._ExtractFrom(geometry, copyWhenShared);
  32800. };
  32801. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  32802. var result = new VertexData();
  32803. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32804. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  32805. }
  32806. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32807. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  32808. }
  32809. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32810. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  32811. }
  32812. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32813. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  32814. }
  32815. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32816. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  32817. }
  32818. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32819. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  32820. }
  32821. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32822. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  32823. }
  32824. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32825. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  32826. }
  32827. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32828. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  32829. }
  32830. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32831. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  32832. }
  32833. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32834. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  32835. }
  32836. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32837. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  32838. }
  32839. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32840. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  32841. }
  32842. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32843. return result;
  32844. };
  32845. VertexData.CreateRibbon = function (options) {
  32846. var pathArray = options.pathArray;
  32847. var closeArray = options.closeArray || false;
  32848. var closePath = options.closePath || false;
  32849. var invertUV = options.invertUV || false;
  32850. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32851. var offset = options.offset || defaultOffset;
  32852. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32853. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32854. var positions = [];
  32855. var indices = [];
  32856. var normals = [];
  32857. var uvs = [];
  32858. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32859. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32860. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32861. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32862. var minlg; // minimal length among all paths from pathArray
  32863. var lg = []; // array of path lengths : nb of vertex per path
  32864. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32865. var p; // path iterator
  32866. var i; // point iterator
  32867. var j; // point iterator
  32868. // if single path in pathArray
  32869. if (pathArray.length < 2) {
  32870. var ar1 = [];
  32871. var ar2 = [];
  32872. for (i = 0; i < pathArray[0].length - offset; i++) {
  32873. ar1.push(pathArray[0][i]);
  32874. ar2.push(pathArray[0][i + offset]);
  32875. }
  32876. pathArray = [ar1, ar2];
  32877. }
  32878. // positions and horizontal distances (u)
  32879. var idc = 0;
  32880. var closePathCorr = (closePath) ? 1 : 0;
  32881. var path;
  32882. var l;
  32883. minlg = pathArray[0].length;
  32884. var vectlg;
  32885. var dist;
  32886. for (p = 0; p < pathArray.length; p++) {
  32887. uTotalDistance[p] = 0;
  32888. us[p] = [0];
  32889. path = pathArray[p];
  32890. l = path.length;
  32891. minlg = (minlg < l) ? minlg : l;
  32892. j = 0;
  32893. while (j < l) {
  32894. positions.push(path[j].x, path[j].y, path[j].z);
  32895. if (j > 0) {
  32896. vectlg = path[j].subtract(path[j - 1]).length();
  32897. dist = vectlg + uTotalDistance[p];
  32898. us[p].push(dist);
  32899. uTotalDistance[p] = dist;
  32900. }
  32901. j++;
  32902. }
  32903. if (closePath) {
  32904. j--;
  32905. positions.push(path[0].x, path[0].y, path[0].z);
  32906. vectlg = path[j].subtract(path[0]).length();
  32907. dist = vectlg + uTotalDistance[p];
  32908. us[p].push(dist);
  32909. uTotalDistance[p] = dist;
  32910. }
  32911. lg[p] = l + closePathCorr;
  32912. idx[p] = idc;
  32913. idc += (l + closePathCorr);
  32914. }
  32915. // vertical distances (v)
  32916. var path1;
  32917. var path2;
  32918. var vertex1;
  32919. var vertex2;
  32920. for (i = 0; i < minlg + closePathCorr; i++) {
  32921. vTotalDistance[i] = 0;
  32922. vs[i] = [0];
  32923. for (p = 0; p < pathArray.length - 1; p++) {
  32924. path1 = pathArray[p];
  32925. path2 = pathArray[p + 1];
  32926. if (i === minlg) {
  32927. vertex1 = path1[0];
  32928. vertex2 = path2[0];
  32929. }
  32930. else {
  32931. vertex1 = path1[i];
  32932. vertex2 = path2[i];
  32933. }
  32934. vectlg = vertex2.subtract(vertex1).length();
  32935. dist = vectlg + vTotalDistance[i];
  32936. vs[i].push(dist);
  32937. vTotalDistance[i] = dist;
  32938. }
  32939. if (closeArray) {
  32940. path1 = pathArray[p];
  32941. path2 = pathArray[0];
  32942. if (i === minlg) {
  32943. vertex2 = path2[0];
  32944. }
  32945. vectlg = vertex2.subtract(vertex1).length();
  32946. dist = vectlg + vTotalDistance[i];
  32947. vTotalDistance[i] = dist;
  32948. }
  32949. }
  32950. // uvs
  32951. var u;
  32952. var v;
  32953. for (p = 0; p < pathArray.length; p++) {
  32954. for (i = 0; i < minlg + closePathCorr; i++) {
  32955. u = us[p][i] / uTotalDistance[p];
  32956. v = vs[i][p] / vTotalDistance[i];
  32957. if (invertUV) {
  32958. uvs.push(v, u);
  32959. }
  32960. else {
  32961. uvs.push(u, v);
  32962. }
  32963. }
  32964. }
  32965. // indices
  32966. p = 0; // path index
  32967. var pi = 0; // positions array index
  32968. var l1 = lg[p] - 1; // path1 length
  32969. var l2 = lg[p + 1] - 1; // path2 length
  32970. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32971. var shft = idx[1] - idx[0]; // shift
  32972. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32973. while (pi <= min && p < path1nb) {
  32974. // 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
  32975. indices.push(pi, pi + shft, pi + 1);
  32976. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32977. pi += 1;
  32978. if (pi === min) {
  32979. p++;
  32980. if (p === lg.length - 1) {
  32981. shft = idx[0] - idx[p];
  32982. l1 = lg[p] - 1;
  32983. l2 = lg[0] - 1;
  32984. }
  32985. else {
  32986. shft = idx[p + 1] - idx[p];
  32987. l1 = lg[p] - 1;
  32988. l2 = lg[p + 1] - 1;
  32989. }
  32990. pi = idx[p];
  32991. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32992. }
  32993. }
  32994. // normals
  32995. VertexData.ComputeNormals(positions, indices, normals);
  32996. if (closePath) {
  32997. var indexFirst = 0;
  32998. var indexLast = 0;
  32999. for (p = 0; p < pathArray.length; p++) {
  33000. indexFirst = idx[p] * 3;
  33001. if (p + 1 < pathArray.length) {
  33002. indexLast = (idx[p + 1] - 1) * 3;
  33003. }
  33004. else {
  33005. indexLast = normals.length - 3;
  33006. }
  33007. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33008. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33009. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33010. normals[indexLast] = normals[indexFirst];
  33011. normals[indexLast + 1] = normals[indexFirst + 1];
  33012. normals[indexLast + 2] = normals[indexFirst + 2];
  33013. }
  33014. }
  33015. // sides
  33016. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33017. // Result
  33018. var vertexData = new VertexData();
  33019. vertexData.indices = indices;
  33020. vertexData.positions = positions;
  33021. vertexData.normals = normals;
  33022. vertexData.uvs = uvs;
  33023. if (closePath) {
  33024. vertexData._idx = idx;
  33025. }
  33026. return vertexData;
  33027. };
  33028. VertexData.CreateBox = function (options) {
  33029. var normalsSource = [
  33030. new BABYLON.Vector3(0, 0, 1),
  33031. new BABYLON.Vector3(0, 0, -1),
  33032. new BABYLON.Vector3(1, 0, 0),
  33033. new BABYLON.Vector3(-1, 0, 0),
  33034. new BABYLON.Vector3(0, 1, 0),
  33035. new BABYLON.Vector3(0, -1, 0)
  33036. ];
  33037. var indices = [];
  33038. var positions = [];
  33039. var normals = [];
  33040. var uvs = [];
  33041. var width = options.width || options.size || 1;
  33042. var height = options.height || options.size || 1;
  33043. var depth = options.depth || options.size || 1;
  33044. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33045. var faceUV = options.faceUV || new Array(6);
  33046. var faceColors = options.faceColors;
  33047. var colors = [];
  33048. // default face colors and UV if undefined
  33049. for (var f = 0; f < 6; f++) {
  33050. if (faceUV[f] === undefined) {
  33051. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33052. }
  33053. if (faceColors && faceColors[f] === undefined) {
  33054. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33055. }
  33056. }
  33057. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33058. // Create each face in turn.
  33059. for (var index = 0; index < normalsSource.length; index++) {
  33060. var normal = normalsSource[index];
  33061. // Get two vectors perpendicular to the face normal and to each other.
  33062. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33063. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33064. // Six indices (two triangles) per face.
  33065. var verticesLength = positions.length / 3;
  33066. indices.push(verticesLength);
  33067. indices.push(verticesLength + 1);
  33068. indices.push(verticesLength + 2);
  33069. indices.push(verticesLength);
  33070. indices.push(verticesLength + 2);
  33071. indices.push(verticesLength + 3);
  33072. // Four vertices per face.
  33073. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33074. positions.push(vertex.x, vertex.y, vertex.z);
  33075. normals.push(normal.x, normal.y, normal.z);
  33076. uvs.push(faceUV[index].z, faceUV[index].w);
  33077. if (faceColors) {
  33078. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33079. }
  33080. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33081. positions.push(vertex.x, vertex.y, vertex.z);
  33082. normals.push(normal.x, normal.y, normal.z);
  33083. uvs.push(faceUV[index].x, faceUV[index].w);
  33084. if (faceColors) {
  33085. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33086. }
  33087. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33088. positions.push(vertex.x, vertex.y, vertex.z);
  33089. normals.push(normal.x, normal.y, normal.z);
  33090. uvs.push(faceUV[index].x, faceUV[index].y);
  33091. if (faceColors) {
  33092. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33093. }
  33094. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33095. positions.push(vertex.x, vertex.y, vertex.z);
  33096. normals.push(normal.x, normal.y, normal.z);
  33097. uvs.push(faceUV[index].z, faceUV[index].y);
  33098. if (faceColors) {
  33099. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33100. }
  33101. }
  33102. // sides
  33103. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33104. // Result
  33105. var vertexData = new VertexData();
  33106. vertexData.indices = indices;
  33107. vertexData.positions = positions;
  33108. vertexData.normals = normals;
  33109. vertexData.uvs = uvs;
  33110. if (faceColors) {
  33111. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33112. vertexData.colors = totalColors;
  33113. }
  33114. return vertexData;
  33115. };
  33116. VertexData.CreateSphere = function (options) {
  33117. var segments = options.segments || 32;
  33118. var diameterX = options.diameterX || options.diameter || 1;
  33119. var diameterY = options.diameterY || options.diameter || 1;
  33120. var diameterZ = options.diameterZ || options.diameter || 1;
  33121. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33122. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33123. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33124. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33125. var totalZRotationSteps = 2 + segments;
  33126. var totalYRotationSteps = 2 * totalZRotationSteps;
  33127. var indices = [];
  33128. var positions = [];
  33129. var normals = [];
  33130. var uvs = [];
  33131. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33132. var normalizedZ = zRotationStep / totalZRotationSteps;
  33133. var angleZ = normalizedZ * Math.PI * slice;
  33134. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33135. var normalizedY = yRotationStep / totalYRotationSteps;
  33136. var angleY = normalizedY * Math.PI * 2 * arc;
  33137. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33138. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33139. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33140. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33141. var vertex = complete.multiply(radius);
  33142. var normal = complete.divide(radius).normalize();
  33143. positions.push(vertex.x, vertex.y, vertex.z);
  33144. normals.push(normal.x, normal.y, normal.z);
  33145. uvs.push(normalizedY, normalizedZ);
  33146. }
  33147. if (zRotationStep > 0) {
  33148. var verticesCount = positions.length / 3;
  33149. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33150. indices.push((firstIndex));
  33151. indices.push((firstIndex + 1));
  33152. indices.push(firstIndex + totalYRotationSteps + 1);
  33153. indices.push((firstIndex + totalYRotationSteps + 1));
  33154. indices.push((firstIndex + 1));
  33155. indices.push((firstIndex + totalYRotationSteps + 2));
  33156. }
  33157. }
  33158. }
  33159. // Sides
  33160. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33161. // Result
  33162. var vertexData = new VertexData();
  33163. vertexData.indices = indices;
  33164. vertexData.positions = positions;
  33165. vertexData.normals = normals;
  33166. vertexData.uvs = uvs;
  33167. return vertexData;
  33168. };
  33169. // Cylinder and cone
  33170. VertexData.CreateCylinder = function (options) {
  33171. var height = options.height || 2;
  33172. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33173. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33174. var tessellation = options.tessellation || 24;
  33175. var subdivisions = options.subdivisions || 1;
  33176. var hasRings = options.hasRings;
  33177. var enclose = options.enclose;
  33178. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33179. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33180. var faceUV = options.faceUV || new Array(3);
  33181. var faceColors = options.faceColors;
  33182. // default face colors and UV if undefined
  33183. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33184. var ringNb = (hasRings) ? subdivisions : 1;
  33185. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33186. var f;
  33187. for (f = 0; f < surfaceNb; f++) {
  33188. if (faceColors && faceColors[f] === undefined) {
  33189. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33190. }
  33191. }
  33192. for (f = 0; f < surfaceNb; f++) {
  33193. if (faceUV && faceUV[f] === undefined) {
  33194. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33195. }
  33196. }
  33197. var indices = [];
  33198. var positions = [];
  33199. var normals = [];
  33200. var uvs = [];
  33201. var colors = [];
  33202. var angle_step = Math.PI * 2 * arc / tessellation;
  33203. var angle;
  33204. var h;
  33205. var radius;
  33206. var tan = (diameterBottom - diameterTop) / 2 / height;
  33207. var ringVertex = BABYLON.Vector3.Zero();
  33208. var ringNormal = BABYLON.Vector3.Zero();
  33209. var ringFirstVertex = BABYLON.Vector3.Zero();
  33210. var ringFirstNormal = BABYLON.Vector3.Zero();
  33211. var quadNormal = BABYLON.Vector3.Zero();
  33212. var Y = BABYLON.Axis.Y;
  33213. // positions, normals, uvs
  33214. var i;
  33215. var j;
  33216. var r;
  33217. var ringIdx = 1;
  33218. var s = 1; // surface index
  33219. var cs = 0;
  33220. var v = 0;
  33221. for (i = 0; i <= subdivisions; i++) {
  33222. h = i / subdivisions;
  33223. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33224. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33225. for (r = 0; r < ringIdx; r++) {
  33226. if (hasRings) {
  33227. s += r;
  33228. }
  33229. if (enclose) {
  33230. s += 2 * r;
  33231. }
  33232. for (j = 0; j <= tessellation; j++) {
  33233. angle = j * angle_step;
  33234. // position
  33235. ringVertex.x = Math.cos(-angle) * radius;
  33236. ringVertex.y = -height / 2 + h * height;
  33237. ringVertex.z = Math.sin(-angle) * radius;
  33238. // normal
  33239. if (diameterTop === 0 && i === subdivisions) {
  33240. // if no top cap, reuse former normals
  33241. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33242. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33243. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33244. }
  33245. else {
  33246. ringNormal.x = ringVertex.x;
  33247. ringNormal.z = ringVertex.z;
  33248. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33249. ringNormal.normalize();
  33250. }
  33251. // keep first ring vertex values for enclose
  33252. if (j === 0) {
  33253. ringFirstVertex.copyFrom(ringVertex);
  33254. ringFirstNormal.copyFrom(ringNormal);
  33255. }
  33256. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33257. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33258. if (hasRings) {
  33259. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33260. }
  33261. else {
  33262. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33263. }
  33264. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33265. if (faceColors) {
  33266. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33267. }
  33268. }
  33269. // if enclose, add four vertices and their dedicated normals
  33270. if (arc !== 1 && enclose) {
  33271. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33272. positions.push(0, ringVertex.y, 0);
  33273. positions.push(0, ringVertex.y, 0);
  33274. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33275. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33276. quadNormal.normalize();
  33277. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33278. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33279. quadNormal.normalize();
  33280. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33281. if (hasRings) {
  33282. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33283. }
  33284. else {
  33285. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33286. }
  33287. uvs.push(faceUV[s + 1].x, v);
  33288. uvs.push(faceUV[s + 1].z, v);
  33289. if (hasRings) {
  33290. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33291. }
  33292. else {
  33293. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33294. }
  33295. uvs.push(faceUV[s + 2].x, v);
  33296. uvs.push(faceUV[s + 2].z, v);
  33297. if (faceColors) {
  33298. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33299. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33300. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33301. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33302. }
  33303. }
  33304. if (cs !== s) {
  33305. cs = s;
  33306. }
  33307. }
  33308. }
  33309. // indices
  33310. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33311. var s;
  33312. i = 0;
  33313. for (s = 0; s < subdivisions; s++) {
  33314. for (j = 0; j < tessellation; j++) {
  33315. var i0 = i * (e + 1) + j;
  33316. var i1 = (i + 1) * (e + 1) + j;
  33317. var i2 = i * (e + 1) + (j + 1);
  33318. var i3 = (i + 1) * (e + 1) + (j + 1);
  33319. indices.push(i0, i1, i2);
  33320. indices.push(i3, i2, i1);
  33321. }
  33322. if (arc !== 1 && enclose) {
  33323. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33324. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33325. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33326. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33327. }
  33328. i = (hasRings) ? (i + 2) : (i + 1);
  33329. }
  33330. // Caps
  33331. var createCylinderCap = function (isTop) {
  33332. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33333. if (radius === 0) {
  33334. return;
  33335. }
  33336. // Cap positions, normals & uvs
  33337. var angle;
  33338. var circleVector;
  33339. var i;
  33340. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33341. var c;
  33342. if (faceColors) {
  33343. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33344. }
  33345. // cap center
  33346. var vbase = positions.length / 3;
  33347. var offset = isTop ? height / 2 : -height / 2;
  33348. var center = new BABYLON.Vector3(0, offset, 0);
  33349. positions.push(center.x, center.y, center.z);
  33350. normals.push(0, isTop ? 1 : -1, 0);
  33351. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33352. if (faceColors) {
  33353. colors.push(c.r, c.g, c.b, c.a);
  33354. }
  33355. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33356. for (i = 0; i <= tessellation; i++) {
  33357. angle = Math.PI * 2 * i * arc / tessellation;
  33358. var cos = Math.cos(-angle);
  33359. var sin = Math.sin(-angle);
  33360. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33361. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33362. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33363. normals.push(0, isTop ? 1 : -1, 0);
  33364. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33365. if (faceColors) {
  33366. colors.push(c.r, c.g, c.b, c.a);
  33367. }
  33368. }
  33369. // Cap indices
  33370. for (i = 0; i < tessellation; i++) {
  33371. if (!isTop) {
  33372. indices.push(vbase);
  33373. indices.push(vbase + (i + 1));
  33374. indices.push(vbase + (i + 2));
  33375. }
  33376. else {
  33377. indices.push(vbase);
  33378. indices.push(vbase + (i + 2));
  33379. indices.push(vbase + (i + 1));
  33380. }
  33381. }
  33382. };
  33383. // add caps to geometry
  33384. createCylinderCap(false);
  33385. createCylinderCap(true);
  33386. // Sides
  33387. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33388. var vertexData = new VertexData();
  33389. vertexData.indices = indices;
  33390. vertexData.positions = positions;
  33391. vertexData.normals = normals;
  33392. vertexData.uvs = uvs;
  33393. if (faceColors) {
  33394. vertexData.colors = colors;
  33395. }
  33396. return vertexData;
  33397. };
  33398. VertexData.CreateTorus = function (options) {
  33399. var indices = [];
  33400. var positions = [];
  33401. var normals = [];
  33402. var uvs = [];
  33403. var diameter = options.diameter || 1;
  33404. var thickness = options.thickness || 0.5;
  33405. var tessellation = options.tessellation || 16;
  33406. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33407. var stride = tessellation + 1;
  33408. for (var i = 0; i <= tessellation; i++) {
  33409. var u = i / tessellation;
  33410. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33411. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33412. for (var j = 0; j <= tessellation; j++) {
  33413. var v = 1 - j / tessellation;
  33414. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33415. var dx = Math.cos(innerAngle);
  33416. var dy = Math.sin(innerAngle);
  33417. // Create a vertex.
  33418. var normal = new BABYLON.Vector3(dx, dy, 0);
  33419. var position = normal.scale(thickness / 2);
  33420. var textureCoordinate = new BABYLON.Vector2(u, v);
  33421. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33422. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33423. positions.push(position.x, position.y, position.z);
  33424. normals.push(normal.x, normal.y, normal.z);
  33425. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33426. // And create indices for two triangles.
  33427. var nextI = (i + 1) % stride;
  33428. var nextJ = (j + 1) % stride;
  33429. indices.push(i * stride + j);
  33430. indices.push(i * stride + nextJ);
  33431. indices.push(nextI * stride + j);
  33432. indices.push(i * stride + nextJ);
  33433. indices.push(nextI * stride + nextJ);
  33434. indices.push(nextI * stride + j);
  33435. }
  33436. }
  33437. // Sides
  33438. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33439. // Result
  33440. var vertexData = new VertexData();
  33441. vertexData.indices = indices;
  33442. vertexData.positions = positions;
  33443. vertexData.normals = normals;
  33444. vertexData.uvs = uvs;
  33445. return vertexData;
  33446. };
  33447. VertexData.CreateLineSystem = function (options) {
  33448. var indices = [];
  33449. var positions = [];
  33450. var lines = options.lines;
  33451. var idx = 0;
  33452. for (var l = 0; l < lines.length; l++) {
  33453. var points = lines[l];
  33454. for (var index = 0; index < points.length; index++) {
  33455. positions.push(points[index].x, points[index].y, points[index].z);
  33456. if (index > 0) {
  33457. indices.push(idx - 1);
  33458. indices.push(idx);
  33459. }
  33460. idx++;
  33461. }
  33462. }
  33463. var vertexData = new VertexData();
  33464. vertexData.indices = indices;
  33465. vertexData.positions = positions;
  33466. return vertexData;
  33467. };
  33468. VertexData.CreateDashedLines = function (options) {
  33469. var dashSize = options.dashSize || 3;
  33470. var gapSize = options.gapSize || 1;
  33471. var dashNb = options.dashNb || 200;
  33472. var points = options.points;
  33473. var positions = new Array();
  33474. var indices = new Array();
  33475. var curvect = BABYLON.Vector3.Zero();
  33476. var lg = 0;
  33477. var nb = 0;
  33478. var shft = 0;
  33479. var dashshft = 0;
  33480. var curshft = 0;
  33481. var idx = 0;
  33482. var i = 0;
  33483. for (i = 0; i < points.length - 1; i++) {
  33484. points[i + 1].subtractToRef(points[i], curvect);
  33485. lg += curvect.length();
  33486. }
  33487. shft = lg / dashNb;
  33488. dashshft = dashSize * shft / (dashSize + gapSize);
  33489. for (i = 0; i < points.length - 1; i++) {
  33490. points[i + 1].subtractToRef(points[i], curvect);
  33491. nb = Math.floor(curvect.length() / shft);
  33492. curvect.normalize();
  33493. for (var j = 0; j < nb; j++) {
  33494. curshft = shft * j;
  33495. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33496. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33497. indices.push(idx, idx + 1);
  33498. idx += 2;
  33499. }
  33500. }
  33501. // Result
  33502. var vertexData = new VertexData();
  33503. vertexData.positions = positions;
  33504. vertexData.indices = indices;
  33505. return vertexData;
  33506. };
  33507. VertexData.CreateGround = function (options) {
  33508. var indices = [];
  33509. var positions = [];
  33510. var normals = [];
  33511. var uvs = [];
  33512. var row, col;
  33513. var width = options.width || 1;
  33514. var height = options.height || 1;
  33515. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33516. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33517. for (row = 0; row <= subdivisionsY; row++) {
  33518. for (col = 0; col <= subdivisionsX; col++) {
  33519. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33520. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33521. positions.push(position.x, position.y, position.z);
  33522. normals.push(normal.x, normal.y, normal.z);
  33523. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsX);
  33524. }
  33525. }
  33526. for (row = 0; row < subdivisionsY; row++) {
  33527. for (col = 0; col < subdivisionsX; col++) {
  33528. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33529. indices.push(col + 1 + row * (subdivisionsX + 1));
  33530. indices.push(col + row * (subdivisionsX + 1));
  33531. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33532. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33533. indices.push(col + row * (subdivisionsX + 1));
  33534. }
  33535. }
  33536. // Result
  33537. var vertexData = new VertexData();
  33538. vertexData.indices = indices;
  33539. vertexData.positions = positions;
  33540. vertexData.normals = normals;
  33541. vertexData.uvs = uvs;
  33542. return vertexData;
  33543. };
  33544. VertexData.CreateTiledGround = function (options) {
  33545. var xmin = options.xmin || -1.0;
  33546. var zmin = options.zmin || -1.0;
  33547. var xmax = options.xmax || 1.0;
  33548. var zmax = options.zmax || 1.0;
  33549. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33550. var precision = options.precision || { w: 1, h: 1 };
  33551. var indices = [];
  33552. var positions = [];
  33553. var normals = [];
  33554. var uvs = [];
  33555. var row, col, tileRow, tileCol;
  33556. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33557. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33558. precision.w = (precision.w < 1) ? 1 : precision.w;
  33559. precision.h = (precision.h < 1) ? 1 : precision.h;
  33560. var tileSize = {
  33561. 'w': (xmax - xmin) / subdivisions.w,
  33562. 'h': (zmax - zmin) / subdivisions.h
  33563. };
  33564. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33565. // Indices
  33566. var base = positions.length / 3;
  33567. var rowLength = precision.w + 1;
  33568. for (row = 0; row < precision.h; row++) {
  33569. for (col = 0; col < precision.w; col++) {
  33570. var square = [
  33571. base + col + row * rowLength,
  33572. base + (col + 1) + row * rowLength,
  33573. base + (col + 1) + (row + 1) * rowLength,
  33574. base + col + (row + 1) * rowLength
  33575. ];
  33576. indices.push(square[1]);
  33577. indices.push(square[2]);
  33578. indices.push(square[3]);
  33579. indices.push(square[0]);
  33580. indices.push(square[1]);
  33581. indices.push(square[3]);
  33582. }
  33583. }
  33584. // Position, normals and uvs
  33585. var position = BABYLON.Vector3.Zero();
  33586. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33587. for (row = 0; row <= precision.h; row++) {
  33588. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33589. for (col = 0; col <= precision.w; col++) {
  33590. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33591. position.y = 0;
  33592. positions.push(position.x, position.y, position.z);
  33593. normals.push(normal.x, normal.y, normal.z);
  33594. uvs.push(col / precision.w, row / precision.h);
  33595. }
  33596. }
  33597. }
  33598. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33599. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33600. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33601. }
  33602. }
  33603. // Result
  33604. var vertexData = new VertexData();
  33605. vertexData.indices = indices;
  33606. vertexData.positions = positions;
  33607. vertexData.normals = normals;
  33608. vertexData.uvs = uvs;
  33609. return vertexData;
  33610. };
  33611. VertexData.CreateGroundFromHeightMap = function (options) {
  33612. var indices = [];
  33613. var positions = [];
  33614. var normals = [];
  33615. var uvs = [];
  33616. var row, col;
  33617. // Vertices
  33618. for (row = 0; row <= options.subdivisions; row++) {
  33619. for (col = 0; col <= options.subdivisions; col++) {
  33620. 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));
  33621. // Compute height
  33622. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33623. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33624. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33625. var r = options.buffer[pos] / 255.0;
  33626. var g = options.buffer[pos + 1] / 255.0;
  33627. var b = options.buffer[pos + 2] / 255.0;
  33628. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33629. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33630. // Add vertex
  33631. positions.push(position.x, position.y, position.z);
  33632. normals.push(0, 0, 0);
  33633. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33634. }
  33635. }
  33636. // Indices
  33637. for (row = 0; row < options.subdivisions; row++) {
  33638. for (col = 0; col < options.subdivisions; col++) {
  33639. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33640. indices.push(col + 1 + row * (options.subdivisions + 1));
  33641. indices.push(col + row * (options.subdivisions + 1));
  33642. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33643. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33644. indices.push(col + row * (options.subdivisions + 1));
  33645. }
  33646. }
  33647. // Normals
  33648. VertexData.ComputeNormals(positions, indices, normals);
  33649. // Result
  33650. var vertexData = new VertexData();
  33651. vertexData.indices = indices;
  33652. vertexData.positions = positions;
  33653. vertexData.normals = normals;
  33654. vertexData.uvs = uvs;
  33655. return vertexData;
  33656. };
  33657. VertexData.CreatePlane = function (options) {
  33658. var indices = [];
  33659. var positions = [];
  33660. var normals = [];
  33661. var uvs = [];
  33662. var width = options.width || options.size || 1;
  33663. var height = options.height || options.size || 1;
  33664. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33665. // Vertices
  33666. var halfWidth = width / 2.0;
  33667. var halfHeight = height / 2.0;
  33668. positions.push(-halfWidth, -halfHeight, 0);
  33669. normals.push(0, 0, -1.0);
  33670. uvs.push(0.0, 0.0);
  33671. positions.push(halfWidth, -halfHeight, 0);
  33672. normals.push(0, 0, -1.0);
  33673. uvs.push(1.0, 0.0);
  33674. positions.push(halfWidth, halfHeight, 0);
  33675. normals.push(0, 0, -1.0);
  33676. uvs.push(1.0, 1.0);
  33677. positions.push(-halfWidth, halfHeight, 0);
  33678. normals.push(0, 0, -1.0);
  33679. uvs.push(0.0, 1.0);
  33680. // Indices
  33681. indices.push(0);
  33682. indices.push(1);
  33683. indices.push(2);
  33684. indices.push(0);
  33685. indices.push(2);
  33686. indices.push(3);
  33687. // Sides
  33688. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33689. // Result
  33690. var vertexData = new VertexData();
  33691. vertexData.indices = indices;
  33692. vertexData.positions = positions;
  33693. vertexData.normals = normals;
  33694. vertexData.uvs = uvs;
  33695. return vertexData;
  33696. };
  33697. VertexData.CreateDisc = function (options) {
  33698. var positions = [];
  33699. var indices = [];
  33700. var normals = [];
  33701. var uvs = [];
  33702. var radius = options.radius || 0.5;
  33703. var tessellation = options.tessellation || 64;
  33704. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33705. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33706. // positions and uvs
  33707. positions.push(0, 0, 0); // disc center first
  33708. uvs.push(0.5, 0.5);
  33709. var theta = Math.PI * 2 * arc;
  33710. var step = theta / tessellation;
  33711. for (var a = 0; a < theta; a += step) {
  33712. var x = Math.cos(a);
  33713. var y = Math.sin(a);
  33714. var u = (x + 1) / 2;
  33715. var v = (1 - y) / 2;
  33716. positions.push(radius * x, radius * y, 0);
  33717. uvs.push(u, v);
  33718. }
  33719. if (arc === 1) {
  33720. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33721. uvs.push(uvs[2], uvs[3]);
  33722. }
  33723. //indices
  33724. var vertexNb = positions.length / 3;
  33725. for (var i = 1; i < vertexNb - 1; i++) {
  33726. indices.push(i + 1, 0, i);
  33727. }
  33728. // result
  33729. VertexData.ComputeNormals(positions, indices, normals);
  33730. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33731. var vertexData = new VertexData();
  33732. vertexData.indices = indices;
  33733. vertexData.positions = positions;
  33734. vertexData.normals = normals;
  33735. vertexData.uvs = uvs;
  33736. return vertexData;
  33737. };
  33738. VertexData.CreateIcoSphere = function (options) {
  33739. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33740. var radius = options.radius || 1;
  33741. var flat = (options.flat === undefined) ? true : options.flat;
  33742. var subdivisions = options.subdivisions || 4;
  33743. var radiusX = options.radiusX || radius;
  33744. var radiusY = options.radiusY || radius;
  33745. var radiusZ = options.radiusZ || radius;
  33746. var t = (1 + Math.sqrt(5)) / 2;
  33747. // 12 vertex x,y,z
  33748. var ico_vertices = [
  33749. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33750. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33751. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33752. ];
  33753. // index of 3 vertex makes a face of icopshere
  33754. var ico_indices = [
  33755. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33756. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33757. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33758. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33759. ];
  33760. // vertex for uv have aliased position, not for UV
  33761. var vertices_unalias_id = [
  33762. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33763. // vertex alias
  33764. 0,
  33765. 2,
  33766. 3,
  33767. 3,
  33768. 3,
  33769. 4,
  33770. 7,
  33771. 8,
  33772. 9,
  33773. 9,
  33774. 10,
  33775. 11 // 23: B + 12
  33776. ];
  33777. // uv as integer step (not pixels !)
  33778. var ico_vertexuv = [
  33779. 5, 1, 3, 1, 6, 4, 0, 0,
  33780. 5, 3, 4, 2, 2, 2, 4, 0,
  33781. 2, 0, 1, 1, 6, 0, 6, 2,
  33782. // vertex alias (for same vertex on different faces)
  33783. 0, 4,
  33784. 3, 3,
  33785. 4, 4,
  33786. 3, 1,
  33787. 4, 2,
  33788. 4, 4,
  33789. 0, 2,
  33790. 1, 1,
  33791. 2, 2,
  33792. 3, 3,
  33793. 1, 3,
  33794. 2, 4 // 23: B + 12
  33795. ];
  33796. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33797. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33798. // First island of uv mapping
  33799. // v = 4h 3+ 2
  33800. // v = 3h 9+ 4
  33801. // v = 2h 9+ 5 B
  33802. // v = 1h 9 1 0
  33803. // v = 0h 3 8 7 A
  33804. // u = 0 1 2 3 4 5 6 *a
  33805. // Second island of uv mapping
  33806. // v = 4h 0+ B+ 4+
  33807. // v = 3h A+ 2+
  33808. // v = 2h 7+ 6 3+
  33809. // v = 1h 8+ 3+
  33810. // v = 0h
  33811. // u = 0 1 2 3 4 5 6 *a
  33812. // Face layout on texture UV mapping
  33813. // ============
  33814. // \ 4 /\ 16 / ======
  33815. // \ / \ / /\ 11 /
  33816. // \/ 7 \/ / \ /
  33817. // ======= / 10 \/
  33818. // /\ 17 /\ =======
  33819. // / \ / \ \ 15 /\
  33820. // / 8 \/ 12 \ \ / \
  33821. // ============ \/ 6 \
  33822. // \ 18 /\ ============
  33823. // \ / \ \ 5 /\ 0 /
  33824. // \/ 13 \ \ / \ /
  33825. // ======= \/ 1 \/
  33826. // =============
  33827. // /\ 19 /\ 2 /\
  33828. // / \ / \ / \
  33829. // / 14 \/ 9 \/ 3 \
  33830. // ===================
  33831. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33832. var ustep = 138 / 1024;
  33833. var vstep = 239 / 1024;
  33834. var uoffset = 60 / 1024;
  33835. var voffset = 26 / 1024;
  33836. // Second island should have margin, not to touch the first island
  33837. // avoid any borderline artefact in pixel rounding
  33838. var island_u_offset = -40 / 1024;
  33839. var island_v_offset = +20 / 1024;
  33840. // face is either island 0 or 1 :
  33841. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33842. var island = [
  33843. 0, 0, 0, 0, 1,
  33844. 0, 0, 1, 1, 0,
  33845. 0, 0, 1, 1, 0,
  33846. 0, 1, 1, 1, 0 // 15 - 19
  33847. ];
  33848. var indices = [];
  33849. var positions = [];
  33850. var normals = [];
  33851. var uvs = [];
  33852. var current_indice = 0;
  33853. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33854. var face_vertex_pos = new Array(3);
  33855. var face_vertex_uv = new Array(3);
  33856. var v012;
  33857. for (v012 = 0; v012 < 3; v012++) {
  33858. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33859. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33860. }
  33861. // create all with normals
  33862. for (var face = 0; face < 20; face++) {
  33863. // 3 vertex per face
  33864. for (v012 = 0; v012 < 3; v012++) {
  33865. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33866. var v_id = ico_indices[3 * face + v012];
  33867. // vertex have 3D position (x,y,z)
  33868. 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]);
  33869. // Normalize to get normal, then scale to radius
  33870. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33871. // uv Coordinates from vertex ID
  33872. 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);
  33873. }
  33874. // Subdivide the face (interpolate pos, norm, uv)
  33875. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33876. // - norm is linear interpolation of vertex corner normal
  33877. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33878. // - uv is linear interpolation
  33879. //
  33880. // Topology is as below for sub-divide by 2
  33881. // vertex shown as v0,v1,v2
  33882. // interp index is i1 to progress in range [v0,v1[
  33883. // interp index is i2 to progress in range [v0,v2[
  33884. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33885. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33886. //
  33887. //
  33888. // i2 v2
  33889. // ^ ^
  33890. // / / \
  33891. // / / \
  33892. // / / \
  33893. // / / (0,1) \
  33894. // / #---------\
  33895. // / / \ (0,0)'/ \
  33896. // / / \ / \
  33897. // / / \ / \
  33898. // / / (0,0) \ / (1,0) \
  33899. // / #---------#---------\
  33900. // v0 v1
  33901. //
  33902. // --------------------> i1
  33903. //
  33904. // interp of (i1,i2):
  33905. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33906. // along i1 : lerp(x0,x1, i1/(S-i2))
  33907. //
  33908. // centroid of triangle is needed to get help normal computation
  33909. // (c1,c2) are used for centroid location
  33910. var interp_vertex = function (i1, i2, c1, c2) {
  33911. // vertex is interpolated from
  33912. // - face_vertex_pos[0..2]
  33913. // - face_vertex_uv[0..2]
  33914. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33915. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33916. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33917. pos_interp.normalize();
  33918. var vertex_normal;
  33919. if (flat) {
  33920. // in flat mode, recalculate normal as face centroid normal
  33921. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33922. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33923. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33924. }
  33925. else {
  33926. // in smooth mode, recalculate normal from each single vertex position
  33927. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33928. }
  33929. // Vertex normal need correction due to X,Y,Z radius scaling
  33930. vertex_normal.x /= radiusX;
  33931. vertex_normal.y /= radiusY;
  33932. vertex_normal.z /= radiusZ;
  33933. vertex_normal.normalize();
  33934. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33935. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33936. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33937. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33938. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33939. uvs.push(uv_interp.x, uv_interp.y);
  33940. // push each vertex has member of a face
  33941. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33942. indices.push(current_indice);
  33943. current_indice++;
  33944. };
  33945. for (var i2 = 0; i2 < subdivisions; i2++) {
  33946. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33947. // face : (i1,i2) for /\ :
  33948. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33949. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33950. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33951. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33952. if (i1 + i2 + 1 < subdivisions) {
  33953. // face : (i1,i2)' for \/ :
  33954. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33955. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33956. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33957. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33958. }
  33959. }
  33960. }
  33961. }
  33962. // Sides
  33963. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33964. // Result
  33965. var vertexData = new VertexData();
  33966. vertexData.indices = indices;
  33967. vertexData.positions = positions;
  33968. vertexData.normals = normals;
  33969. vertexData.uvs = uvs;
  33970. return vertexData;
  33971. };
  33972. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33973. VertexData.CreatePolyhedron = function (options) {
  33974. // provided polyhedron types :
  33975. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33976. // 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)
  33977. var polyhedra = [];
  33978. 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]] };
  33979. 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]] };
  33980. polyhedra[2] = {
  33981. 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]],
  33982. 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]]
  33983. };
  33984. polyhedra[3] = {
  33985. 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]],
  33986. 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]]
  33987. };
  33988. polyhedra[4] = {
  33989. 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]],
  33990. 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]]
  33991. };
  33992. 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]] };
  33993. 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]] };
  33994. 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]] };
  33995. 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]] };
  33996. 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]] };
  33997. 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]] };
  33998. 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]] };
  33999. 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]] };
  34000. 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]] };
  34001. polyhedra[14] = {
  34002. 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]],
  34003. 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]]
  34004. };
  34005. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34006. var size = options.size;
  34007. var sizeX = options.sizeX || size || 1;
  34008. var sizeY = options.sizeY || size || 1;
  34009. var sizeZ = options.sizeZ || size || 1;
  34010. var data = options.custom || polyhedra[type];
  34011. var nbfaces = data.face.length;
  34012. var faceUV = options.faceUV || new Array(nbfaces);
  34013. var faceColors = options.faceColors;
  34014. var flat = (options.flat === undefined) ? true : options.flat;
  34015. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34016. var positions = [];
  34017. var indices = [];
  34018. var normals = [];
  34019. var uvs = [];
  34020. var colors = [];
  34021. var index = 0;
  34022. var faceIdx = 0; // face cursor in the array "indexes"
  34023. var indexes = [];
  34024. var i = 0;
  34025. var f = 0;
  34026. var u, v, ang, x, y, tmp;
  34027. // default face colors and UV if undefined
  34028. if (flat) {
  34029. for (f = 0; f < nbfaces; f++) {
  34030. if (faceColors && faceColors[f] === undefined) {
  34031. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34032. }
  34033. if (faceUV && faceUV[f] === undefined) {
  34034. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34035. }
  34036. }
  34037. }
  34038. if (!flat) {
  34039. for (i = 0; i < data.vertex.length; i++) {
  34040. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34041. uvs.push(0, 0);
  34042. }
  34043. for (f = 0; f < nbfaces; f++) {
  34044. for (i = 0; i < data.face[f].length - 2; i++) {
  34045. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34046. }
  34047. }
  34048. }
  34049. else {
  34050. for (f = 0; f < nbfaces; f++) {
  34051. var fl = data.face[f].length; // number of vertices of the current face
  34052. ang = 2 * Math.PI / fl;
  34053. x = 0.5 * Math.tan(ang / 2);
  34054. y = 0.5;
  34055. // positions, uvs, colors
  34056. for (i = 0; i < fl; i++) {
  34057. // positions
  34058. 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);
  34059. indexes.push(index);
  34060. index++;
  34061. // uvs
  34062. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34063. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34064. uvs.push(u, v);
  34065. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34066. y = x * Math.sin(ang) + y * Math.cos(ang);
  34067. x = tmp;
  34068. // colors
  34069. if (faceColors) {
  34070. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34071. }
  34072. }
  34073. // indices from indexes
  34074. for (i = 0; i < fl - 2; i++) {
  34075. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34076. }
  34077. faceIdx += fl;
  34078. }
  34079. }
  34080. VertexData.ComputeNormals(positions, indices, normals);
  34081. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34082. var vertexData = new VertexData();
  34083. vertexData.positions = positions;
  34084. vertexData.indices = indices;
  34085. vertexData.normals = normals;
  34086. vertexData.uvs = uvs;
  34087. if (faceColors && flat) {
  34088. vertexData.colors = colors;
  34089. }
  34090. return vertexData;
  34091. };
  34092. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34093. VertexData.CreateTorusKnot = function (options) {
  34094. var indices = [];
  34095. var positions = [];
  34096. var normals = [];
  34097. var uvs = [];
  34098. var radius = options.radius || 2;
  34099. var tube = options.tube || 0.5;
  34100. var radialSegments = options.radialSegments || 32;
  34101. var tubularSegments = options.tubularSegments || 32;
  34102. var p = options.p || 2;
  34103. var q = options.q || 3;
  34104. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34105. // Helper
  34106. var getPos = function (angle) {
  34107. var cu = Math.cos(angle);
  34108. var su = Math.sin(angle);
  34109. var quOverP = q / p * angle;
  34110. var cs = Math.cos(quOverP);
  34111. var tx = radius * (2 + cs) * 0.5 * cu;
  34112. var ty = radius * (2 + cs) * su * 0.5;
  34113. var tz = radius * Math.sin(quOverP) * 0.5;
  34114. return new BABYLON.Vector3(tx, ty, tz);
  34115. };
  34116. // Vertices
  34117. var i;
  34118. var j;
  34119. for (i = 0; i <= radialSegments; i++) {
  34120. var modI = i % radialSegments;
  34121. var u = modI / radialSegments * 2 * p * Math.PI;
  34122. var p1 = getPos(u);
  34123. var p2 = getPos(u + 0.01);
  34124. var tang = p2.subtract(p1);
  34125. var n = p2.add(p1);
  34126. var bitan = BABYLON.Vector3.Cross(tang, n);
  34127. n = BABYLON.Vector3.Cross(bitan, tang);
  34128. bitan.normalize();
  34129. n.normalize();
  34130. for (j = 0; j < tubularSegments; j++) {
  34131. var modJ = j % tubularSegments;
  34132. var v = modJ / tubularSegments * 2 * Math.PI;
  34133. var cx = -tube * Math.cos(v);
  34134. var cy = tube * Math.sin(v);
  34135. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34136. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34137. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34138. uvs.push(i / radialSegments);
  34139. uvs.push(j / tubularSegments);
  34140. }
  34141. }
  34142. for (i = 0; i < radialSegments; i++) {
  34143. for (j = 0; j < tubularSegments; j++) {
  34144. var jNext = (j + 1) % tubularSegments;
  34145. var a = i * tubularSegments + j;
  34146. var b = (i + 1) * tubularSegments + j;
  34147. var c = (i + 1) * tubularSegments + jNext;
  34148. var d = i * tubularSegments + jNext;
  34149. indices.push(d);
  34150. indices.push(b);
  34151. indices.push(a);
  34152. indices.push(d);
  34153. indices.push(c);
  34154. indices.push(b);
  34155. }
  34156. }
  34157. // Normals
  34158. VertexData.ComputeNormals(positions, indices, normals);
  34159. // Sides
  34160. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34161. // Result
  34162. var vertexData = new VertexData();
  34163. vertexData.indices = indices;
  34164. vertexData.positions = positions;
  34165. vertexData.normals = normals;
  34166. vertexData.uvs = uvs;
  34167. return vertexData;
  34168. };
  34169. // Tools
  34170. /**
  34171. * @param {any} - positions (number[] or Float32Array)
  34172. * @param {any} - indices (number[] or Uint16Array)
  34173. * @param {any} - normals (number[] or Float32Array)
  34174. */
  34175. VertexData.ComputeNormals = function (positions, indices, normals) {
  34176. var index = 0;
  34177. var p1p2x = 0.0;
  34178. var p1p2y = 0.0;
  34179. var p1p2z = 0.0;
  34180. var p3p2x = 0.0;
  34181. var p3p2y = 0.0;
  34182. var p3p2z = 0.0;
  34183. var faceNormalx = 0.0;
  34184. var faceNormaly = 0.0;
  34185. var faceNormalz = 0.0;
  34186. var length = 0.0;
  34187. var i1 = 0;
  34188. var i2 = 0;
  34189. var i3 = 0;
  34190. for (index = 0; index < positions.length; index++) {
  34191. normals[index] = 0.0;
  34192. }
  34193. // indice triplet = 1 face
  34194. var nbFaces = indices.length / 3;
  34195. for (index = 0; index < nbFaces; index++) {
  34196. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  34197. i2 = indices[index * 3 + 1];
  34198. i3 = indices[index * 3 + 2];
  34199. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  34200. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  34201. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  34202. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  34203. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  34204. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  34205. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  34206. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  34207. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  34208. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34209. length = (length === 0) ? 1.0 : length;
  34210. faceNormalx /= length; // normalize this normal
  34211. faceNormaly /= length;
  34212. faceNormalz /= length;
  34213. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  34214. normals[i1 * 3 + 1] += faceNormaly;
  34215. normals[i1 * 3 + 2] += faceNormalz;
  34216. normals[i2 * 3] += faceNormalx;
  34217. normals[i2 * 3 + 1] += faceNormaly;
  34218. normals[i2 * 3 + 2] += faceNormalz;
  34219. normals[i3 * 3] += faceNormalx;
  34220. normals[i3 * 3 + 1] += faceNormaly;
  34221. normals[i3 * 3 + 2] += faceNormalz;
  34222. }
  34223. // last normalization of each normal
  34224. for (index = 0; index < normals.length / 3; index++) {
  34225. faceNormalx = normals[index * 3];
  34226. faceNormaly = normals[index * 3 + 1];
  34227. faceNormalz = normals[index * 3 + 2];
  34228. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34229. length = (length === 0) ? 1.0 : length;
  34230. faceNormalx /= length;
  34231. faceNormaly /= length;
  34232. faceNormalz /= length;
  34233. normals[index * 3] = faceNormalx;
  34234. normals[index * 3 + 1] = faceNormaly;
  34235. normals[index * 3 + 2] = faceNormalz;
  34236. }
  34237. };
  34238. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  34239. var li = indices.length;
  34240. var ln = normals.length;
  34241. var i;
  34242. var n;
  34243. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34244. switch (sideOrientation) {
  34245. case BABYLON.Mesh.FRONTSIDE:
  34246. // nothing changed
  34247. break;
  34248. case BABYLON.Mesh.BACKSIDE:
  34249. var tmp;
  34250. // indices
  34251. for (i = 0; i < li; i += 3) {
  34252. tmp = indices[i];
  34253. indices[i] = indices[i + 2];
  34254. indices[i + 2] = tmp;
  34255. }
  34256. // normals
  34257. for (n = 0; n < ln; n++) {
  34258. normals[n] = -normals[n];
  34259. }
  34260. break;
  34261. case BABYLON.Mesh.DOUBLESIDE:
  34262. // positions
  34263. var lp = positions.length;
  34264. var l = lp / 3;
  34265. for (var p = 0; p < lp; p++) {
  34266. positions[lp + p] = positions[p];
  34267. }
  34268. // indices
  34269. for (i = 0; i < li; i += 3) {
  34270. indices[i + li] = indices[i + 2] + l;
  34271. indices[i + 1 + li] = indices[i + 1] + l;
  34272. indices[i + 2 + li] = indices[i] + l;
  34273. }
  34274. // normals
  34275. for (n = 0; n < ln; n++) {
  34276. normals[ln + n] = -normals[n];
  34277. }
  34278. // uvs
  34279. var lu = uvs.length;
  34280. for (var u = 0; u < lu; u++) {
  34281. uvs[u + lu] = uvs[u];
  34282. }
  34283. break;
  34284. }
  34285. };
  34286. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34287. var vertexData = new VertexData();
  34288. // positions
  34289. var positions = parsedVertexData.positions;
  34290. if (positions) {
  34291. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34292. }
  34293. // normals
  34294. var normals = parsedVertexData.normals;
  34295. if (normals) {
  34296. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34297. }
  34298. // uvs
  34299. var uvs = parsedVertexData.uvs;
  34300. if (uvs) {
  34301. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34302. }
  34303. // uv2s
  34304. var uv2s = parsedVertexData.uv2s;
  34305. if (uv2s) {
  34306. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34307. }
  34308. // uv3s
  34309. var uv3s = parsedVertexData.uv3s;
  34310. if (uv3s) {
  34311. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34312. }
  34313. // uv4s
  34314. var uv4s = parsedVertexData.uv4s;
  34315. if (uv4s) {
  34316. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34317. }
  34318. // uv5s
  34319. var uv5s = parsedVertexData.uv5s;
  34320. if (uv5s) {
  34321. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34322. }
  34323. // uv6s
  34324. var uv6s = parsedVertexData.uv6s;
  34325. if (uv6s) {
  34326. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34327. }
  34328. // colors
  34329. var colors = parsedVertexData.colors;
  34330. if (colors) {
  34331. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34332. }
  34333. // matricesIndices
  34334. var matricesIndices = parsedVertexData.matricesIndices;
  34335. if (matricesIndices) {
  34336. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34337. }
  34338. // matricesWeights
  34339. var matricesWeights = parsedVertexData.matricesWeights;
  34340. if (matricesWeights) {
  34341. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34342. }
  34343. // indices
  34344. var indices = parsedVertexData.indices;
  34345. if (indices) {
  34346. vertexData.indices = indices;
  34347. }
  34348. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34349. };
  34350. return VertexData;
  34351. }());
  34352. BABYLON.VertexData = VertexData;
  34353. })(BABYLON || (BABYLON = {}));
  34354. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34355. var BABYLON;
  34356. (function (BABYLON) {
  34357. var Tags = (function () {
  34358. function Tags() {
  34359. }
  34360. Tags.EnableFor = function (obj) {
  34361. obj._tags = obj._tags || {};
  34362. obj.hasTags = function () {
  34363. return Tags.HasTags(obj);
  34364. };
  34365. obj.addTags = function (tagsString) {
  34366. return Tags.AddTagsTo(obj, tagsString);
  34367. };
  34368. obj.removeTags = function (tagsString) {
  34369. return Tags.RemoveTagsFrom(obj, tagsString);
  34370. };
  34371. obj.matchesTagsQuery = function (tagsQuery) {
  34372. return Tags.MatchesQuery(obj, tagsQuery);
  34373. };
  34374. };
  34375. Tags.DisableFor = function (obj) {
  34376. delete obj._tags;
  34377. delete obj.hasTags;
  34378. delete obj.addTags;
  34379. delete obj.removeTags;
  34380. delete obj.matchesTagsQuery;
  34381. };
  34382. Tags.HasTags = function (obj) {
  34383. if (!obj._tags) {
  34384. return false;
  34385. }
  34386. return !BABYLON.Tools.IsEmpty(obj._tags);
  34387. };
  34388. Tags.GetTags = function (obj, asString) {
  34389. if (asString === void 0) { asString = true; }
  34390. if (!obj._tags) {
  34391. return null;
  34392. }
  34393. if (asString) {
  34394. var tagsArray = [];
  34395. for (var tag in obj._tags) {
  34396. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  34397. tagsArray.push(tag);
  34398. }
  34399. }
  34400. return tagsArray.join(" ");
  34401. }
  34402. else {
  34403. return obj._tags;
  34404. }
  34405. };
  34406. // the tags 'true' and 'false' are reserved and cannot be used as tags
  34407. // a tag cannot start with '||', '&&', and '!'
  34408. // it cannot contain whitespaces
  34409. Tags.AddTagsTo = function (obj, tagsString) {
  34410. if (!tagsString) {
  34411. return;
  34412. }
  34413. if (typeof tagsString !== "string") {
  34414. return;
  34415. }
  34416. var tags = tagsString.split(" ");
  34417. tags.forEach(function (tag, index, array) {
  34418. Tags._AddTagTo(obj, tag);
  34419. });
  34420. };
  34421. Tags._AddTagTo = function (obj, tag) {
  34422. tag = tag.trim();
  34423. if (tag === "" || tag === "true" || tag === "false") {
  34424. return;
  34425. }
  34426. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  34427. return;
  34428. }
  34429. Tags.EnableFor(obj);
  34430. obj._tags[tag] = true;
  34431. };
  34432. Tags.RemoveTagsFrom = function (obj, tagsString) {
  34433. if (!Tags.HasTags(obj)) {
  34434. return;
  34435. }
  34436. var tags = tagsString.split(" ");
  34437. for (var t in tags) {
  34438. Tags._RemoveTagFrom(obj, tags[t]);
  34439. }
  34440. };
  34441. Tags._RemoveTagFrom = function (obj, tag) {
  34442. delete obj._tags[tag];
  34443. };
  34444. Tags.MatchesQuery = function (obj, tagsQuery) {
  34445. if (tagsQuery === undefined) {
  34446. return true;
  34447. }
  34448. if (tagsQuery === "") {
  34449. return Tags.HasTags(obj);
  34450. }
  34451. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  34452. };
  34453. return Tags;
  34454. }());
  34455. BABYLON.Tags = Tags;
  34456. })(BABYLON || (BABYLON = {}));
  34457. //# sourceMappingURL=babylon.tags.js.map
  34458. var BABYLON;
  34459. (function (BABYLON) {
  34460. var Internals;
  34461. (function (Internals) {
  34462. var AndOrNotEvaluator = (function () {
  34463. function AndOrNotEvaluator() {
  34464. }
  34465. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  34466. if (!query.match(/\([^\(\)]*\)/g)) {
  34467. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  34468. }
  34469. else {
  34470. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  34471. // remove parenthesis
  34472. r = r.slice(1, r.length - 1);
  34473. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  34474. });
  34475. }
  34476. if (query === "true") {
  34477. return true;
  34478. }
  34479. if (query === "false") {
  34480. return false;
  34481. }
  34482. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  34483. };
  34484. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  34485. evaluateCallback = evaluateCallback || (function (r) {
  34486. return r === "true" ? true : false;
  34487. });
  34488. var result;
  34489. var or = parenthesisContent.split("||");
  34490. for (var i in or) {
  34491. if (or.hasOwnProperty(i)) {
  34492. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  34493. var and = ori.split("&&");
  34494. if (and.length > 1) {
  34495. for (var j = 0; j < and.length; ++j) {
  34496. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  34497. if (andj !== "true" && andj !== "false") {
  34498. if (andj[0] === "!") {
  34499. result = !evaluateCallback(andj.substring(1));
  34500. }
  34501. else {
  34502. result = evaluateCallback(andj);
  34503. }
  34504. }
  34505. else {
  34506. result = andj === "true" ? true : false;
  34507. }
  34508. if (!result) {
  34509. ori = "false";
  34510. break;
  34511. }
  34512. }
  34513. }
  34514. if (result || ori === "true") {
  34515. result = true;
  34516. break;
  34517. }
  34518. // result equals false (or undefined)
  34519. if (ori !== "true" && ori !== "false") {
  34520. if (ori[0] === "!") {
  34521. result = !evaluateCallback(ori.substring(1));
  34522. }
  34523. else {
  34524. result = evaluateCallback(ori);
  34525. }
  34526. }
  34527. else {
  34528. result = ori === "true" ? true : false;
  34529. }
  34530. }
  34531. }
  34532. // the whole parenthesis scope is replaced by 'true' or 'false'
  34533. return result ? "true" : "false";
  34534. };
  34535. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  34536. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  34537. // remove whitespaces
  34538. r = r.replace(/[\s]/g, function () { return ""; });
  34539. return r.length % 2 ? "!" : "";
  34540. });
  34541. booleanString = booleanString.trim();
  34542. if (booleanString === "!true") {
  34543. booleanString = "false";
  34544. }
  34545. else if (booleanString === "!false") {
  34546. booleanString = "true";
  34547. }
  34548. return booleanString;
  34549. };
  34550. return AndOrNotEvaluator;
  34551. }());
  34552. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  34553. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34554. })(BABYLON || (BABYLON = {}));
  34555. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  34556. var BABYLON;
  34557. (function (BABYLON) {
  34558. var PostProcessRenderPass = (function () {
  34559. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  34560. this._enabled = true;
  34561. this._refCount = 0;
  34562. this._name = name;
  34563. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  34564. this.setRenderList(renderList);
  34565. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  34566. this._renderTexture.onAfterRenderObservable.add(afterRender);
  34567. this._scene = scene;
  34568. this._renderList = renderList;
  34569. }
  34570. // private
  34571. PostProcessRenderPass.prototype._incRefCount = function () {
  34572. if (this._refCount === 0) {
  34573. this._scene.customRenderTargets.push(this._renderTexture);
  34574. }
  34575. return ++this._refCount;
  34576. };
  34577. PostProcessRenderPass.prototype._decRefCount = function () {
  34578. this._refCount--;
  34579. if (this._refCount <= 0) {
  34580. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  34581. }
  34582. return this._refCount;
  34583. };
  34584. PostProcessRenderPass.prototype._update = function () {
  34585. this.setRenderList(this._renderList);
  34586. };
  34587. // public
  34588. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  34589. this._renderTexture.renderList = renderList;
  34590. };
  34591. PostProcessRenderPass.prototype.getRenderTexture = function () {
  34592. return this._renderTexture;
  34593. };
  34594. return PostProcessRenderPass;
  34595. }());
  34596. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  34597. })(BABYLON || (BABYLON = {}));
  34598. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  34599. var BABYLON;
  34600. (function (BABYLON) {
  34601. var PostProcessRenderEffect = (function () {
  34602. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  34603. this._engine = engine;
  34604. this._name = name;
  34605. this._singleInstance = singleInstance || true;
  34606. this._getPostProcess = getPostProcess;
  34607. this._cameras = [];
  34608. this._indicesForCamera = [];
  34609. this._postProcesses = {};
  34610. this._renderPasses = {};
  34611. this._renderEffectAsPasses = {};
  34612. }
  34613. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  34614. get: function () {
  34615. for (var index in this._postProcesses) {
  34616. if (!this._postProcesses[index].isSupported) {
  34617. return false;
  34618. }
  34619. }
  34620. return true;
  34621. },
  34622. enumerable: true,
  34623. configurable: true
  34624. });
  34625. PostProcessRenderEffect.prototype._update = function () {
  34626. for (var renderPassName in this._renderPasses) {
  34627. this._renderPasses[renderPassName]._update();
  34628. }
  34629. };
  34630. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  34631. this._renderPasses[renderPass._name] = renderPass;
  34632. this._linkParameters();
  34633. };
  34634. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  34635. delete this._renderPasses[renderPass._name];
  34636. this._linkParameters();
  34637. };
  34638. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  34639. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  34640. this._linkParameters();
  34641. };
  34642. PostProcessRenderEffect.prototype.getPass = function (passName) {
  34643. for (var renderPassName in this._renderPasses) {
  34644. if (renderPassName === passName) {
  34645. return this._renderPasses[passName];
  34646. }
  34647. }
  34648. };
  34649. PostProcessRenderEffect.prototype.emptyPasses = function () {
  34650. this._renderPasses = {};
  34651. this._linkParameters();
  34652. };
  34653. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  34654. var cameraKey;
  34655. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34656. for (var i = 0; i < _cam.length; i++) {
  34657. var camera = _cam[i];
  34658. var cameraName = camera.name;
  34659. if (this._singleInstance) {
  34660. cameraKey = 0;
  34661. }
  34662. else {
  34663. cameraKey = cameraName;
  34664. }
  34665. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  34666. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  34667. if (!this._indicesForCamera[cameraName]) {
  34668. this._indicesForCamera[cameraName] = [];
  34669. }
  34670. this._indicesForCamera[cameraName].push(index);
  34671. if (this._cameras.indexOf(camera) === -1) {
  34672. this._cameras[cameraName] = camera;
  34673. }
  34674. for (var passName in this._renderPasses) {
  34675. this._renderPasses[passName]._incRefCount();
  34676. }
  34677. }
  34678. this._linkParameters();
  34679. };
  34680. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  34681. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34682. for (var i = 0; i < _cam.length; i++) {
  34683. var camera = _cam[i];
  34684. var cameraName = camera.name;
  34685. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  34686. var index = this._cameras.indexOf(cameraName);
  34687. this._indicesForCamera.splice(index, 1);
  34688. this._cameras.splice(index, 1);
  34689. for (var passName in this._renderPasses) {
  34690. this._renderPasses[passName]._decRefCount();
  34691. }
  34692. }
  34693. };
  34694. PostProcessRenderEffect.prototype._enable = function (cameras) {
  34695. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34696. for (var i = 0; i < _cam.length; i++) {
  34697. var camera = _cam[i];
  34698. var cameraName = camera.name;
  34699. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  34700. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  34701. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  34702. }
  34703. }
  34704. for (var passName in this._renderPasses) {
  34705. this._renderPasses[passName]._incRefCount();
  34706. }
  34707. }
  34708. };
  34709. PostProcessRenderEffect.prototype._disable = function (cameras) {
  34710. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34711. for (var i = 0; i < _cam.length; i++) {
  34712. var camera = _cam[i];
  34713. var cameraName = camera.Name;
  34714. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  34715. for (var passName in this._renderPasses) {
  34716. this._renderPasses[passName]._decRefCount();
  34717. }
  34718. }
  34719. };
  34720. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  34721. if (this._singleInstance) {
  34722. return this._postProcesses[0];
  34723. }
  34724. else {
  34725. return this._postProcesses[camera.name];
  34726. }
  34727. };
  34728. PostProcessRenderEffect.prototype._linkParameters = function () {
  34729. var _this = this;
  34730. for (var index in this._postProcesses) {
  34731. if (this.applyParameters) {
  34732. this.applyParameters(this._postProcesses[index]);
  34733. }
  34734. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  34735. _this._linkTextures(effect);
  34736. });
  34737. }
  34738. };
  34739. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  34740. for (var renderPassName in this._renderPasses) {
  34741. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  34742. }
  34743. for (var renderEffectName in this._renderEffectAsPasses) {
  34744. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  34745. }
  34746. };
  34747. return PostProcessRenderEffect;
  34748. }());
  34749. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  34750. })(BABYLON || (BABYLON = {}));
  34751. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  34752. var BABYLON;
  34753. (function (BABYLON) {
  34754. var PostProcessRenderPipeline = (function () {
  34755. function PostProcessRenderPipeline(engine, name) {
  34756. this._engine = engine;
  34757. this._name = name;
  34758. this._renderEffects = {};
  34759. this._renderEffectsForIsolatedPass = {};
  34760. this._cameras = [];
  34761. }
  34762. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  34763. get: function () {
  34764. for (var renderEffectName in this._renderEffects) {
  34765. if (!this._renderEffects[renderEffectName].isSupported) {
  34766. return false;
  34767. }
  34768. }
  34769. return true;
  34770. },
  34771. enumerable: true,
  34772. configurable: true
  34773. });
  34774. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  34775. this._renderEffects[renderEffect._name] = renderEffect;
  34776. };
  34777. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  34778. var renderEffects = this._renderEffects[renderEffectName];
  34779. if (!renderEffects) {
  34780. return;
  34781. }
  34782. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  34783. };
  34784. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  34785. var renderEffects = this._renderEffects[renderEffectName];
  34786. if (!renderEffects) {
  34787. return;
  34788. }
  34789. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  34790. };
  34791. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  34792. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34793. var indicesToDelete = [];
  34794. var i;
  34795. for (i = 0; i < _cam.length; i++) {
  34796. var camera = _cam[i];
  34797. var cameraName = camera.name;
  34798. if (this._cameras.indexOf(camera) === -1) {
  34799. this._cameras[cameraName] = camera;
  34800. }
  34801. else if (unique) {
  34802. indicesToDelete.push(i);
  34803. }
  34804. }
  34805. for (i = 0; i < indicesToDelete.length; i++) {
  34806. cameras.splice(indicesToDelete[i], 1);
  34807. }
  34808. for (var renderEffectName in this._renderEffects) {
  34809. this._renderEffects[renderEffectName]._attachCameras(_cam);
  34810. }
  34811. };
  34812. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  34813. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34814. for (var renderEffectName in this._renderEffects) {
  34815. this._renderEffects[renderEffectName]._detachCameras(_cam);
  34816. }
  34817. for (var i = 0; i < _cam.length; i++) {
  34818. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  34819. }
  34820. };
  34821. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  34822. var _this = this;
  34823. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34824. var pass = null;
  34825. var renderEffectName;
  34826. for (renderEffectName in this._renderEffects) {
  34827. pass = this._renderEffects[renderEffectName].getPass(passName);
  34828. if (pass != null) {
  34829. break;
  34830. }
  34831. }
  34832. if (pass === null) {
  34833. return;
  34834. }
  34835. for (renderEffectName in this._renderEffects) {
  34836. this._renderEffects[renderEffectName]._disable(_cam);
  34837. }
  34838. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  34839. for (var i = 0; i < _cam.length; i++) {
  34840. var camera = _cam[i];
  34841. var cameraName = camera.name;
  34842. 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); });
  34843. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  34844. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  34845. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  34846. }
  34847. };
  34848. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  34849. var _this = this;
  34850. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34851. for (var i = 0; i < _cam.length; i++) {
  34852. var camera = _cam[i];
  34853. var cameraName = camera.name;
  34854. 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); });
  34855. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  34856. }
  34857. for (var renderEffectName in this._renderEffects) {
  34858. this._renderEffects[renderEffectName]._enable(_cam);
  34859. }
  34860. };
  34861. PostProcessRenderPipeline.prototype._update = function () {
  34862. for (var renderEffectName in this._renderEffects) {
  34863. this._renderEffects[renderEffectName]._update();
  34864. }
  34865. for (var i = 0; i < this._cameras.length; i++) {
  34866. var cameraName = this._cameras[i].name;
  34867. if (this._renderEffectsForIsolatedPass[cameraName]) {
  34868. this._renderEffectsForIsolatedPass[cameraName]._update();
  34869. }
  34870. }
  34871. };
  34872. PostProcessRenderPipeline.prototype.dispose = function () {
  34873. // Must be implemented by children
  34874. };
  34875. return PostProcessRenderPipeline;
  34876. }());
  34877. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  34878. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  34879. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  34880. })(BABYLON || (BABYLON = {}));
  34881. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  34882. var BABYLON;
  34883. (function (BABYLON) {
  34884. var PostProcessRenderPipelineManager = (function () {
  34885. function PostProcessRenderPipelineManager() {
  34886. this._renderPipelines = {};
  34887. }
  34888. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  34889. this._renderPipelines[renderPipeline._name] = renderPipeline;
  34890. };
  34891. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  34892. var renderPipeline = this._renderPipelines[renderPipelineName];
  34893. if (!renderPipeline) {
  34894. return;
  34895. }
  34896. renderPipeline._attachCameras(cameras, unique);
  34897. };
  34898. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  34899. var renderPipeline = this._renderPipelines[renderPipelineName];
  34900. if (!renderPipeline) {
  34901. return;
  34902. }
  34903. renderPipeline._detachCameras(cameras);
  34904. };
  34905. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  34906. var renderPipeline = this._renderPipelines[renderPipelineName];
  34907. if (!renderPipeline) {
  34908. return;
  34909. }
  34910. renderPipeline._enableEffect(renderEffectName, cameras);
  34911. };
  34912. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  34913. var renderPipeline = this._renderPipelines[renderPipelineName];
  34914. if (!renderPipeline) {
  34915. return;
  34916. }
  34917. renderPipeline._disableEffect(renderEffectName, cameras);
  34918. };
  34919. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  34920. var renderPipeline = this._renderPipelines[renderPipelineName];
  34921. if (!renderPipeline) {
  34922. return;
  34923. }
  34924. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  34925. };
  34926. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  34927. var renderPipeline = this._renderPipelines[renderPipelineName];
  34928. if (!renderPipeline) {
  34929. return;
  34930. }
  34931. renderPipeline._disableDisplayOnlyPass(cameras);
  34932. };
  34933. PostProcessRenderPipelineManager.prototype.update = function () {
  34934. for (var renderPipelineName in this._renderPipelines) {
  34935. var pipeline = this._renderPipelines[renderPipelineName];
  34936. if (!pipeline.isSupported) {
  34937. pipeline.dispose();
  34938. delete this._renderPipelines[renderPipelineName];
  34939. }
  34940. else {
  34941. pipeline._update();
  34942. }
  34943. }
  34944. };
  34945. return PostProcessRenderPipelineManager;
  34946. }());
  34947. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  34948. })(BABYLON || (BABYLON = {}));
  34949. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  34950. var BABYLON;
  34951. (function (BABYLON) {
  34952. var BoundingBoxRenderer = (function () {
  34953. function BoundingBoxRenderer(scene) {
  34954. this.frontColor = new BABYLON.Color3(1, 1, 1);
  34955. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  34956. this.showBackLines = true;
  34957. this.renderList = new BABYLON.SmartArray(32);
  34958. this._vertexBuffers = {};
  34959. this._scene = scene;
  34960. }
  34961. BoundingBoxRenderer.prototype._prepareRessources = function () {
  34962. if (this._colorShader) {
  34963. return;
  34964. }
  34965. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  34966. attributes: [BABYLON.VertexBuffer.PositionKind],
  34967. uniforms: ["worldViewProjection", "color"]
  34968. });
  34969. var engine = this._scene.getEngine();
  34970. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  34971. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  34972. 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]);
  34973. };
  34974. BoundingBoxRenderer.prototype.reset = function () {
  34975. this.renderList.reset();
  34976. };
  34977. BoundingBoxRenderer.prototype.render = function () {
  34978. if (this.renderList.length === 0) {
  34979. return;
  34980. }
  34981. this._prepareRessources();
  34982. if (!this._colorShader.isReady()) {
  34983. return;
  34984. }
  34985. var engine = this._scene.getEngine();
  34986. engine.setDepthWrite(false);
  34987. this._colorShader._preBind();
  34988. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  34989. var boundingBox = this.renderList.data[boundingBoxIndex];
  34990. var min = boundingBox.minimum;
  34991. var max = boundingBox.maximum;
  34992. var diff = max.subtract(min);
  34993. var median = min.add(diff.scale(0.5));
  34994. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  34995. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  34996. .multiply(boundingBox.getWorldMatrix());
  34997. // VBOs
  34998. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  34999. if (this.showBackLines) {
  35000. // Back
  35001. engine.setDepthFunctionToGreaterOrEqual();
  35002. this._scene.resetCachedMaterial();
  35003. this._colorShader.setColor4("color", this.backColor.toColor4());
  35004. this._colorShader.bind(worldMatrix);
  35005. // Draw order
  35006. engine.draw(false, 0, 24);
  35007. }
  35008. // Front
  35009. engine.setDepthFunctionToLess();
  35010. this._scene.resetCachedMaterial();
  35011. this._colorShader.setColor4("color", this.frontColor.toColor4());
  35012. this._colorShader.bind(worldMatrix);
  35013. // Draw order
  35014. engine.draw(false, 0, 24);
  35015. }
  35016. this._colorShader.unbind();
  35017. engine.setDepthFunctionToLessOrEqual();
  35018. engine.setDepthWrite(true);
  35019. };
  35020. BoundingBoxRenderer.prototype.dispose = function () {
  35021. if (!this._colorShader) {
  35022. return;
  35023. }
  35024. this._colorShader.dispose();
  35025. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  35026. if (buffer) {
  35027. buffer.dispose();
  35028. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  35029. }
  35030. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  35031. };
  35032. return BoundingBoxRenderer;
  35033. }());
  35034. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  35035. })(BABYLON || (BABYLON = {}));
  35036. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  35037. var BABYLON;
  35038. (function (BABYLON) {
  35039. var Condition = (function () {
  35040. function Condition(actionManager) {
  35041. this._actionManager = actionManager;
  35042. }
  35043. Condition.prototype.isValid = function () {
  35044. return true;
  35045. };
  35046. Condition.prototype._getProperty = function (propertyPath) {
  35047. return this._actionManager._getProperty(propertyPath);
  35048. };
  35049. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  35050. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35051. };
  35052. Condition.prototype.serialize = function () {
  35053. };
  35054. Condition.prototype._serialize = function (serializedCondition) {
  35055. return {
  35056. type: 2,
  35057. children: [],
  35058. name: serializedCondition.name,
  35059. properties: serializedCondition.properties
  35060. };
  35061. };
  35062. return Condition;
  35063. }());
  35064. BABYLON.Condition = Condition;
  35065. var ValueCondition = (function (_super) {
  35066. __extends(ValueCondition, _super);
  35067. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  35068. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  35069. var _this = _super.call(this, actionManager) || this;
  35070. _this.propertyPath = propertyPath;
  35071. _this.value = value;
  35072. _this.operator = operator;
  35073. _this._target = target;
  35074. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  35075. _this._property = _this._getProperty(_this.propertyPath);
  35076. return _this;
  35077. }
  35078. Object.defineProperty(ValueCondition, "IsEqual", {
  35079. get: function () {
  35080. return ValueCondition._IsEqual;
  35081. },
  35082. enumerable: true,
  35083. configurable: true
  35084. });
  35085. Object.defineProperty(ValueCondition, "IsDifferent", {
  35086. get: function () {
  35087. return ValueCondition._IsDifferent;
  35088. },
  35089. enumerable: true,
  35090. configurable: true
  35091. });
  35092. Object.defineProperty(ValueCondition, "IsGreater", {
  35093. get: function () {
  35094. return ValueCondition._IsGreater;
  35095. },
  35096. enumerable: true,
  35097. configurable: true
  35098. });
  35099. Object.defineProperty(ValueCondition, "IsLesser", {
  35100. get: function () {
  35101. return ValueCondition._IsLesser;
  35102. },
  35103. enumerable: true,
  35104. configurable: true
  35105. });
  35106. // Methods
  35107. ValueCondition.prototype.isValid = function () {
  35108. switch (this.operator) {
  35109. case ValueCondition.IsGreater:
  35110. return this._effectiveTarget[this._property] > this.value;
  35111. case ValueCondition.IsLesser:
  35112. return this._effectiveTarget[this._property] < this.value;
  35113. case ValueCondition.IsEqual:
  35114. case ValueCondition.IsDifferent:
  35115. var check;
  35116. if (this.value.equals) {
  35117. check = this.value.equals(this._effectiveTarget[this._property]);
  35118. }
  35119. else {
  35120. check = this.value === this._effectiveTarget[this._property];
  35121. }
  35122. return this.operator === ValueCondition.IsEqual ? check : !check;
  35123. }
  35124. return false;
  35125. };
  35126. ValueCondition.prototype.serialize = function () {
  35127. return this._serialize({
  35128. name: "ValueCondition",
  35129. properties: [
  35130. BABYLON.Action._GetTargetProperty(this._target),
  35131. { name: "propertyPath", value: this.propertyPath },
  35132. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  35133. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  35134. ]
  35135. });
  35136. };
  35137. ValueCondition.GetOperatorName = function (operator) {
  35138. switch (operator) {
  35139. case ValueCondition._IsEqual: return "IsEqual";
  35140. case ValueCondition._IsDifferent: return "IsDifferent";
  35141. case ValueCondition._IsGreater: return "IsGreater";
  35142. case ValueCondition._IsLesser: return "IsLesser";
  35143. default: return "";
  35144. }
  35145. };
  35146. return ValueCondition;
  35147. }(Condition));
  35148. // Statics
  35149. ValueCondition._IsEqual = 0;
  35150. ValueCondition._IsDifferent = 1;
  35151. ValueCondition._IsGreater = 2;
  35152. ValueCondition._IsLesser = 3;
  35153. BABYLON.ValueCondition = ValueCondition;
  35154. var PredicateCondition = (function (_super) {
  35155. __extends(PredicateCondition, _super);
  35156. function PredicateCondition(actionManager, predicate) {
  35157. var _this = _super.call(this, actionManager) || this;
  35158. _this.predicate = predicate;
  35159. return _this;
  35160. }
  35161. PredicateCondition.prototype.isValid = function () {
  35162. return this.predicate();
  35163. };
  35164. return PredicateCondition;
  35165. }(Condition));
  35166. BABYLON.PredicateCondition = PredicateCondition;
  35167. var StateCondition = (function (_super) {
  35168. __extends(StateCondition, _super);
  35169. function StateCondition(actionManager, target, value) {
  35170. var _this = _super.call(this, actionManager) || this;
  35171. _this.value = value;
  35172. _this._target = target;
  35173. return _this;
  35174. }
  35175. // Methods
  35176. StateCondition.prototype.isValid = function () {
  35177. return this._target.state === this.value;
  35178. };
  35179. StateCondition.prototype.serialize = function () {
  35180. return this._serialize({
  35181. name: "StateCondition",
  35182. properties: [
  35183. BABYLON.Action._GetTargetProperty(this._target),
  35184. { name: "value", value: this.value }
  35185. ]
  35186. });
  35187. };
  35188. return StateCondition;
  35189. }(Condition));
  35190. BABYLON.StateCondition = StateCondition;
  35191. })(BABYLON || (BABYLON = {}));
  35192. //# sourceMappingURL=babylon.condition.js.map
  35193. var BABYLON;
  35194. (function (BABYLON) {
  35195. var Action = (function () {
  35196. function Action(triggerOptions, condition) {
  35197. this.triggerOptions = triggerOptions;
  35198. if (triggerOptions.parameter) {
  35199. this.trigger = triggerOptions.trigger;
  35200. this._triggerParameter = triggerOptions.parameter;
  35201. }
  35202. else {
  35203. this.trigger = triggerOptions;
  35204. }
  35205. this._nextActiveAction = this;
  35206. this._condition = condition;
  35207. }
  35208. // Methods
  35209. Action.prototype._prepare = function () {
  35210. };
  35211. Action.prototype.getTriggerParameter = function () {
  35212. return this._triggerParameter;
  35213. };
  35214. Action.prototype._executeCurrent = function (evt) {
  35215. if (this._nextActiveAction._condition) {
  35216. var condition = this._nextActiveAction._condition;
  35217. var currentRenderId = this._actionManager.getScene().getRenderId();
  35218. // We cache the current evaluation for the current frame
  35219. if (condition._evaluationId === currentRenderId) {
  35220. if (!condition._currentResult) {
  35221. return;
  35222. }
  35223. }
  35224. else {
  35225. condition._evaluationId = currentRenderId;
  35226. if (!condition.isValid()) {
  35227. condition._currentResult = false;
  35228. return;
  35229. }
  35230. condition._currentResult = true;
  35231. }
  35232. }
  35233. this._nextActiveAction.execute(evt);
  35234. this.skipToNextActiveAction();
  35235. };
  35236. Action.prototype.execute = function (evt) {
  35237. };
  35238. Action.prototype.skipToNextActiveAction = function () {
  35239. if (this._nextActiveAction._child) {
  35240. if (!this._nextActiveAction._child._actionManager) {
  35241. this._nextActiveAction._child._actionManager = this._actionManager;
  35242. }
  35243. this._nextActiveAction = this._nextActiveAction._child;
  35244. }
  35245. else {
  35246. this._nextActiveAction = this;
  35247. }
  35248. };
  35249. Action.prototype.then = function (action) {
  35250. this._child = action;
  35251. action._actionManager = this._actionManager;
  35252. action._prepare();
  35253. return action;
  35254. };
  35255. Action.prototype._getProperty = function (propertyPath) {
  35256. return this._actionManager._getProperty(propertyPath);
  35257. };
  35258. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  35259. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35260. };
  35261. Action.prototype.serialize = function (parent) {
  35262. };
  35263. // Called by BABYLON.Action objects in serialize(...). Internal use
  35264. Action.prototype._serialize = function (serializedAction, parent) {
  35265. var serializationObject = {
  35266. type: 1,
  35267. children: [],
  35268. name: serializedAction.name,
  35269. properties: serializedAction.properties || []
  35270. };
  35271. // Serialize child
  35272. if (this._child) {
  35273. this._child.serialize(serializationObject);
  35274. }
  35275. // Check if "this" has a condition
  35276. if (this._condition) {
  35277. var serializedCondition = this._condition.serialize();
  35278. serializedCondition.children.push(serializationObject);
  35279. if (parent) {
  35280. parent.children.push(serializedCondition);
  35281. }
  35282. return serializedCondition;
  35283. }
  35284. if (parent) {
  35285. parent.children.push(serializationObject);
  35286. }
  35287. return serializationObject;
  35288. };
  35289. return Action;
  35290. }());
  35291. Action._SerializeValueAsString = function (value) {
  35292. if (typeof value === "number") {
  35293. return value.toString();
  35294. }
  35295. if (typeof value === "boolean") {
  35296. return value ? "true" : "false";
  35297. }
  35298. if (value instanceof BABYLON.Vector2) {
  35299. return value.x + ", " + value.y;
  35300. }
  35301. if (value instanceof BABYLON.Vector3) {
  35302. return value.x + ", " + value.y + ", " + value.z;
  35303. }
  35304. if (value instanceof BABYLON.Color3) {
  35305. return value.r + ", " + value.g + ", " + value.b;
  35306. }
  35307. if (value instanceof BABYLON.Color4) {
  35308. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  35309. }
  35310. return value; // string
  35311. };
  35312. Action._GetTargetProperty = function (target) {
  35313. return {
  35314. name: "target",
  35315. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  35316. : target instanceof BABYLON.Light ? "LightProperties"
  35317. : target instanceof BABYLON.Camera ? "CameraProperties"
  35318. : "SceneProperties",
  35319. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  35320. };
  35321. };
  35322. BABYLON.Action = Action;
  35323. })(BABYLON || (BABYLON = {}));
  35324. //# sourceMappingURL=babylon.action.js.map
  35325. var BABYLON;
  35326. (function (BABYLON) {
  35327. /**
  35328. * ActionEvent is the event beint sent when an action is triggered.
  35329. */
  35330. var ActionEvent = (function () {
  35331. /**
  35332. * @constructor
  35333. * @param source The mesh or sprite that triggered the action.
  35334. * @param pointerX The X mouse cursor position at the time of the event
  35335. * @param pointerY The Y mouse cursor position at the time of the event
  35336. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  35337. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  35338. */
  35339. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  35340. this.source = source;
  35341. this.pointerX = pointerX;
  35342. this.pointerY = pointerY;
  35343. this.meshUnderPointer = meshUnderPointer;
  35344. this.sourceEvent = sourceEvent;
  35345. this.additionalData = additionalData;
  35346. }
  35347. /**
  35348. * Helper function to auto-create an ActionEvent from a source mesh.
  35349. * @param source The source mesh that triggered the event
  35350. * @param evt {Event} The original (browser) event
  35351. */
  35352. ActionEvent.CreateNew = function (source, evt, additionalData) {
  35353. var scene = source.getScene();
  35354. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35355. };
  35356. /**
  35357. * Helper function to auto-create an ActionEvent from a source mesh.
  35358. * @param source The source sprite that triggered the event
  35359. * @param scene Scene associated with the sprite
  35360. * @param evt {Event} The original (browser) event
  35361. */
  35362. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  35363. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35364. };
  35365. /**
  35366. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  35367. * @param scene the scene where the event occurred
  35368. * @param evt {Event} The original (browser) event
  35369. */
  35370. ActionEvent.CreateNewFromScene = function (scene, evt) {
  35371. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  35372. };
  35373. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  35374. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  35375. };
  35376. return ActionEvent;
  35377. }());
  35378. BABYLON.ActionEvent = ActionEvent;
  35379. /**
  35380. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  35381. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  35382. */
  35383. var ActionManager = (function () {
  35384. function ActionManager(scene) {
  35385. // Members
  35386. this.actions = new Array();
  35387. this.hoverCursor = '';
  35388. this._scene = scene;
  35389. scene._actionManagers.push(this);
  35390. }
  35391. Object.defineProperty(ActionManager, "NothingTrigger", {
  35392. get: function () {
  35393. return ActionManager._NothingTrigger;
  35394. },
  35395. enumerable: true,
  35396. configurable: true
  35397. });
  35398. Object.defineProperty(ActionManager, "OnPickTrigger", {
  35399. get: function () {
  35400. return ActionManager._OnPickTrigger;
  35401. },
  35402. enumerable: true,
  35403. configurable: true
  35404. });
  35405. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  35406. get: function () {
  35407. return ActionManager._OnLeftPickTrigger;
  35408. },
  35409. enumerable: true,
  35410. configurable: true
  35411. });
  35412. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  35413. get: function () {
  35414. return ActionManager._OnRightPickTrigger;
  35415. },
  35416. enumerable: true,
  35417. configurable: true
  35418. });
  35419. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  35420. get: function () {
  35421. return ActionManager._OnCenterPickTrigger;
  35422. },
  35423. enumerable: true,
  35424. configurable: true
  35425. });
  35426. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  35427. get: function () {
  35428. return ActionManager._OnPickDownTrigger;
  35429. },
  35430. enumerable: true,
  35431. configurable: true
  35432. });
  35433. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  35434. get: function () {
  35435. return ActionManager._OnPickUpTrigger;
  35436. },
  35437. enumerable: true,
  35438. configurable: true
  35439. });
  35440. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  35441. /// This trigger will only be raised if you also declared a OnPickDown
  35442. get: function () {
  35443. return ActionManager._OnPickOutTrigger;
  35444. },
  35445. enumerable: true,
  35446. configurable: true
  35447. });
  35448. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  35449. get: function () {
  35450. return ActionManager._OnLongPressTrigger;
  35451. },
  35452. enumerable: true,
  35453. configurable: true
  35454. });
  35455. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  35456. get: function () {
  35457. return ActionManager._OnPointerOverTrigger;
  35458. },
  35459. enumerable: true,
  35460. configurable: true
  35461. });
  35462. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  35463. get: function () {
  35464. return ActionManager._OnPointerOutTrigger;
  35465. },
  35466. enumerable: true,
  35467. configurable: true
  35468. });
  35469. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  35470. get: function () {
  35471. return ActionManager._OnEveryFrameTrigger;
  35472. },
  35473. enumerable: true,
  35474. configurable: true
  35475. });
  35476. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  35477. get: function () {
  35478. return ActionManager._OnIntersectionEnterTrigger;
  35479. },
  35480. enumerable: true,
  35481. configurable: true
  35482. });
  35483. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  35484. get: function () {
  35485. return ActionManager._OnIntersectionExitTrigger;
  35486. },
  35487. enumerable: true,
  35488. configurable: true
  35489. });
  35490. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  35491. get: function () {
  35492. return ActionManager._OnKeyDownTrigger;
  35493. },
  35494. enumerable: true,
  35495. configurable: true
  35496. });
  35497. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  35498. get: function () {
  35499. return ActionManager._OnKeyUpTrigger;
  35500. },
  35501. enumerable: true,
  35502. configurable: true
  35503. });
  35504. // Methods
  35505. ActionManager.prototype.dispose = function () {
  35506. var index = this._scene._actionManagers.indexOf(this);
  35507. if (index > -1) {
  35508. this._scene._actionManagers.splice(index, 1);
  35509. }
  35510. };
  35511. ActionManager.prototype.getScene = function () {
  35512. return this._scene;
  35513. };
  35514. /**
  35515. * Does this action manager handles actions of any of the given triggers
  35516. * @param {number[]} triggers - the triggers to be tested
  35517. * @return {boolean} whether one (or more) of the triggers is handeled
  35518. */
  35519. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  35520. for (var index = 0; index < this.actions.length; index++) {
  35521. var action = this.actions[index];
  35522. if (triggers.indexOf(action.trigger) > -1) {
  35523. return true;
  35524. }
  35525. }
  35526. return false;
  35527. };
  35528. /**
  35529. * Does this action manager handles actions of a given trigger
  35530. * @param {number} trigger - the trigger to be tested
  35531. * @return {boolean} whether the trigger is handeled
  35532. */
  35533. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  35534. for (var index = 0; index < this.actions.length; index++) {
  35535. var action = this.actions[index];
  35536. if (action.trigger === trigger) {
  35537. return true;
  35538. }
  35539. }
  35540. return false;
  35541. };
  35542. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  35543. /**
  35544. * Does this action manager has pointer triggers
  35545. * @return {boolean} whether or not it has pointer triggers
  35546. */
  35547. get: function () {
  35548. for (var index = 0; index < this.actions.length; index++) {
  35549. var action = this.actions[index];
  35550. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  35551. return true;
  35552. }
  35553. }
  35554. return false;
  35555. },
  35556. enumerable: true,
  35557. configurable: true
  35558. });
  35559. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  35560. /**
  35561. * Does this action manager has pick triggers
  35562. * @return {boolean} whether or not it has pick triggers
  35563. */
  35564. get: function () {
  35565. for (var index = 0; index < this.actions.length; index++) {
  35566. var action = this.actions[index];
  35567. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  35568. return true;
  35569. }
  35570. }
  35571. return false;
  35572. },
  35573. enumerable: true,
  35574. configurable: true
  35575. });
  35576. /**
  35577. * Registers an action to this action manager
  35578. * @param {BABYLON.Action} action - the action to be registered
  35579. * @return {BABYLON.Action} the action amended (prepared) after registration
  35580. */
  35581. ActionManager.prototype.registerAction = function (action) {
  35582. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  35583. if (this.getScene().actionManager !== this) {
  35584. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  35585. return null;
  35586. }
  35587. }
  35588. this.actions.push(action);
  35589. action._actionManager = this;
  35590. action._prepare();
  35591. return action;
  35592. };
  35593. /**
  35594. * Process a specific trigger
  35595. * @param {number} trigger - the trigger to process
  35596. * @param evt {BABYLON.ActionEvent} the event details to be processed
  35597. */
  35598. ActionManager.prototype.processTrigger = function (trigger, evt) {
  35599. for (var index = 0; index < this.actions.length; index++) {
  35600. var action = this.actions[index];
  35601. if (action.trigger === trigger) {
  35602. if (trigger === ActionManager.OnKeyUpTrigger
  35603. || trigger === ActionManager.OnKeyDownTrigger) {
  35604. var parameter = action.getTriggerParameter();
  35605. if (parameter) {
  35606. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  35607. var actualkey = String.fromCharCode(unicode).toLowerCase();
  35608. if (actualkey !== parameter.toLowerCase()) {
  35609. continue;
  35610. }
  35611. }
  35612. }
  35613. action._executeCurrent(evt);
  35614. }
  35615. }
  35616. };
  35617. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  35618. var properties = propertyPath.split(".");
  35619. for (var index = 0; index < properties.length - 1; index++) {
  35620. target = target[properties[index]];
  35621. }
  35622. return target;
  35623. };
  35624. ActionManager.prototype._getProperty = function (propertyPath) {
  35625. var properties = propertyPath.split(".");
  35626. return properties[properties.length - 1];
  35627. };
  35628. ActionManager.prototype.serialize = function (name) {
  35629. var root = {
  35630. children: [],
  35631. name: name,
  35632. type: 3,
  35633. properties: [] // Empty for root but required
  35634. };
  35635. for (var i = 0; i < this.actions.length; i++) {
  35636. var triggerObject = {
  35637. type: 0,
  35638. children: [],
  35639. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  35640. properties: []
  35641. };
  35642. var triggerOptions = this.actions[i].triggerOptions;
  35643. if (triggerOptions && typeof triggerOptions !== "number") {
  35644. if (triggerOptions.parameter instanceof BABYLON.Node) {
  35645. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  35646. }
  35647. else {
  35648. var parameter = {};
  35649. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  35650. if (triggerOptions.parameter.mesh) {
  35651. parameter._meshId = triggerOptions.parameter.mesh.id;
  35652. }
  35653. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  35654. }
  35655. }
  35656. // Serialize child action, recursively
  35657. this.actions[i].serialize(triggerObject);
  35658. // Add serialized trigger
  35659. root.children.push(triggerObject);
  35660. }
  35661. return root;
  35662. };
  35663. ActionManager.Parse = function (parsedActions, object, scene) {
  35664. var actionManager = new BABYLON.ActionManager(scene);
  35665. if (object === null)
  35666. scene.actionManager = actionManager;
  35667. else
  35668. object.actionManager = actionManager;
  35669. // instanciate a new object
  35670. var instanciate = function (name, params) {
  35671. var newInstance = Object.create(BABYLON[name].prototype);
  35672. newInstance.constructor.apply(newInstance, params);
  35673. return newInstance;
  35674. };
  35675. var parseParameter = function (name, value, target, propertyPath) {
  35676. if (propertyPath === null) {
  35677. // String, boolean or float
  35678. var floatValue = parseFloat(value);
  35679. if (value === "true" || value === "false")
  35680. return value === "true";
  35681. else
  35682. return isNaN(floatValue) ? value : floatValue;
  35683. }
  35684. var effectiveTarget = propertyPath.split(".");
  35685. var values = value.split(",");
  35686. // Get effective Target
  35687. for (var i = 0; i < effectiveTarget.length; i++) {
  35688. target = target[effectiveTarget[i]];
  35689. }
  35690. // Return appropriate value with its type
  35691. if (typeof (target) === "boolean")
  35692. return values[0] === "true";
  35693. if (typeof (target) === "string")
  35694. return values[0];
  35695. // Parameters with multiple values such as Vector3 etc.
  35696. var split = new Array();
  35697. for (var i = 0; i < values.length; i++)
  35698. split.push(parseFloat(values[i]));
  35699. if (target instanceof BABYLON.Vector3)
  35700. return BABYLON.Vector3.FromArray(split);
  35701. if (target instanceof BABYLON.Vector4)
  35702. return BABYLON.Vector4.FromArray(split);
  35703. if (target instanceof BABYLON.Color3)
  35704. return BABYLON.Color3.FromArray(split);
  35705. if (target instanceof BABYLON.Color4)
  35706. return BABYLON.Color4.FromArray(split);
  35707. return parseFloat(values[0]);
  35708. };
  35709. // traverse graph per trigger
  35710. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  35711. if (combineArray === void 0) { combineArray = null; }
  35712. if (parsedAction.detached)
  35713. return;
  35714. var parameters = new Array();
  35715. var target = null;
  35716. var propertyPath = null;
  35717. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  35718. // Parameters
  35719. if (parsedAction.type === 2)
  35720. parameters.push(actionManager);
  35721. else
  35722. parameters.push(trigger);
  35723. if (combine) {
  35724. var actions = new Array();
  35725. for (var j = 0; j < parsedAction.combine.length; j++) {
  35726. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  35727. }
  35728. parameters.push(actions);
  35729. }
  35730. else {
  35731. for (var i = 0; i < parsedAction.properties.length; i++) {
  35732. var value = parsedAction.properties[i].value;
  35733. var name = parsedAction.properties[i].name;
  35734. var targetType = parsedAction.properties[i].targetType;
  35735. if (name === "target")
  35736. if (targetType !== null && targetType === "SceneProperties")
  35737. value = target = scene;
  35738. else
  35739. value = target = scene.getNodeByName(value);
  35740. else if (name === "parent")
  35741. value = scene.getNodeByName(value);
  35742. else if (name === "sound")
  35743. value = scene.getSoundByName(value);
  35744. else if (name !== "propertyPath") {
  35745. if (parsedAction.type === 2 && name === "operator")
  35746. value = BABYLON.ValueCondition[value];
  35747. else
  35748. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  35749. }
  35750. else {
  35751. propertyPath = value;
  35752. }
  35753. parameters.push(value);
  35754. }
  35755. }
  35756. if (combineArray === null) {
  35757. parameters.push(condition);
  35758. }
  35759. else {
  35760. parameters.push(null);
  35761. }
  35762. // If interpolate value action
  35763. if (parsedAction.name === "InterpolateValueAction") {
  35764. var param = parameters[parameters.length - 2];
  35765. parameters[parameters.length - 1] = param;
  35766. parameters[parameters.length - 2] = condition;
  35767. }
  35768. // Action or condition(s) and not CombineAction
  35769. var newAction = instanciate(parsedAction.name, parameters);
  35770. if (newAction instanceof BABYLON.Condition && condition !== null) {
  35771. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  35772. if (action)
  35773. action.then(nothing);
  35774. else
  35775. actionManager.registerAction(nothing);
  35776. action = nothing;
  35777. }
  35778. if (combineArray === null) {
  35779. if (newAction instanceof BABYLON.Condition) {
  35780. condition = newAction;
  35781. newAction = action;
  35782. }
  35783. else {
  35784. condition = null;
  35785. if (action)
  35786. action.then(newAction);
  35787. else
  35788. actionManager.registerAction(newAction);
  35789. }
  35790. }
  35791. else {
  35792. combineArray.push(newAction);
  35793. }
  35794. for (var i = 0; i < parsedAction.children.length; i++)
  35795. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  35796. };
  35797. // triggers
  35798. for (var i = 0; i < parsedActions.children.length; i++) {
  35799. var triggerParams;
  35800. var trigger = parsedActions.children[i];
  35801. if (trigger.properties.length > 0) {
  35802. var param = trigger.properties[0].value;
  35803. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  35804. if (value._meshId) {
  35805. value.mesh = scene.getMeshByID(value._meshId);
  35806. }
  35807. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  35808. }
  35809. else
  35810. triggerParams = BABYLON.ActionManager[trigger.name];
  35811. for (var j = 0; j < trigger.children.length; j++) {
  35812. if (!trigger.detached)
  35813. traverse(trigger.children[j], triggerParams, null, null);
  35814. }
  35815. }
  35816. };
  35817. ActionManager.GetTriggerName = function (trigger) {
  35818. switch (trigger) {
  35819. case 0: return "NothingTrigger";
  35820. case 1: return "OnPickTrigger";
  35821. case 2: return "OnLeftPickTrigger";
  35822. case 3: return "OnRightPickTrigger";
  35823. case 4: return "OnCenterPickTrigger";
  35824. case 5: return "OnPickDownTrigger";
  35825. case 6: return "OnPickUpTrigger";
  35826. case 7: return "OnLongPressTrigger";
  35827. case 8: return "OnPointerOverTrigger";
  35828. case 9: return "OnPointerOutTrigger";
  35829. case 10: return "OnEveryFrameTrigger";
  35830. case 11: return "OnIntersectionEnterTrigger";
  35831. case 12: return "OnIntersectionExitTrigger";
  35832. case 13: return "OnKeyDownTrigger";
  35833. case 14: return "OnKeyUpTrigger";
  35834. case 15: return "OnPickOutTrigger";
  35835. default: return "";
  35836. }
  35837. };
  35838. return ActionManager;
  35839. }());
  35840. // Statics
  35841. ActionManager._NothingTrigger = 0;
  35842. ActionManager._OnPickTrigger = 1;
  35843. ActionManager._OnLeftPickTrigger = 2;
  35844. ActionManager._OnRightPickTrigger = 3;
  35845. ActionManager._OnCenterPickTrigger = 4;
  35846. ActionManager._OnPickDownTrigger = 5;
  35847. ActionManager._OnPickUpTrigger = 6;
  35848. ActionManager._OnLongPressTrigger = 7;
  35849. ActionManager._OnPointerOverTrigger = 8;
  35850. ActionManager._OnPointerOutTrigger = 9;
  35851. ActionManager._OnEveryFrameTrigger = 10;
  35852. ActionManager._OnIntersectionEnterTrigger = 11;
  35853. ActionManager._OnIntersectionExitTrigger = 12;
  35854. ActionManager._OnKeyDownTrigger = 13;
  35855. ActionManager._OnKeyUpTrigger = 14;
  35856. ActionManager._OnPickOutTrigger = 15;
  35857. ActionManager.DragMovementThreshold = 10; // in pixels
  35858. ActionManager.LongPressDelay = 500; // in milliseconds
  35859. BABYLON.ActionManager = ActionManager;
  35860. })(BABYLON || (BABYLON = {}));
  35861. //# sourceMappingURL=babylon.actionManager.js.map
  35862. var BABYLON;
  35863. (function (BABYLON) {
  35864. var InterpolateValueAction = (function (_super) {
  35865. __extends(InterpolateValueAction, _super);
  35866. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  35867. if (duration === void 0) { duration = 1000; }
  35868. var _this = _super.call(this, triggerOptions, condition) || this;
  35869. _this.propertyPath = propertyPath;
  35870. _this.value = value;
  35871. _this.duration = duration;
  35872. _this.stopOtherAnimations = stopOtherAnimations;
  35873. _this.onInterpolationDone = onInterpolationDone;
  35874. _this._target = _this._effectiveTarget = target;
  35875. return _this;
  35876. }
  35877. InterpolateValueAction.prototype._prepare = function () {
  35878. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35879. this._property = this._getProperty(this.propertyPath);
  35880. };
  35881. InterpolateValueAction.prototype.execute = function () {
  35882. var scene = this._actionManager.getScene();
  35883. var keys = [
  35884. {
  35885. frame: 0,
  35886. value: this._effectiveTarget[this._property]
  35887. }, {
  35888. frame: 100,
  35889. value: this.value
  35890. }
  35891. ];
  35892. var dataType;
  35893. if (typeof this.value === "number") {
  35894. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  35895. }
  35896. else if (this.value instanceof BABYLON.Color3) {
  35897. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  35898. }
  35899. else if (this.value instanceof BABYLON.Vector3) {
  35900. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  35901. }
  35902. else if (this.value instanceof BABYLON.Matrix) {
  35903. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  35904. }
  35905. else if (this.value instanceof BABYLON.Quaternion) {
  35906. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  35907. }
  35908. else {
  35909. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  35910. return;
  35911. }
  35912. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  35913. animation.setKeys(keys);
  35914. if (this.stopOtherAnimations) {
  35915. scene.stopAnimation(this._effectiveTarget);
  35916. }
  35917. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  35918. };
  35919. InterpolateValueAction.prototype.serialize = function (parent) {
  35920. return _super.prototype._serialize.call(this, {
  35921. name: "InterpolateValueAction",
  35922. properties: [
  35923. BABYLON.Action._GetTargetProperty(this._target),
  35924. { name: "propertyPath", value: this.propertyPath },
  35925. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  35926. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  35927. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  35928. ]
  35929. }, parent);
  35930. };
  35931. return InterpolateValueAction;
  35932. }(BABYLON.Action));
  35933. BABYLON.InterpolateValueAction = InterpolateValueAction;
  35934. })(BABYLON || (BABYLON = {}));
  35935. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  35936. var BABYLON;
  35937. (function (BABYLON) {
  35938. var SwitchBooleanAction = (function (_super) {
  35939. __extends(SwitchBooleanAction, _super);
  35940. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  35941. var _this = _super.call(this, triggerOptions, condition) || this;
  35942. _this.propertyPath = propertyPath;
  35943. _this._target = _this._effectiveTarget = target;
  35944. return _this;
  35945. }
  35946. SwitchBooleanAction.prototype._prepare = function () {
  35947. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35948. this._property = this._getProperty(this.propertyPath);
  35949. };
  35950. SwitchBooleanAction.prototype.execute = function () {
  35951. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  35952. };
  35953. SwitchBooleanAction.prototype.serialize = function (parent) {
  35954. return _super.prototype._serialize.call(this, {
  35955. name: "SwitchBooleanAction",
  35956. properties: [
  35957. BABYLON.Action._GetTargetProperty(this._target),
  35958. { name: "propertyPath", value: this.propertyPath }
  35959. ]
  35960. }, parent);
  35961. };
  35962. return SwitchBooleanAction;
  35963. }(BABYLON.Action));
  35964. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  35965. var SetStateAction = (function (_super) {
  35966. __extends(SetStateAction, _super);
  35967. function SetStateAction(triggerOptions, target, value, condition) {
  35968. var _this = _super.call(this, triggerOptions, condition) || this;
  35969. _this.value = value;
  35970. _this._target = target;
  35971. return _this;
  35972. }
  35973. SetStateAction.prototype.execute = function () {
  35974. this._target.state = this.value;
  35975. };
  35976. SetStateAction.prototype.serialize = function (parent) {
  35977. return _super.prototype._serialize.call(this, {
  35978. name: "SetStateAction",
  35979. properties: [
  35980. BABYLON.Action._GetTargetProperty(this._target),
  35981. { name: "value", value: this.value }
  35982. ]
  35983. }, parent);
  35984. };
  35985. return SetStateAction;
  35986. }(BABYLON.Action));
  35987. BABYLON.SetStateAction = SetStateAction;
  35988. var SetValueAction = (function (_super) {
  35989. __extends(SetValueAction, _super);
  35990. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  35991. var _this = _super.call(this, triggerOptions, condition) || this;
  35992. _this.propertyPath = propertyPath;
  35993. _this.value = value;
  35994. _this._target = _this._effectiveTarget = target;
  35995. return _this;
  35996. }
  35997. SetValueAction.prototype._prepare = function () {
  35998. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35999. this._property = this._getProperty(this.propertyPath);
  36000. };
  36001. SetValueAction.prototype.execute = function () {
  36002. this._effectiveTarget[this._property] = this.value;
  36003. if (this._target.markAsDirty) {
  36004. this._target.markAsDirty(this._property);
  36005. }
  36006. };
  36007. SetValueAction.prototype.serialize = function (parent) {
  36008. return _super.prototype._serialize.call(this, {
  36009. name: "SetValueAction",
  36010. properties: [
  36011. BABYLON.Action._GetTargetProperty(this._target),
  36012. { name: "propertyPath", value: this.propertyPath },
  36013. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  36014. ]
  36015. }, parent);
  36016. };
  36017. return SetValueAction;
  36018. }(BABYLON.Action));
  36019. BABYLON.SetValueAction = SetValueAction;
  36020. var IncrementValueAction = (function (_super) {
  36021. __extends(IncrementValueAction, _super);
  36022. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  36023. var _this = _super.call(this, triggerOptions, condition) || this;
  36024. _this.propertyPath = propertyPath;
  36025. _this.value = value;
  36026. _this._target = _this._effectiveTarget = target;
  36027. return _this;
  36028. }
  36029. IncrementValueAction.prototype._prepare = function () {
  36030. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36031. this._property = this._getProperty(this.propertyPath);
  36032. if (typeof this._effectiveTarget[this._property] !== "number") {
  36033. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  36034. }
  36035. };
  36036. IncrementValueAction.prototype.execute = function () {
  36037. this._effectiveTarget[this._property] += this.value;
  36038. if (this._target.markAsDirty) {
  36039. this._target.markAsDirty(this._property);
  36040. }
  36041. };
  36042. IncrementValueAction.prototype.serialize = function (parent) {
  36043. return _super.prototype._serialize.call(this, {
  36044. name: "IncrementValueAction",
  36045. properties: [
  36046. BABYLON.Action._GetTargetProperty(this._target),
  36047. { name: "propertyPath", value: this.propertyPath },
  36048. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  36049. ]
  36050. }, parent);
  36051. };
  36052. return IncrementValueAction;
  36053. }(BABYLON.Action));
  36054. BABYLON.IncrementValueAction = IncrementValueAction;
  36055. var PlayAnimationAction = (function (_super) {
  36056. __extends(PlayAnimationAction, _super);
  36057. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  36058. var _this = _super.call(this, triggerOptions, condition) || this;
  36059. _this.from = from;
  36060. _this.to = to;
  36061. _this.loop = loop;
  36062. _this._target = target;
  36063. return _this;
  36064. }
  36065. PlayAnimationAction.prototype._prepare = function () {
  36066. };
  36067. PlayAnimationAction.prototype.execute = function () {
  36068. var scene = this._actionManager.getScene();
  36069. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  36070. };
  36071. PlayAnimationAction.prototype.serialize = function (parent) {
  36072. return _super.prototype._serialize.call(this, {
  36073. name: "PlayAnimationAction",
  36074. properties: [
  36075. BABYLON.Action._GetTargetProperty(this._target),
  36076. { name: "from", value: String(this.from) },
  36077. { name: "to", value: String(this.to) },
  36078. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  36079. ]
  36080. }, parent);
  36081. };
  36082. return PlayAnimationAction;
  36083. }(BABYLON.Action));
  36084. BABYLON.PlayAnimationAction = PlayAnimationAction;
  36085. var StopAnimationAction = (function (_super) {
  36086. __extends(StopAnimationAction, _super);
  36087. function StopAnimationAction(triggerOptions, target, condition) {
  36088. var _this = _super.call(this, triggerOptions, condition) || this;
  36089. _this._target = target;
  36090. return _this;
  36091. }
  36092. StopAnimationAction.prototype._prepare = function () {
  36093. };
  36094. StopAnimationAction.prototype.execute = function () {
  36095. var scene = this._actionManager.getScene();
  36096. scene.stopAnimation(this._target);
  36097. };
  36098. StopAnimationAction.prototype.serialize = function (parent) {
  36099. return _super.prototype._serialize.call(this, {
  36100. name: "StopAnimationAction",
  36101. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  36102. }, parent);
  36103. };
  36104. return StopAnimationAction;
  36105. }(BABYLON.Action));
  36106. BABYLON.StopAnimationAction = StopAnimationAction;
  36107. var DoNothingAction = (function (_super) {
  36108. __extends(DoNothingAction, _super);
  36109. function DoNothingAction(triggerOptions, condition) {
  36110. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  36111. return _super.call(this, triggerOptions, condition) || this;
  36112. }
  36113. DoNothingAction.prototype.execute = function () {
  36114. };
  36115. DoNothingAction.prototype.serialize = function (parent) {
  36116. return _super.prototype._serialize.call(this, {
  36117. name: "DoNothingAction",
  36118. properties: []
  36119. }, parent);
  36120. };
  36121. return DoNothingAction;
  36122. }(BABYLON.Action));
  36123. BABYLON.DoNothingAction = DoNothingAction;
  36124. var CombineAction = (function (_super) {
  36125. __extends(CombineAction, _super);
  36126. function CombineAction(triggerOptions, children, condition) {
  36127. var _this = _super.call(this, triggerOptions, condition) || this;
  36128. _this.children = children;
  36129. return _this;
  36130. }
  36131. CombineAction.prototype._prepare = function () {
  36132. for (var index = 0; index < this.children.length; index++) {
  36133. this.children[index]._actionManager = this._actionManager;
  36134. this.children[index]._prepare();
  36135. }
  36136. };
  36137. CombineAction.prototype.execute = function (evt) {
  36138. for (var index = 0; index < this.children.length; index++) {
  36139. this.children[index].execute(evt);
  36140. }
  36141. };
  36142. CombineAction.prototype.serialize = function (parent) {
  36143. var serializationObject = _super.prototype._serialize.call(this, {
  36144. name: "CombineAction",
  36145. properties: [],
  36146. combine: []
  36147. }, parent);
  36148. for (var i = 0; i < this.children.length; i++) {
  36149. serializationObject.combine.push(this.children[i].serialize(null));
  36150. }
  36151. return serializationObject;
  36152. };
  36153. return CombineAction;
  36154. }(BABYLON.Action));
  36155. BABYLON.CombineAction = CombineAction;
  36156. var ExecuteCodeAction = (function (_super) {
  36157. __extends(ExecuteCodeAction, _super);
  36158. function ExecuteCodeAction(triggerOptions, func, condition) {
  36159. var _this = _super.call(this, triggerOptions, condition) || this;
  36160. _this.func = func;
  36161. return _this;
  36162. }
  36163. ExecuteCodeAction.prototype.execute = function (evt) {
  36164. this.func(evt);
  36165. };
  36166. return ExecuteCodeAction;
  36167. }(BABYLON.Action));
  36168. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  36169. var SetParentAction = (function (_super) {
  36170. __extends(SetParentAction, _super);
  36171. function SetParentAction(triggerOptions, target, parent, condition) {
  36172. var _this = _super.call(this, triggerOptions, condition) || this;
  36173. _this._target = target;
  36174. _this._parent = parent;
  36175. return _this;
  36176. }
  36177. SetParentAction.prototype._prepare = function () {
  36178. };
  36179. SetParentAction.prototype.execute = function () {
  36180. if (this._target.parent === this._parent) {
  36181. return;
  36182. }
  36183. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  36184. invertParentWorldMatrix.invert();
  36185. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  36186. this._target.parent = this._parent;
  36187. };
  36188. SetParentAction.prototype.serialize = function (parent) {
  36189. return _super.prototype._serialize.call(this, {
  36190. name: "SetParentAction",
  36191. properties: [
  36192. BABYLON.Action._GetTargetProperty(this._target),
  36193. BABYLON.Action._GetTargetProperty(this._parent),
  36194. ]
  36195. }, parent);
  36196. };
  36197. return SetParentAction;
  36198. }(BABYLON.Action));
  36199. BABYLON.SetParentAction = SetParentAction;
  36200. var PlaySoundAction = (function (_super) {
  36201. __extends(PlaySoundAction, _super);
  36202. function PlaySoundAction(triggerOptions, sound, condition) {
  36203. var _this = _super.call(this, triggerOptions, condition) || this;
  36204. _this._sound = sound;
  36205. return _this;
  36206. }
  36207. PlaySoundAction.prototype._prepare = function () {
  36208. };
  36209. PlaySoundAction.prototype.execute = function () {
  36210. if (this._sound !== undefined)
  36211. this._sound.play();
  36212. };
  36213. PlaySoundAction.prototype.serialize = function (parent) {
  36214. return _super.prototype._serialize.call(this, {
  36215. name: "PlaySoundAction",
  36216. properties: [{ name: "sound", value: this._sound.name }]
  36217. }, parent);
  36218. };
  36219. return PlaySoundAction;
  36220. }(BABYLON.Action));
  36221. BABYLON.PlaySoundAction = PlaySoundAction;
  36222. var StopSoundAction = (function (_super) {
  36223. __extends(StopSoundAction, _super);
  36224. function StopSoundAction(triggerOptions, sound, condition) {
  36225. var _this = _super.call(this, triggerOptions, condition) || this;
  36226. _this._sound = sound;
  36227. return _this;
  36228. }
  36229. StopSoundAction.prototype._prepare = function () {
  36230. };
  36231. StopSoundAction.prototype.execute = function () {
  36232. if (this._sound !== undefined)
  36233. this._sound.stop();
  36234. };
  36235. StopSoundAction.prototype.serialize = function (parent) {
  36236. return _super.prototype._serialize.call(this, {
  36237. name: "StopSoundAction",
  36238. properties: [{ name: "sound", value: this._sound.name }]
  36239. }, parent);
  36240. };
  36241. return StopSoundAction;
  36242. }(BABYLON.Action));
  36243. BABYLON.StopSoundAction = StopSoundAction;
  36244. })(BABYLON || (BABYLON = {}));
  36245. //# sourceMappingURL=babylon.directActions.js.map
  36246. var BABYLON;
  36247. (function (BABYLON) {
  36248. var Geometry = (function () {
  36249. function Geometry(id, scene, vertexData, updatable, mesh) {
  36250. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  36251. this._totalVertices = 0;
  36252. this._isDisposed = false;
  36253. this.id = id;
  36254. this._engine = scene.getEngine();
  36255. this._meshes = [];
  36256. this._scene = scene;
  36257. //Init vertex buffer cache
  36258. this._vertexBuffers = {};
  36259. this._indices = [];
  36260. // vertexData
  36261. if (vertexData) {
  36262. this.setAllVerticesData(vertexData, updatable);
  36263. }
  36264. else {
  36265. this._totalVertices = 0;
  36266. this._indices = [];
  36267. }
  36268. // applyToMesh
  36269. if (mesh) {
  36270. if (mesh instanceof BABYLON.LinesMesh) {
  36271. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  36272. this.updateExtend();
  36273. }
  36274. this.applyToMesh(mesh);
  36275. mesh.computeWorldMatrix(true);
  36276. }
  36277. }
  36278. Object.defineProperty(Geometry.prototype, "boundingBias", {
  36279. /**
  36280. * 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
  36281. * @returns The Bias Vector
  36282. */
  36283. get: function () {
  36284. return this._boundingBias;
  36285. },
  36286. set: function (value) {
  36287. if (this._boundingBias && this._boundingBias.equals(value)) {
  36288. return;
  36289. }
  36290. this._boundingBias = value.clone();
  36291. this.updateBoundingInfo(true, null);
  36292. },
  36293. enumerable: true,
  36294. configurable: true
  36295. });
  36296. Object.defineProperty(Geometry.prototype, "extend", {
  36297. get: function () {
  36298. return this._extend;
  36299. },
  36300. enumerable: true,
  36301. configurable: true
  36302. });
  36303. Geometry.prototype.getScene = function () {
  36304. return this._scene;
  36305. };
  36306. Geometry.prototype.getEngine = function () {
  36307. return this._engine;
  36308. };
  36309. Geometry.prototype.isReady = function () {
  36310. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  36311. };
  36312. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  36313. get: function () {
  36314. for (var index = 0; index < this._meshes.length; index++) {
  36315. if (!this._meshes[index].doNotSerialize) {
  36316. return false;
  36317. }
  36318. }
  36319. return true;
  36320. },
  36321. enumerable: true,
  36322. configurable: true
  36323. });
  36324. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36325. vertexData.applyToGeometry(this, updatable);
  36326. this.notifyUpdate();
  36327. };
  36328. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  36329. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  36330. this.setVerticesBuffer(buffer);
  36331. };
  36332. Geometry.prototype.setVerticesBuffer = function (buffer) {
  36333. var kind = buffer.getKind();
  36334. if (this._vertexBuffers[kind]) {
  36335. this._vertexBuffers[kind].dispose();
  36336. }
  36337. this._vertexBuffers[kind] = buffer;
  36338. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36339. var data = buffer.getData();
  36340. var stride = buffer.getStrideSize();
  36341. this._totalVertices = data.length / stride;
  36342. this.updateExtend(data, stride);
  36343. var meshes = this._meshes;
  36344. var numOfMeshes = meshes.length;
  36345. for (var index = 0; index < numOfMeshes; index++) {
  36346. var mesh = meshes[index];
  36347. mesh._resetPointsArrayCache();
  36348. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36349. mesh._createGlobalSubMesh();
  36350. mesh.computeWorldMatrix(true);
  36351. }
  36352. }
  36353. this.notifyUpdate(kind);
  36354. };
  36355. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  36356. var vertexBuffer = this.getVertexBuffer(kind);
  36357. if (!vertexBuffer) {
  36358. return;
  36359. }
  36360. vertexBuffer.updateDirectly(data, offset);
  36361. this.notifyUpdate(kind);
  36362. };
  36363. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  36364. var vertexBuffer = this.getVertexBuffer(kind);
  36365. if (!vertexBuffer) {
  36366. return;
  36367. }
  36368. vertexBuffer.update(data);
  36369. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36370. var stride = vertexBuffer.getStrideSize();
  36371. this._totalVertices = data.length / stride;
  36372. this.updateBoundingInfo(updateExtends, data);
  36373. }
  36374. this.notifyUpdate(kind);
  36375. };
  36376. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  36377. if (updateExtends) {
  36378. this.updateExtend(data);
  36379. }
  36380. var meshes = this._meshes;
  36381. var numOfMeshes = meshes.length;
  36382. for (var index = 0; index < numOfMeshes; index++) {
  36383. var mesh = meshes[index];
  36384. mesh._resetPointsArrayCache();
  36385. if (updateExtends) {
  36386. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36387. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  36388. var subMesh = mesh.subMeshes[subIndex];
  36389. subMesh.refreshBoundingInfo();
  36390. }
  36391. }
  36392. }
  36393. };
  36394. Geometry.prototype.getTotalVertices = function () {
  36395. if (!this.isReady()) {
  36396. return 0;
  36397. }
  36398. return this._totalVertices;
  36399. };
  36400. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  36401. var vertexBuffer = this.getVertexBuffer(kind);
  36402. if (!vertexBuffer) {
  36403. return null;
  36404. }
  36405. var orig = vertexBuffer.getData();
  36406. if (!copyWhenShared || this._meshes.length === 1) {
  36407. return orig;
  36408. }
  36409. else {
  36410. var len = orig.length;
  36411. var copy = [];
  36412. for (var i = 0; i < len; i++) {
  36413. copy.push(orig[i]);
  36414. }
  36415. return copy;
  36416. }
  36417. };
  36418. Geometry.prototype.getVertexBuffer = function (kind) {
  36419. if (!this.isReady()) {
  36420. return null;
  36421. }
  36422. return this._vertexBuffers[kind];
  36423. };
  36424. Geometry.prototype.getVertexBuffers = function () {
  36425. if (!this.isReady()) {
  36426. return null;
  36427. }
  36428. return this._vertexBuffers;
  36429. };
  36430. Geometry.prototype.isVerticesDataPresent = function (kind) {
  36431. if (!this._vertexBuffers) {
  36432. if (this._delayInfo) {
  36433. return this._delayInfo.indexOf(kind) !== -1;
  36434. }
  36435. return false;
  36436. }
  36437. return this._vertexBuffers[kind] !== undefined;
  36438. };
  36439. Geometry.prototype.getVerticesDataKinds = function () {
  36440. var result = [];
  36441. var kind;
  36442. if (!this._vertexBuffers && this._delayInfo) {
  36443. for (kind in this._delayInfo) {
  36444. result.push(kind);
  36445. }
  36446. }
  36447. else {
  36448. for (kind in this._vertexBuffers) {
  36449. result.push(kind);
  36450. }
  36451. }
  36452. return result;
  36453. };
  36454. Geometry.prototype.setIndices = function (indices, totalVertices) {
  36455. if (this._indexBuffer) {
  36456. this._engine._releaseBuffer(this._indexBuffer);
  36457. }
  36458. this._indices = indices;
  36459. if (this._meshes.length !== 0 && this._indices) {
  36460. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  36461. }
  36462. if (totalVertices !== undefined) {
  36463. this._totalVertices = totalVertices;
  36464. }
  36465. var meshes = this._meshes;
  36466. var numOfMeshes = meshes.length;
  36467. for (var index = 0; index < numOfMeshes; index++) {
  36468. meshes[index]._createGlobalSubMesh();
  36469. }
  36470. this.notifyUpdate();
  36471. };
  36472. Geometry.prototype.getTotalIndices = function () {
  36473. if (!this.isReady()) {
  36474. return 0;
  36475. }
  36476. return this._indices.length;
  36477. };
  36478. Geometry.prototype.getIndices = function (copyWhenShared) {
  36479. if (!this.isReady()) {
  36480. return null;
  36481. }
  36482. var orig = this._indices;
  36483. if (!copyWhenShared || this._meshes.length === 1) {
  36484. return orig;
  36485. }
  36486. else {
  36487. var len = orig.length;
  36488. var copy = [];
  36489. for (var i = 0; i < len; i++) {
  36490. copy.push(orig[i]);
  36491. }
  36492. return copy;
  36493. }
  36494. };
  36495. Geometry.prototype.getIndexBuffer = function () {
  36496. if (!this.isReady()) {
  36497. return null;
  36498. }
  36499. return this._indexBuffer;
  36500. };
  36501. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  36502. var meshes = this._meshes;
  36503. var index = meshes.indexOf(mesh);
  36504. if (index === -1) {
  36505. return;
  36506. }
  36507. for (var kind in this._vertexBuffers) {
  36508. this._vertexBuffers[kind].dispose();
  36509. }
  36510. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  36511. this._indexBuffer = null;
  36512. }
  36513. meshes.splice(index, 1);
  36514. mesh._geometry = null;
  36515. if (meshes.length === 0 && shouldDispose) {
  36516. this.dispose();
  36517. }
  36518. };
  36519. Geometry.prototype.applyToMesh = function (mesh) {
  36520. if (mesh._geometry === this) {
  36521. return;
  36522. }
  36523. var previousGeometry = mesh._geometry;
  36524. if (previousGeometry) {
  36525. previousGeometry.releaseForMesh(mesh);
  36526. }
  36527. var meshes = this._meshes;
  36528. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  36529. mesh._geometry = this;
  36530. this._scene.pushGeometry(this);
  36531. meshes.push(mesh);
  36532. if (this.isReady()) {
  36533. this._applyToMesh(mesh);
  36534. }
  36535. else {
  36536. mesh._boundingInfo = this._boundingInfo;
  36537. }
  36538. };
  36539. Geometry.prototype.updateExtend = function (data, stride) {
  36540. if (data === void 0) { data = null; }
  36541. if (!data) {
  36542. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  36543. }
  36544. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  36545. };
  36546. Geometry.prototype._applyToMesh = function (mesh) {
  36547. var numOfMeshes = this._meshes.length;
  36548. // vertexBuffers
  36549. for (var kind in this._vertexBuffers) {
  36550. if (numOfMeshes === 1) {
  36551. this._vertexBuffers[kind].create();
  36552. }
  36553. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  36554. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36555. mesh._resetPointsArrayCache();
  36556. if (!this._extend) {
  36557. this.updateExtend(this._vertexBuffers[kind].getData());
  36558. }
  36559. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36560. mesh._createGlobalSubMesh();
  36561. //bounding info was just created again, world matrix should be applied again.
  36562. mesh._updateBoundingInfo();
  36563. }
  36564. }
  36565. // indexBuffer
  36566. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  36567. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  36568. }
  36569. if (this._indexBuffer) {
  36570. this._indexBuffer.references = numOfMeshes;
  36571. }
  36572. };
  36573. Geometry.prototype.notifyUpdate = function (kind) {
  36574. if (this.onGeometryUpdated) {
  36575. this.onGeometryUpdated(this, kind);
  36576. }
  36577. };
  36578. Geometry.prototype.load = function (scene, onLoaded) {
  36579. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  36580. return;
  36581. }
  36582. if (this.isReady()) {
  36583. if (onLoaded) {
  36584. onLoaded();
  36585. }
  36586. return;
  36587. }
  36588. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  36589. this._queueLoad(scene, onLoaded);
  36590. };
  36591. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  36592. var _this = this;
  36593. scene._addPendingData(this);
  36594. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  36595. _this._delayLoadingFunction(JSON.parse(data), _this);
  36596. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  36597. _this._delayInfo = [];
  36598. scene._removePendingData(_this);
  36599. var meshes = _this._meshes;
  36600. var numOfMeshes = meshes.length;
  36601. for (var index = 0; index < numOfMeshes; index++) {
  36602. _this._applyToMesh(meshes[index]);
  36603. }
  36604. if (onLoaded) {
  36605. onLoaded();
  36606. }
  36607. }, function () { }, scene.database);
  36608. };
  36609. /**
  36610. * Invert the geometry to move from a right handed system to a left handed one.
  36611. */
  36612. Geometry.prototype.toLeftHanded = function () {
  36613. // Flip faces
  36614. var tIndices = this.getIndices(false);
  36615. if (tIndices != null && tIndices.length > 0) {
  36616. for (var i = 0; i < tIndices.length; i += 3) {
  36617. var tTemp = tIndices[i + 0];
  36618. tIndices[i + 0] = tIndices[i + 2];
  36619. tIndices[i + 2] = tTemp;
  36620. }
  36621. this.setIndices(tIndices);
  36622. }
  36623. // Negate position.z
  36624. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  36625. if (tPositions != null && tPositions.length > 0) {
  36626. for (var i = 0; i < tPositions.length; i += 3) {
  36627. tPositions[i + 2] = -tPositions[i + 2];
  36628. }
  36629. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  36630. }
  36631. // Negate normal.z
  36632. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  36633. if (tNormals != null && tNormals.length > 0) {
  36634. for (var i = 0; i < tNormals.length; i += 3) {
  36635. tNormals[i + 2] = -tNormals[i + 2];
  36636. }
  36637. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  36638. }
  36639. };
  36640. Geometry.prototype.isDisposed = function () {
  36641. return this._isDisposed;
  36642. };
  36643. Geometry.prototype.dispose = function () {
  36644. var meshes = this._meshes;
  36645. var numOfMeshes = meshes.length;
  36646. var index;
  36647. for (index = 0; index < numOfMeshes; index++) {
  36648. this.releaseForMesh(meshes[index]);
  36649. }
  36650. this._meshes = [];
  36651. for (var kind in this._vertexBuffers) {
  36652. this._vertexBuffers[kind].dispose();
  36653. }
  36654. this._vertexBuffers = {};
  36655. this._totalVertices = 0;
  36656. if (this._indexBuffer) {
  36657. this._engine._releaseBuffer(this._indexBuffer);
  36658. }
  36659. this._indexBuffer = null;
  36660. this._indices = [];
  36661. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  36662. this.delayLoadingFile = null;
  36663. this._delayLoadingFunction = null;
  36664. this._delayInfo = [];
  36665. this._boundingInfo = null;
  36666. this._scene.removeGeometry(this);
  36667. this._isDisposed = true;
  36668. };
  36669. Geometry.prototype.copy = function (id) {
  36670. var vertexData = new BABYLON.VertexData();
  36671. vertexData.indices = [];
  36672. var indices = this.getIndices();
  36673. for (var index = 0; index < indices.length; index++) {
  36674. vertexData.indices.push(indices[index]);
  36675. }
  36676. var updatable = false;
  36677. var stopChecking = false;
  36678. var kind;
  36679. for (kind in this._vertexBuffers) {
  36680. // using slice() to make a copy of the array and not just reference it
  36681. var data = this.getVerticesData(kind);
  36682. if (data instanceof Float32Array) {
  36683. vertexData.set(new Float32Array(data), kind);
  36684. }
  36685. else {
  36686. vertexData.set(data.slice(0), kind);
  36687. }
  36688. if (!stopChecking) {
  36689. updatable = this.getVertexBuffer(kind).isUpdatable();
  36690. stopChecking = !updatable;
  36691. }
  36692. }
  36693. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  36694. geometry.delayLoadState = this.delayLoadState;
  36695. geometry.delayLoadingFile = this.delayLoadingFile;
  36696. geometry._delayLoadingFunction = this._delayLoadingFunction;
  36697. for (kind in this._delayInfo) {
  36698. geometry._delayInfo = geometry._delayInfo || [];
  36699. geometry._delayInfo.push(kind);
  36700. }
  36701. // Bounding info
  36702. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36703. return geometry;
  36704. };
  36705. Geometry.prototype.serialize = function () {
  36706. var serializationObject = {};
  36707. serializationObject.id = this.id;
  36708. if (BABYLON.Tags.HasTags(this)) {
  36709. serializationObject.tags = BABYLON.Tags.GetTags(this);
  36710. }
  36711. return serializationObject;
  36712. };
  36713. Geometry.prototype.serializeVerticeData = function () {
  36714. var serializationObject = this.serialize();
  36715. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36716. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36717. }
  36718. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36719. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36720. }
  36721. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36722. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36723. }
  36724. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36725. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  36726. }
  36727. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36728. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  36729. }
  36730. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36731. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  36732. }
  36733. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36734. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  36735. }
  36736. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36737. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  36738. }
  36739. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36740. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36741. }
  36742. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36743. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36744. serializationObject.matricesIndices._isExpanded = true;
  36745. }
  36746. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36747. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  36748. }
  36749. serializationObject.indices = this.getIndices();
  36750. return serializationObject;
  36751. };
  36752. // Statics
  36753. Geometry.ExtractFromMesh = function (mesh, id) {
  36754. var geometry = mesh._geometry;
  36755. if (!geometry) {
  36756. return null;
  36757. }
  36758. return geometry.copy(id);
  36759. };
  36760. /**
  36761. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  36762. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  36763. * Be aware Math.random() could cause collisions, but:
  36764. * "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"
  36765. */
  36766. Geometry.RandomId = function () {
  36767. return BABYLON.Tools.RandomId();
  36768. };
  36769. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  36770. var scene = mesh.getScene();
  36771. // Geometry
  36772. var geometryId = parsedGeometry.geometryId;
  36773. if (geometryId) {
  36774. var geometry = scene.getGeometryByID(geometryId);
  36775. if (geometry) {
  36776. geometry.applyToMesh(mesh);
  36777. }
  36778. }
  36779. else if (parsedGeometry instanceof ArrayBuffer) {
  36780. var binaryInfo = mesh._binaryInfo;
  36781. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36782. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36783. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36784. }
  36785. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36786. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36787. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36788. }
  36789. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36790. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36791. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36792. }
  36793. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36794. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36795. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36796. }
  36797. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36798. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36799. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36800. }
  36801. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36802. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36803. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36804. }
  36805. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36806. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36807. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36808. }
  36809. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36810. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36811. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36812. }
  36813. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36814. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36815. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36816. }
  36817. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36818. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36819. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36820. }
  36821. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36822. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36823. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36824. }
  36825. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36826. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36827. mesh.setIndices(indicesData);
  36828. }
  36829. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36830. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36831. mesh.subMeshes = [];
  36832. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36833. var materialIndex = subMeshesData[(i * 5) + 0];
  36834. var verticesStart = subMeshesData[(i * 5) + 1];
  36835. var verticesCount = subMeshesData[(i * 5) + 2];
  36836. var indexStart = subMeshesData[(i * 5) + 3];
  36837. var indexCount = subMeshesData[(i * 5) + 4];
  36838. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36839. }
  36840. }
  36841. }
  36842. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36843. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  36844. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  36845. if (parsedGeometry.uvs) {
  36846. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  36847. }
  36848. if (parsedGeometry.uvs2) {
  36849. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  36850. }
  36851. if (parsedGeometry.uvs3) {
  36852. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  36853. }
  36854. if (parsedGeometry.uvs4) {
  36855. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  36856. }
  36857. if (parsedGeometry.uvs5) {
  36858. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  36859. }
  36860. if (parsedGeometry.uvs6) {
  36861. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  36862. }
  36863. if (parsedGeometry.colors) {
  36864. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  36865. }
  36866. if (parsedGeometry.matricesIndices) {
  36867. if (!parsedGeometry.matricesIndices._isExpanded) {
  36868. var floatIndices = [];
  36869. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36870. var matricesIndex = parsedGeometry.matricesIndices[i];
  36871. floatIndices.push(matricesIndex & 0x000000FF);
  36872. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36873. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36874. floatIndices.push(matricesIndex >> 24);
  36875. }
  36876. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  36877. }
  36878. else {
  36879. delete parsedGeometry.matricesIndices._isExpanded;
  36880. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  36881. }
  36882. }
  36883. if (parsedGeometry.matricesIndicesExtra) {
  36884. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36885. var floatIndices = [];
  36886. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36887. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36888. floatIndices.push(matricesIndex & 0x000000FF);
  36889. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36890. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36891. floatIndices.push(matricesIndex >> 24);
  36892. }
  36893. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  36894. }
  36895. else {
  36896. delete parsedGeometry.matricesIndices._isExpanded;
  36897. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  36898. }
  36899. }
  36900. if (parsedGeometry.matricesWeights) {
  36901. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  36902. }
  36903. if (parsedGeometry.matricesWeightsExtra) {
  36904. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  36905. }
  36906. mesh.setIndices(parsedGeometry.indices);
  36907. }
  36908. // SubMeshes
  36909. if (parsedGeometry.subMeshes) {
  36910. mesh.subMeshes = [];
  36911. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36912. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36913. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36914. }
  36915. }
  36916. // Flat shading
  36917. if (mesh._shouldGenerateFlatShading) {
  36918. mesh.convertToFlatShadedMesh();
  36919. delete mesh._shouldGenerateFlatShading;
  36920. }
  36921. // Update
  36922. mesh.computeWorldMatrix(true);
  36923. // Octree
  36924. if (scene['_selectionOctree']) {
  36925. scene['_selectionOctree'].addMesh(mesh);
  36926. }
  36927. };
  36928. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36929. if (scene.getGeometryByID(parsedVertexData.id)) {
  36930. return null; // null since geometry could be something else than a box...
  36931. }
  36932. var geometry = new Geometry(parsedVertexData.id, scene);
  36933. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36934. if (parsedVertexData.delayLoadingFile) {
  36935. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36936. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36937. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36938. geometry._delayInfo = [];
  36939. if (parsedVertexData.hasUVs) {
  36940. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36941. }
  36942. if (parsedVertexData.hasUVs2) {
  36943. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36944. }
  36945. if (parsedVertexData.hasUVs3) {
  36946. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36947. }
  36948. if (parsedVertexData.hasUVs4) {
  36949. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36950. }
  36951. if (parsedVertexData.hasUVs5) {
  36952. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36953. }
  36954. if (parsedVertexData.hasUVs6) {
  36955. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36956. }
  36957. if (parsedVertexData.hasColors) {
  36958. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36959. }
  36960. if (parsedVertexData.hasMatricesIndices) {
  36961. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36962. }
  36963. if (parsedVertexData.hasMatricesWeights) {
  36964. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36965. }
  36966. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36967. }
  36968. else {
  36969. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36970. }
  36971. scene.pushGeometry(geometry, true);
  36972. return geometry;
  36973. };
  36974. return Geometry;
  36975. }());
  36976. BABYLON.Geometry = Geometry;
  36977. /////// Primitives //////////////////////////////////////////////
  36978. (function (Geometry) {
  36979. var Primitives;
  36980. (function (Primitives) {
  36981. /// Abstract class
  36982. var _Primitive = (function (_super) {
  36983. __extends(_Primitive, _super);
  36984. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  36985. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  36986. _this._canBeRegenerated = _canBeRegenerated;
  36987. _this._beingRegenerated = true;
  36988. _this.regenerate();
  36989. _this._beingRegenerated = false;
  36990. return _this;
  36991. }
  36992. _Primitive.prototype.canBeRegenerated = function () {
  36993. return this._canBeRegenerated;
  36994. };
  36995. _Primitive.prototype.regenerate = function () {
  36996. if (!this._canBeRegenerated) {
  36997. return;
  36998. }
  36999. this._beingRegenerated = true;
  37000. this.setAllVerticesData(this._regenerateVertexData(), false);
  37001. this._beingRegenerated = false;
  37002. };
  37003. _Primitive.prototype.asNewGeometry = function (id) {
  37004. return _super.prototype.copy.call(this, id);
  37005. };
  37006. // overrides
  37007. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  37008. if (!this._beingRegenerated) {
  37009. return;
  37010. }
  37011. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  37012. };
  37013. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  37014. if (!this._beingRegenerated) {
  37015. return;
  37016. }
  37017. _super.prototype.setVerticesData.call(this, kind, data, false);
  37018. };
  37019. // to override
  37020. // protected
  37021. _Primitive.prototype._regenerateVertexData = function () {
  37022. throw new Error("Abstract method");
  37023. };
  37024. _Primitive.prototype.copy = function (id) {
  37025. throw new Error("Must be overriden in sub-classes.");
  37026. };
  37027. _Primitive.prototype.serialize = function () {
  37028. var serializationObject = _super.prototype.serialize.call(this);
  37029. serializationObject.canBeRegenerated = this.canBeRegenerated();
  37030. return serializationObject;
  37031. };
  37032. return _Primitive;
  37033. }(Geometry));
  37034. Primitives._Primitive = _Primitive;
  37035. var Ribbon = (function (_super) {
  37036. __extends(Ribbon, _super);
  37037. // Members
  37038. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  37039. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37040. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37041. _this.pathArray = pathArray;
  37042. _this.closeArray = closeArray;
  37043. _this.closePath = closePath;
  37044. _this.offset = offset;
  37045. _this.side = side;
  37046. return _this;
  37047. }
  37048. Ribbon.prototype._regenerateVertexData = function () {
  37049. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  37050. };
  37051. Ribbon.prototype.copy = function (id) {
  37052. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  37053. };
  37054. return Ribbon;
  37055. }(_Primitive));
  37056. Primitives.Ribbon = Ribbon;
  37057. var Box = (function (_super) {
  37058. __extends(Box, _super);
  37059. // Members
  37060. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  37061. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37062. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37063. _this.size = size;
  37064. _this.side = side;
  37065. return _this;
  37066. }
  37067. Box.prototype._regenerateVertexData = function () {
  37068. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  37069. };
  37070. Box.prototype.copy = function (id) {
  37071. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  37072. };
  37073. Box.prototype.serialize = function () {
  37074. var serializationObject = _super.prototype.serialize.call(this);
  37075. serializationObject.size = this.size;
  37076. return serializationObject;
  37077. };
  37078. Box.Parse = function (parsedBox, scene) {
  37079. if (scene.getGeometryByID(parsedBox.id)) {
  37080. return null; // null since geometry could be something else than a box...
  37081. }
  37082. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  37083. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  37084. scene.pushGeometry(box, true);
  37085. return box;
  37086. };
  37087. return Box;
  37088. }(_Primitive));
  37089. Primitives.Box = Box;
  37090. var Sphere = (function (_super) {
  37091. __extends(Sphere, _super);
  37092. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  37093. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37094. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37095. _this.segments = segments;
  37096. _this.diameter = diameter;
  37097. _this.side = side;
  37098. return _this;
  37099. }
  37100. Sphere.prototype._regenerateVertexData = function () {
  37101. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  37102. };
  37103. Sphere.prototype.copy = function (id) {
  37104. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  37105. };
  37106. Sphere.prototype.serialize = function () {
  37107. var serializationObject = _super.prototype.serialize.call(this);
  37108. serializationObject.segments = this.segments;
  37109. serializationObject.diameter = this.diameter;
  37110. return serializationObject;
  37111. };
  37112. Sphere.Parse = function (parsedSphere, scene) {
  37113. if (scene.getGeometryByID(parsedSphere.id)) {
  37114. return null; // null since geometry could be something else than a sphere...
  37115. }
  37116. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  37117. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  37118. scene.pushGeometry(sphere, true);
  37119. return sphere;
  37120. };
  37121. return Sphere;
  37122. }(_Primitive));
  37123. Primitives.Sphere = Sphere;
  37124. var Disc = (function (_super) {
  37125. __extends(Disc, _super);
  37126. // Members
  37127. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  37128. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37129. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37130. _this.radius = radius;
  37131. _this.tessellation = tessellation;
  37132. _this.side = side;
  37133. return _this;
  37134. }
  37135. Disc.prototype._regenerateVertexData = function () {
  37136. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  37137. };
  37138. Disc.prototype.copy = function (id) {
  37139. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  37140. };
  37141. return Disc;
  37142. }(_Primitive));
  37143. Primitives.Disc = Disc;
  37144. var Cylinder = (function (_super) {
  37145. __extends(Cylinder, _super);
  37146. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  37147. if (subdivisions === void 0) { subdivisions = 1; }
  37148. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37149. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37150. _this.height = height;
  37151. _this.diameterTop = diameterTop;
  37152. _this.diameterBottom = diameterBottom;
  37153. _this.tessellation = tessellation;
  37154. _this.subdivisions = subdivisions;
  37155. _this.side = side;
  37156. return _this;
  37157. }
  37158. Cylinder.prototype._regenerateVertexData = function () {
  37159. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  37160. };
  37161. Cylinder.prototype.copy = function (id) {
  37162. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  37163. };
  37164. Cylinder.prototype.serialize = function () {
  37165. var serializationObject = _super.prototype.serialize.call(this);
  37166. serializationObject.height = this.height;
  37167. serializationObject.diameterTop = this.diameterTop;
  37168. serializationObject.diameterBottom = this.diameterBottom;
  37169. serializationObject.tessellation = this.tessellation;
  37170. return serializationObject;
  37171. };
  37172. Cylinder.Parse = function (parsedCylinder, scene) {
  37173. if (scene.getGeometryByID(parsedCylinder.id)) {
  37174. return null; // null since geometry could be something else than a cylinder...
  37175. }
  37176. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  37177. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  37178. scene.pushGeometry(cylinder, true);
  37179. return cylinder;
  37180. };
  37181. return Cylinder;
  37182. }(_Primitive));
  37183. Primitives.Cylinder = Cylinder;
  37184. var Torus = (function (_super) {
  37185. __extends(Torus, _super);
  37186. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  37187. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37188. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37189. _this.diameter = diameter;
  37190. _this.thickness = thickness;
  37191. _this.tessellation = tessellation;
  37192. _this.side = side;
  37193. return _this;
  37194. }
  37195. Torus.prototype._regenerateVertexData = function () {
  37196. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  37197. };
  37198. Torus.prototype.copy = function (id) {
  37199. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  37200. };
  37201. Torus.prototype.serialize = function () {
  37202. var serializationObject = _super.prototype.serialize.call(this);
  37203. serializationObject.diameter = this.diameter;
  37204. serializationObject.thickness = this.thickness;
  37205. serializationObject.tessellation = this.tessellation;
  37206. return serializationObject;
  37207. };
  37208. Torus.Parse = function (parsedTorus, scene) {
  37209. if (scene.getGeometryByID(parsedTorus.id)) {
  37210. return null; // null since geometry could be something else than a torus...
  37211. }
  37212. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  37213. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  37214. scene.pushGeometry(torus, true);
  37215. return torus;
  37216. };
  37217. return Torus;
  37218. }(_Primitive));
  37219. Primitives.Torus = Torus;
  37220. var Ground = (function (_super) {
  37221. __extends(Ground, _super);
  37222. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  37223. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37224. _this.width = width;
  37225. _this.height = height;
  37226. _this.subdivisions = subdivisions;
  37227. return _this;
  37228. }
  37229. Ground.prototype._regenerateVertexData = function () {
  37230. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  37231. };
  37232. Ground.prototype.copy = function (id) {
  37233. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  37234. };
  37235. Ground.prototype.serialize = function () {
  37236. var serializationObject = _super.prototype.serialize.call(this);
  37237. serializationObject.width = this.width;
  37238. serializationObject.height = this.height;
  37239. serializationObject.subdivisions = this.subdivisions;
  37240. return serializationObject;
  37241. };
  37242. Ground.Parse = function (parsedGround, scene) {
  37243. if (scene.getGeometryByID(parsedGround.id)) {
  37244. return null; // null since geometry could be something else than a ground...
  37245. }
  37246. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  37247. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  37248. scene.pushGeometry(ground, true);
  37249. return ground;
  37250. };
  37251. return Ground;
  37252. }(_Primitive));
  37253. Primitives.Ground = Ground;
  37254. var TiledGround = (function (_super) {
  37255. __extends(TiledGround, _super);
  37256. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  37257. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37258. _this.xmin = xmin;
  37259. _this.zmin = zmin;
  37260. _this.xmax = xmax;
  37261. _this.zmax = zmax;
  37262. _this.subdivisions = subdivisions;
  37263. _this.precision = precision;
  37264. return _this;
  37265. }
  37266. TiledGround.prototype._regenerateVertexData = function () {
  37267. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  37268. };
  37269. TiledGround.prototype.copy = function (id) {
  37270. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  37271. };
  37272. return TiledGround;
  37273. }(_Primitive));
  37274. Primitives.TiledGround = TiledGround;
  37275. var Plane = (function (_super) {
  37276. __extends(Plane, _super);
  37277. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  37278. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37279. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37280. _this.size = size;
  37281. _this.side = side;
  37282. return _this;
  37283. }
  37284. Plane.prototype._regenerateVertexData = function () {
  37285. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  37286. };
  37287. Plane.prototype.copy = function (id) {
  37288. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  37289. };
  37290. Plane.prototype.serialize = function () {
  37291. var serializationObject = _super.prototype.serialize.call(this);
  37292. serializationObject.size = this.size;
  37293. return serializationObject;
  37294. };
  37295. Plane.Parse = function (parsedPlane, scene) {
  37296. if (scene.getGeometryByID(parsedPlane.id)) {
  37297. return null; // null since geometry could be something else than a ground...
  37298. }
  37299. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  37300. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  37301. scene.pushGeometry(plane, true);
  37302. return plane;
  37303. };
  37304. return Plane;
  37305. }(_Primitive));
  37306. Primitives.Plane = Plane;
  37307. var TorusKnot = (function (_super) {
  37308. __extends(TorusKnot, _super);
  37309. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  37310. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37311. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37312. _this.radius = radius;
  37313. _this.tube = tube;
  37314. _this.radialSegments = radialSegments;
  37315. _this.tubularSegments = tubularSegments;
  37316. _this.p = p;
  37317. _this.q = q;
  37318. _this.side = side;
  37319. return _this;
  37320. }
  37321. TorusKnot.prototype._regenerateVertexData = function () {
  37322. 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 });
  37323. };
  37324. TorusKnot.prototype.copy = function (id) {
  37325. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  37326. };
  37327. TorusKnot.prototype.serialize = function () {
  37328. var serializationObject = _super.prototype.serialize.call(this);
  37329. serializationObject.radius = this.radius;
  37330. serializationObject.tube = this.tube;
  37331. serializationObject.radialSegments = this.radialSegments;
  37332. serializationObject.tubularSegments = this.tubularSegments;
  37333. serializationObject.p = this.p;
  37334. serializationObject.q = this.q;
  37335. return serializationObject;
  37336. };
  37337. ;
  37338. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  37339. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37340. return null; // null since geometry could be something else than a ground...
  37341. }
  37342. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37343. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37344. scene.pushGeometry(torusKnot, true);
  37345. return torusKnot;
  37346. };
  37347. return TorusKnot;
  37348. }(_Primitive));
  37349. Primitives.TorusKnot = TorusKnot;
  37350. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  37351. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  37352. })(BABYLON || (BABYLON = {}));
  37353. //# sourceMappingURL=babylon.geometry.js.map
  37354. var BABYLON;
  37355. (function (BABYLON) {
  37356. var GroundMesh = (function (_super) {
  37357. __extends(GroundMesh, _super);
  37358. function GroundMesh(name, scene) {
  37359. var _this = _super.call(this, name, scene) || this;
  37360. _this.generateOctree = false;
  37361. _this._worldInverse = new BABYLON.Matrix();
  37362. return _this;
  37363. }
  37364. GroundMesh.prototype.getClassName = function () {
  37365. return "GroundMesh";
  37366. };
  37367. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  37368. get: function () {
  37369. return Math.min(this._subdivisionsX, this._subdivisionsY);
  37370. },
  37371. enumerable: true,
  37372. configurable: true
  37373. });
  37374. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  37375. get: function () {
  37376. return this._subdivisionsX;
  37377. },
  37378. enumerable: true,
  37379. configurable: true
  37380. });
  37381. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  37382. get: function () {
  37383. return this._subdivisionsY;
  37384. },
  37385. enumerable: true,
  37386. configurable: true
  37387. });
  37388. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  37389. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  37390. this._subdivisionsX = chunksCount;
  37391. this._subdivisionsY = chunksCount;
  37392. this.subdivide(chunksCount);
  37393. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  37394. };
  37395. /**
  37396. * Returns a height (y) value in the Worl system :
  37397. * the ground altitude at the coordinates (x, z) expressed in the World system.
  37398. * Returns the ground y position if (x, z) are outside the ground surface.
  37399. * Not pertinent if the ground is rotated.
  37400. */
  37401. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  37402. // express x and y in the ground local system
  37403. x -= this.position.x;
  37404. z -= this.position.z;
  37405. x /= this.scaling.x;
  37406. z /= this.scaling.z;
  37407. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37408. return this.position.y;
  37409. }
  37410. if (!this._heightQuads || this._heightQuads.length == 0) {
  37411. this._initHeightQuads();
  37412. this._computeHeightQuads();
  37413. }
  37414. var facet = this._getFacetAt(x, z);
  37415. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  37416. // return y in the World system
  37417. return y * this.scaling.y + this.position.y;
  37418. };
  37419. /**
  37420. * Returns a normalized vector (Vector3) orthogonal to the ground
  37421. * at the ground coordinates (x, z) expressed in the World system.
  37422. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  37423. * Not pertinent if the ground is rotated.
  37424. */
  37425. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  37426. var normal = new BABYLON.Vector3(0, 1, 0);
  37427. this.getNormalAtCoordinatesToRef(x, z, normal);
  37428. return normal;
  37429. };
  37430. /**
  37431. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  37432. * at the ground coordinates (x, z) expressed in the World system.
  37433. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  37434. * Not pertinent if the ground is rotated.
  37435. */
  37436. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  37437. // express x and y in the ground local system
  37438. x -= this.position.x;
  37439. z -= this.position.z;
  37440. x /= this.scaling.x;
  37441. z /= this.scaling.z;
  37442. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37443. return;
  37444. }
  37445. if (!this._heightQuads || this._heightQuads.length == 0) {
  37446. this._initHeightQuads();
  37447. this._computeHeightQuads();
  37448. }
  37449. var facet = this._getFacetAt(x, z);
  37450. ref.x = facet.x;
  37451. ref.y = facet.y;
  37452. ref.z = facet.z;
  37453. };
  37454. /**
  37455. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  37456. * if the ground has been updated.
  37457. * This can be used in the render loop
  37458. */
  37459. GroundMesh.prototype.updateCoordinateHeights = function () {
  37460. if (!this._heightQuads || this._heightQuads.length == 0) {
  37461. this._initHeightQuads();
  37462. }
  37463. this._computeHeightQuads();
  37464. };
  37465. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  37466. GroundMesh.prototype._getFacetAt = function (x, z) {
  37467. // retrieve col and row from x, z coordinates in the ground local system
  37468. var subdivisionsX = this._subdivisionsX;
  37469. var subdivisionsY = this._subdivisionsY;
  37470. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  37471. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  37472. var quad = this._heightQuads[row * this._subdivisionsX + col];
  37473. var facet;
  37474. if (z < quad.slope.x * x + quad.slope.y) {
  37475. facet = quad.facet1;
  37476. }
  37477. else {
  37478. facet = quad.facet2;
  37479. }
  37480. return facet;
  37481. };
  37482. // Creates and populates the heightMap array with "facet" elements :
  37483. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  37484. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37485. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37486. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37487. GroundMesh.prototype._initHeightQuads = function () {
  37488. var subdivisionsX = this._subdivisionsX;
  37489. var subdivisionsY = this._subdivisionsY;
  37490. this._heightQuads = new Array();
  37491. for (var row = 0; row < subdivisionsY; row++) {
  37492. for (var col = 0; col < subdivisionsX; col++) {
  37493. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  37494. this._heightQuads[row * subdivisionsX + col] = quad;
  37495. }
  37496. }
  37497. };
  37498. // Compute each quad element values and update the the heightMap array :
  37499. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37500. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37501. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37502. GroundMesh.prototype._computeHeightQuads = function () {
  37503. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37504. var v1 = BABYLON.Tmp.Vector3[3];
  37505. var v2 = BABYLON.Tmp.Vector3[2];
  37506. var v3 = BABYLON.Tmp.Vector3[1];
  37507. var v4 = BABYLON.Tmp.Vector3[0];
  37508. var v1v2 = BABYLON.Tmp.Vector3[4];
  37509. var v1v3 = BABYLON.Tmp.Vector3[5];
  37510. var v1v4 = BABYLON.Tmp.Vector3[6];
  37511. var norm1 = BABYLON.Tmp.Vector3[7];
  37512. var norm2 = BABYLON.Tmp.Vector3[8];
  37513. var i = 0;
  37514. var j = 0;
  37515. var k = 0;
  37516. var cd = 0; // 2D slope coefficient : z = cd * x + h
  37517. var h = 0;
  37518. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  37519. var d2 = 0;
  37520. var subdivisionsX = this._subdivisionsX;
  37521. var subdivisionsY = this._subdivisionsY;
  37522. for (var row = 0; row < subdivisionsY; row++) {
  37523. for (var col = 0; col < subdivisionsX; col++) {
  37524. i = col * 3;
  37525. j = row * (subdivisionsX + 1) * 3;
  37526. k = (row + 1) * (subdivisionsX + 1) * 3;
  37527. v1.x = positions[j + i];
  37528. v1.y = positions[j + i + 1];
  37529. v1.z = positions[j + i + 2];
  37530. v2.x = positions[j + i + 3];
  37531. v2.y = positions[j + i + 4];
  37532. v2.z = positions[j + i + 5];
  37533. v3.x = positions[k + i];
  37534. v3.y = positions[k + i + 1];
  37535. v3.z = positions[k + i + 2];
  37536. v4.x = positions[k + i + 3];
  37537. v4.y = positions[k + i + 4];
  37538. v4.z = positions[k + i + 5];
  37539. // 2D slope V1V4
  37540. cd = (v4.z - v1.z) / (v4.x - v1.x);
  37541. h = v1.z - cd * v1.x; // v1 belongs to the slope
  37542. // facet equations :
  37543. // we compute each facet normal vector
  37544. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  37545. // we compute the value d by applying the equation to v1 which belongs to the plane
  37546. // then we store the facet equation in a Vector4
  37547. v2.subtractToRef(v1, v1v2);
  37548. v3.subtractToRef(v1, v1v3);
  37549. v4.subtractToRef(v1, v1v4);
  37550. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  37551. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  37552. norm1.normalize();
  37553. norm2.normalize();
  37554. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  37555. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  37556. var quad = this._heightQuads[row * subdivisionsX + col];
  37557. quad.slope.copyFromFloats(cd, h);
  37558. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  37559. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  37560. }
  37561. }
  37562. };
  37563. return GroundMesh;
  37564. }(BABYLON.Mesh));
  37565. BABYLON.GroundMesh = GroundMesh;
  37566. })(BABYLON || (BABYLON = {}));
  37567. //# sourceMappingURL=babylon.groundMesh.js.map
  37568. var BABYLON;
  37569. (function (BABYLON) {
  37570. var LinesMesh = (function (_super) {
  37571. __extends(LinesMesh, _super);
  37572. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  37573. if (parent === void 0) { parent = null; }
  37574. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  37575. _this.color = new BABYLON.Color3(1, 1, 1);
  37576. _this.alpha = 1;
  37577. _this._positionBuffer = {};
  37578. if (source) {
  37579. _this.color = source.color.clone();
  37580. _this.alpha = source.alpha;
  37581. }
  37582. _this._intersectionThreshold = 0.1;
  37583. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  37584. attributes: [BABYLON.VertexBuffer.PositionKind],
  37585. uniforms: ["worldViewProjection", "color"],
  37586. needAlphaBlending: true
  37587. });
  37588. _this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  37589. return _this;
  37590. }
  37591. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  37592. /**
  37593. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  37594. * This margin is expressed in world space coordinates, so its value may vary.
  37595. * Default value is 0.1
  37596. * @returns the intersection Threshold value.
  37597. */
  37598. get: function () {
  37599. return this._intersectionThreshold;
  37600. },
  37601. /**
  37602. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  37603. * This margin is expressed in world space coordinates, so its value may vary.
  37604. * @param value the new threshold to apply
  37605. */
  37606. set: function (value) {
  37607. if (this._intersectionThreshold === value) {
  37608. return;
  37609. }
  37610. this._intersectionThreshold = value;
  37611. if (this.geometry) {
  37612. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  37613. }
  37614. },
  37615. enumerable: true,
  37616. configurable: true
  37617. });
  37618. LinesMesh.prototype.getClassName = function () {
  37619. return "LinesMesh";
  37620. };
  37621. Object.defineProperty(LinesMesh.prototype, "material", {
  37622. get: function () {
  37623. return this._colorShader;
  37624. },
  37625. enumerable: true,
  37626. configurable: true
  37627. });
  37628. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  37629. get: function () {
  37630. return false;
  37631. },
  37632. enumerable: true,
  37633. configurable: true
  37634. });
  37635. LinesMesh.prototype.createInstance = function (name) {
  37636. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  37637. return null;
  37638. };
  37639. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  37640. var engine = this.getScene().getEngine();
  37641. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  37642. // VBOs
  37643. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  37644. // Color
  37645. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  37646. };
  37647. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  37648. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  37649. return;
  37650. }
  37651. var engine = this.getScene().getEngine();
  37652. // Draw order
  37653. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  37654. };
  37655. LinesMesh.prototype.dispose = function (doNotRecurse) {
  37656. this._colorShader.dispose();
  37657. _super.prototype.dispose.call(this, doNotRecurse);
  37658. };
  37659. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  37660. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  37661. };
  37662. return LinesMesh;
  37663. }(BABYLON.Mesh));
  37664. BABYLON.LinesMesh = LinesMesh;
  37665. })(BABYLON || (BABYLON = {}));
  37666. //# sourceMappingURL=babylon.linesMesh.js.map
  37667. var BABYLON;
  37668. (function (BABYLON) {
  37669. var DefaultLoadingScreen = (function () {
  37670. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  37671. if (_loadingText === void 0) { _loadingText = ""; }
  37672. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  37673. var _this = this;
  37674. this._renderingCanvas = _renderingCanvas;
  37675. this._loadingText = _loadingText;
  37676. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  37677. // Resize
  37678. this._resizeLoadingUI = function () {
  37679. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  37680. _this._loadingDiv.style.position = "absolute";
  37681. _this._loadingDiv.style.left = canvasRect.left + "px";
  37682. _this._loadingDiv.style.top = canvasRect.top + "px";
  37683. _this._loadingDiv.style.width = canvasRect.width + "px";
  37684. _this._loadingDiv.style.height = canvasRect.height + "px";
  37685. };
  37686. }
  37687. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  37688. var _this = this;
  37689. if (this._loadingDiv) {
  37690. // Do not add a loading screen if there is already one
  37691. return;
  37692. }
  37693. this._loadingDiv = document.createElement("div");
  37694. this._loadingDiv.id = "babylonjsLoadingDiv";
  37695. this._loadingDiv.style.opacity = "0";
  37696. this._loadingDiv.style.transition = "opacity 1.5s ease";
  37697. // Loading text
  37698. this._loadingTextDiv = document.createElement("div");
  37699. this._loadingTextDiv.style.position = "absolute";
  37700. this._loadingTextDiv.style.left = "0";
  37701. this._loadingTextDiv.style.top = "50%";
  37702. this._loadingTextDiv.style.marginTop = "80px";
  37703. this._loadingTextDiv.style.width = "100%";
  37704. this._loadingTextDiv.style.height = "20px";
  37705. this._loadingTextDiv.style.fontFamily = "Arial";
  37706. this._loadingTextDiv.style.fontSize = "14px";
  37707. this._loadingTextDiv.style.color = "white";
  37708. this._loadingTextDiv.style.textAlign = "center";
  37709. this._loadingTextDiv.innerHTML = "Loading";
  37710. this._loadingDiv.appendChild(this._loadingTextDiv);
  37711. //set the predefined text
  37712. this._loadingTextDiv.innerHTML = this._loadingText;
  37713. // Loading img
  37714. var imgBack = new Image();
  37715. 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==";
  37716. imgBack.style.position = "absolute";
  37717. imgBack.style.left = "50%";
  37718. imgBack.style.top = "50%";
  37719. imgBack.style.marginLeft = "-50px";
  37720. imgBack.style.marginTop = "-50px";
  37721. imgBack.style.transition = "transform 1.0s ease";
  37722. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  37723. var deg = 360;
  37724. var onTransitionEnd = function () {
  37725. deg += 360;
  37726. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  37727. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  37728. };
  37729. imgBack.addEventListener("transitionend", onTransitionEnd);
  37730. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  37731. this._loadingDiv.appendChild(imgBack);
  37732. // front image
  37733. var imgFront = new Image();
  37734. 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=";
  37735. imgFront.style.position = "absolute";
  37736. imgFront.style.left = "50%";
  37737. imgFront.style.top = "50%";
  37738. imgFront.style.marginLeft = "-50px";
  37739. imgFront.style.marginTop = "-50px";
  37740. this._loadingDiv.appendChild(imgFront);
  37741. this._resizeLoadingUI();
  37742. window.addEventListener("resize", this._resizeLoadingUI);
  37743. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  37744. document.body.appendChild(this._loadingDiv);
  37745. setTimeout(function () {
  37746. _this._loadingDiv.style.opacity = "1";
  37747. imgBack.style.transform = "rotateZ(360deg)";
  37748. imgBack.style.webkitTransform = "rotateZ(360deg)";
  37749. }, 0);
  37750. };
  37751. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  37752. var _this = this;
  37753. if (!this._loadingDiv) {
  37754. return;
  37755. }
  37756. var onTransitionEnd = function () {
  37757. if (!_this._loadingDiv) {
  37758. return;
  37759. }
  37760. document.body.removeChild(_this._loadingDiv);
  37761. window.removeEventListener("resize", _this._resizeLoadingUI);
  37762. _this._loadingDiv = null;
  37763. };
  37764. this._loadingDiv.style.opacity = "0";
  37765. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  37766. };
  37767. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  37768. set: function (text) {
  37769. this._loadingText = text;
  37770. if (this._loadingTextDiv) {
  37771. this._loadingTextDiv.innerHTML = this._loadingText;
  37772. }
  37773. },
  37774. enumerable: true,
  37775. configurable: true
  37776. });
  37777. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  37778. get: function () {
  37779. return this._loadingDivBackgroundColor;
  37780. },
  37781. set: function (color) {
  37782. this._loadingDivBackgroundColor = color;
  37783. if (!this._loadingDiv) {
  37784. return;
  37785. }
  37786. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  37787. },
  37788. enumerable: true,
  37789. configurable: true
  37790. });
  37791. return DefaultLoadingScreen;
  37792. }());
  37793. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  37794. })(BABYLON || (BABYLON = {}));
  37795. //# sourceMappingURL=babylon.loadingScreen.js.map
  37796. var BABYLON;
  37797. (function (BABYLON) {
  37798. var AudioEngine = (function () {
  37799. function AudioEngine() {
  37800. this._audioContext = null;
  37801. this._audioContextInitialized = false;
  37802. this.canUseWebAudio = false;
  37803. this.WarnedWebAudioUnsupported = false;
  37804. this.unlocked = false;
  37805. this.isMP3supported = false;
  37806. this.isOGGsupported = false;
  37807. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  37808. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  37809. this.canUseWebAudio = true;
  37810. }
  37811. var audioElem = document.createElement('audio');
  37812. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  37813. this.isMP3supported = true;
  37814. }
  37815. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  37816. this.isOGGsupported = true;
  37817. }
  37818. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  37819. this._unlockiOSaudio();
  37820. }
  37821. else {
  37822. this.unlocked = true;
  37823. }
  37824. }
  37825. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  37826. get: function () {
  37827. if (!this._audioContextInitialized) {
  37828. this._initializeAudioContext();
  37829. }
  37830. return this._audioContext;
  37831. },
  37832. enumerable: true,
  37833. configurable: true
  37834. });
  37835. AudioEngine.prototype._unlockiOSaudio = function () {
  37836. var _this = this;
  37837. var unlockaudio = function () {
  37838. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  37839. var source = _this.audioContext.createBufferSource();
  37840. source.buffer = buffer;
  37841. source.connect(_this.audioContext.destination);
  37842. source.start(0);
  37843. setTimeout(function () {
  37844. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  37845. _this.unlocked = true;
  37846. window.removeEventListener('touchend', unlockaudio, false);
  37847. if (_this.onAudioUnlocked) {
  37848. _this.onAudioUnlocked();
  37849. }
  37850. }
  37851. }, 0);
  37852. };
  37853. window.addEventListener('touchend', unlockaudio, false);
  37854. };
  37855. AudioEngine.prototype._initializeAudioContext = function () {
  37856. try {
  37857. if (this.canUseWebAudio) {
  37858. this._audioContext = new AudioContext();
  37859. // create a global volume gain node
  37860. this.masterGain = this._audioContext.createGain();
  37861. this.masterGain.gain.value = 1;
  37862. this.masterGain.connect(this._audioContext.destination);
  37863. this._audioContextInitialized = true;
  37864. }
  37865. }
  37866. catch (e) {
  37867. this.canUseWebAudio = false;
  37868. BABYLON.Tools.Error("Web Audio: " + e.message);
  37869. }
  37870. };
  37871. AudioEngine.prototype.dispose = function () {
  37872. if (this.canUseWebAudio && this._audioContextInitialized) {
  37873. if (this._connectedAnalyser) {
  37874. this._connectedAnalyser.stopDebugCanvas();
  37875. this._connectedAnalyser.dispose();
  37876. this.masterGain.disconnect();
  37877. this.masterGain.connect(this._audioContext.destination);
  37878. this._connectedAnalyser = null;
  37879. }
  37880. this.masterGain.gain.value = 1;
  37881. }
  37882. this.WarnedWebAudioUnsupported = false;
  37883. };
  37884. AudioEngine.prototype.getGlobalVolume = function () {
  37885. if (this.canUseWebAudio && this._audioContextInitialized) {
  37886. return this.masterGain.gain.value;
  37887. }
  37888. else {
  37889. return -1;
  37890. }
  37891. };
  37892. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  37893. if (this.canUseWebAudio && this._audioContextInitialized) {
  37894. this.masterGain.gain.value = newVolume;
  37895. }
  37896. };
  37897. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  37898. if (this._connectedAnalyser) {
  37899. this._connectedAnalyser.stopDebugCanvas();
  37900. }
  37901. if (this.canUseWebAudio && this._audioContextInitialized) {
  37902. this._connectedAnalyser = analyser;
  37903. this.masterGain.disconnect();
  37904. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  37905. }
  37906. };
  37907. return AudioEngine;
  37908. }());
  37909. BABYLON.AudioEngine = AudioEngine;
  37910. })(BABYLON || (BABYLON = {}));
  37911. //# sourceMappingURL=babylon.audioEngine.js.map
  37912. var BABYLON;
  37913. (function (BABYLON) {
  37914. var Sound = (function () {
  37915. /**
  37916. * Create a sound and attach it to a scene
  37917. * @param name Name of your sound
  37918. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  37919. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  37920. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  37921. */
  37922. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  37923. var _this = this;
  37924. this.autoplay = false;
  37925. this.loop = false;
  37926. this.useCustomAttenuation = false;
  37927. this.spatialSound = false;
  37928. this.refDistance = 1;
  37929. this.rolloffFactor = 1;
  37930. this.maxDistance = 100;
  37931. this.distanceModel = "linear";
  37932. this._panningModel = "equalpower";
  37933. this._playbackRate = 1;
  37934. this._streaming = false;
  37935. this._startTime = 0;
  37936. this._startOffset = 0;
  37937. this._position = BABYLON.Vector3.Zero();
  37938. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  37939. this._volume = 1;
  37940. this._isLoaded = false;
  37941. this._isReadyToPlay = false;
  37942. this.isPlaying = false;
  37943. this.isPaused = false;
  37944. this._isDirectional = false;
  37945. // Used if you'd like to create a directional sound.
  37946. // If not set, the sound will be omnidirectional
  37947. this._coneInnerAngle = 360;
  37948. this._coneOuterAngle = 360;
  37949. this._coneOuterGain = 0;
  37950. this._isOutputConnected = false;
  37951. this._urlType = "Unknown";
  37952. this.name = name;
  37953. this._scene = scene;
  37954. this._readyToPlayCallback = readyToPlayCallback;
  37955. // Default custom attenuation function is a linear attenuation
  37956. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  37957. if (currentDistance < maxDistance) {
  37958. return currentVolume * (1 - currentDistance / maxDistance);
  37959. }
  37960. else {
  37961. return 0;
  37962. }
  37963. };
  37964. if (options) {
  37965. this.autoplay = options.autoplay || false;
  37966. this.loop = options.loop || false;
  37967. // if volume === 0, we need another way to check this option
  37968. if (options.volume !== undefined) {
  37969. this._volume = options.volume;
  37970. }
  37971. this.spatialSound = options.spatialSound || false;
  37972. this.maxDistance = options.maxDistance || 100;
  37973. this.useCustomAttenuation = options.useCustomAttenuation || false;
  37974. this.rolloffFactor = options.rolloffFactor || 1;
  37975. this.refDistance = options.refDistance || 1;
  37976. this.distanceModel = options.distanceModel || "linear";
  37977. this._playbackRate = options.playbackRate || 1;
  37978. this._streaming = options.streaming || false;
  37979. }
  37980. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37981. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  37982. this._soundGain.gain.value = this._volume;
  37983. this._inputAudioNode = this._soundGain;
  37984. this._ouputAudioNode = this._soundGain;
  37985. if (this.spatialSound) {
  37986. this._createSpatialParameters();
  37987. }
  37988. this._scene.mainSoundTrack.AddSound(this);
  37989. var validParameter = true;
  37990. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  37991. if (urlOrArrayBuffer) {
  37992. if (typeof (urlOrArrayBuffer) === "string")
  37993. this._urlType = "String";
  37994. if (Array.isArray(urlOrArrayBuffer))
  37995. this._urlType = "Array";
  37996. if (urlOrArrayBuffer instanceof ArrayBuffer)
  37997. this._urlType = "ArrayBuffer";
  37998. var urls = [];
  37999. var codecSupportedFound = false;
  38000. switch (this._urlType) {
  38001. case "ArrayBuffer":
  38002. if (urlOrArrayBuffer.byteLength > 0) {
  38003. codecSupportedFound = true;
  38004. this._soundLoaded(urlOrArrayBuffer);
  38005. }
  38006. break;
  38007. case "String":
  38008. urls.push(urlOrArrayBuffer);
  38009. case "Array":
  38010. if (urls.length === 0)
  38011. urls = urlOrArrayBuffer;
  38012. // If we found a supported format, we load it immediately and stop the loop
  38013. for (var i = 0; i < urls.length; i++) {
  38014. var url = urls[i];
  38015. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  38016. codecSupportedFound = true;
  38017. }
  38018. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  38019. codecSupportedFound = true;
  38020. }
  38021. if (url.indexOf(".wav", url.length - 4) !== -1) {
  38022. codecSupportedFound = true;
  38023. }
  38024. if (codecSupportedFound) {
  38025. // Loading sound using XHR2
  38026. if (!this._streaming) {
  38027. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  38028. }
  38029. else {
  38030. this._htmlAudioElement = new Audio(url);
  38031. this._htmlAudioElement.controls = false;
  38032. this._htmlAudioElement.loop = this.loop;
  38033. this._htmlAudioElement.crossOrigin = "anonymous";
  38034. this._htmlAudioElement.preload = "auto";
  38035. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  38036. _this._isReadyToPlay = true;
  38037. if (_this.autoplay) {
  38038. _this.play();
  38039. }
  38040. if (_this._readyToPlayCallback) {
  38041. _this._readyToPlayCallback();
  38042. }
  38043. });
  38044. document.body.appendChild(this._htmlAudioElement);
  38045. }
  38046. break;
  38047. }
  38048. }
  38049. break;
  38050. default:
  38051. validParameter = false;
  38052. break;
  38053. }
  38054. if (!validParameter) {
  38055. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  38056. }
  38057. else {
  38058. if (!codecSupportedFound) {
  38059. this._isReadyToPlay = true;
  38060. // Simulating a ready to play event to avoid breaking code path
  38061. if (this._readyToPlayCallback) {
  38062. window.setTimeout(function () {
  38063. _this._readyToPlayCallback();
  38064. }, 1000);
  38065. }
  38066. }
  38067. }
  38068. }
  38069. }
  38070. else {
  38071. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  38072. this._scene.mainSoundTrack.AddSound(this);
  38073. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  38074. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  38075. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  38076. }
  38077. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  38078. if (this._readyToPlayCallback) {
  38079. window.setTimeout(function () {
  38080. _this._readyToPlayCallback();
  38081. }, 1000);
  38082. }
  38083. }
  38084. }
  38085. Sound.prototype.dispose = function () {
  38086. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  38087. if (this.isPlaying) {
  38088. this.stop();
  38089. }
  38090. this._isReadyToPlay = false;
  38091. if (this.soundTrackId === -1) {
  38092. this._scene.mainSoundTrack.RemoveSound(this);
  38093. }
  38094. else {
  38095. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  38096. }
  38097. if (this._soundGain) {
  38098. this._soundGain.disconnect();
  38099. this._soundGain = null;
  38100. }
  38101. if (this._soundPanner) {
  38102. this._soundPanner.disconnect();
  38103. this._soundPanner = null;
  38104. }
  38105. if (this._soundSource) {
  38106. this._soundSource.disconnect();
  38107. this._soundSource = null;
  38108. }
  38109. this._audioBuffer = null;
  38110. if (this._htmlAudioElement) {
  38111. this._htmlAudioElement.pause();
  38112. this._htmlAudioElement.src = "";
  38113. document.body.removeChild(this._htmlAudioElement);
  38114. }
  38115. if (this._connectedMesh) {
  38116. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  38117. this._connectedMesh = null;
  38118. }
  38119. }
  38120. };
  38121. Sound.prototype._soundLoaded = function (audioData) {
  38122. var _this = this;
  38123. this._isLoaded = true;
  38124. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  38125. _this._audioBuffer = buffer;
  38126. _this._isReadyToPlay = true;
  38127. if (_this.autoplay) {
  38128. _this.play();
  38129. }
  38130. if (_this._readyToPlayCallback) {
  38131. _this._readyToPlayCallback();
  38132. }
  38133. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  38134. };
  38135. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  38136. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38137. this._audioBuffer = audioBuffer;
  38138. this._isReadyToPlay = true;
  38139. }
  38140. };
  38141. Sound.prototype.updateOptions = function (options) {
  38142. if (options) {
  38143. this.loop = options.loop || this.loop;
  38144. this.maxDistance = options.maxDistance || this.maxDistance;
  38145. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  38146. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  38147. this.refDistance = options.refDistance || this.refDistance;
  38148. this.distanceModel = options.distanceModel || this.distanceModel;
  38149. this._playbackRate = options.playbackRate || this._playbackRate;
  38150. this._updateSpatialParameters();
  38151. if (this.isPlaying) {
  38152. if (this._streaming) {
  38153. this._htmlAudioElement.playbackRate = this._playbackRate;
  38154. }
  38155. else {
  38156. this._soundSource.playbackRate.value = this._playbackRate;
  38157. }
  38158. }
  38159. }
  38160. };
  38161. Sound.prototype._createSpatialParameters = function () {
  38162. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38163. if (this._scene.headphone) {
  38164. this._panningModel = "HRTF";
  38165. }
  38166. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  38167. this._updateSpatialParameters();
  38168. this._soundPanner.connect(this._ouputAudioNode);
  38169. this._inputAudioNode = this._soundPanner;
  38170. }
  38171. };
  38172. Sound.prototype._updateSpatialParameters = function () {
  38173. if (this.spatialSound) {
  38174. if (this.useCustomAttenuation) {
  38175. // Tricks to disable in a way embedded Web Audio attenuation
  38176. this._soundPanner.distanceModel = "linear";
  38177. this._soundPanner.maxDistance = Number.MAX_VALUE;
  38178. this._soundPanner.refDistance = 1;
  38179. this._soundPanner.rolloffFactor = 1;
  38180. this._soundPanner.panningModel = this._panningModel;
  38181. }
  38182. else {
  38183. this._soundPanner.distanceModel = this.distanceModel;
  38184. this._soundPanner.maxDistance = this.maxDistance;
  38185. this._soundPanner.refDistance = this.refDistance;
  38186. this._soundPanner.rolloffFactor = this.rolloffFactor;
  38187. this._soundPanner.panningModel = this._panningModel;
  38188. }
  38189. }
  38190. };
  38191. Sound.prototype.switchPanningModelToHRTF = function () {
  38192. this._panningModel = "HRTF";
  38193. this._switchPanningModel();
  38194. };
  38195. Sound.prototype.switchPanningModelToEqualPower = function () {
  38196. this._panningModel = "equalpower";
  38197. this._switchPanningModel();
  38198. };
  38199. Sound.prototype._switchPanningModel = function () {
  38200. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  38201. this._soundPanner.panningModel = this._panningModel;
  38202. }
  38203. };
  38204. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  38205. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38206. if (this._isOutputConnected) {
  38207. this._ouputAudioNode.disconnect();
  38208. }
  38209. this._ouputAudioNode.connect(soundTrackAudioNode);
  38210. this._isOutputConnected = true;
  38211. }
  38212. };
  38213. /**
  38214. * Transform this sound into a directional source
  38215. * @param coneInnerAngle Size of the inner cone in degree
  38216. * @param coneOuterAngle Size of the outer cone in degree
  38217. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  38218. */
  38219. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  38220. if (coneOuterAngle < coneInnerAngle) {
  38221. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  38222. return;
  38223. }
  38224. this._coneInnerAngle = coneInnerAngle;
  38225. this._coneOuterAngle = coneOuterAngle;
  38226. this._coneOuterGain = coneOuterGain;
  38227. this._isDirectional = true;
  38228. if (this.isPlaying && this.loop) {
  38229. this.stop();
  38230. this.play();
  38231. }
  38232. };
  38233. Sound.prototype.setPosition = function (newPosition) {
  38234. this._position = newPosition;
  38235. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  38236. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  38237. }
  38238. };
  38239. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  38240. this._localDirection = newLocalDirection;
  38241. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  38242. this._updateDirection();
  38243. }
  38244. };
  38245. Sound.prototype._updateDirection = function () {
  38246. var mat = this._connectedMesh.getWorldMatrix();
  38247. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  38248. direction.normalize();
  38249. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  38250. };
  38251. Sound.prototype.updateDistanceFromListener = function () {
  38252. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  38253. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  38254. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  38255. }
  38256. };
  38257. Sound.prototype.setAttenuationFunction = function (callback) {
  38258. this._customAttenuationFunction = callback;
  38259. };
  38260. /**
  38261. * Play the sound
  38262. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  38263. * @param offset (optional) Start the sound setting it at a specific time
  38264. */
  38265. Sound.prototype.play = function (time, offset) {
  38266. var _this = this;
  38267. if (this._isReadyToPlay && this._scene.audioEnabled) {
  38268. try {
  38269. if (this._startOffset < 0) {
  38270. time = -this._startOffset;
  38271. this._startOffset = 0;
  38272. }
  38273. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  38274. if (!this._soundSource || !this._streamingSource) {
  38275. if (this.spatialSound) {
  38276. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  38277. if (this._isDirectional) {
  38278. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  38279. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  38280. this._soundPanner.coneOuterGain = this._coneOuterGain;
  38281. if (this._connectedMesh) {
  38282. this._updateDirection();
  38283. }
  38284. else {
  38285. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  38286. }
  38287. }
  38288. }
  38289. }
  38290. if (this._streaming) {
  38291. if (!this._streamingSource) {
  38292. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  38293. this._htmlAudioElement.onended = function () { _this._onended(); };
  38294. this._htmlAudioElement.playbackRate = this._playbackRate;
  38295. }
  38296. this._streamingSource.disconnect();
  38297. this._streamingSource.connect(this._inputAudioNode);
  38298. this._htmlAudioElement.play();
  38299. }
  38300. else {
  38301. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  38302. this._soundSource.buffer = this._audioBuffer;
  38303. this._soundSource.connect(this._inputAudioNode);
  38304. this._soundSource.loop = this.loop;
  38305. this._soundSource.playbackRate.value = this._playbackRate;
  38306. this._soundSource.onended = function () { _this._onended(); };
  38307. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  38308. }
  38309. this._startTime = startTime;
  38310. this.isPlaying = true;
  38311. this.isPaused = false;
  38312. }
  38313. catch (ex) {
  38314. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  38315. }
  38316. }
  38317. };
  38318. Sound.prototype._onended = function () {
  38319. this.isPlaying = false;
  38320. if (this.onended) {
  38321. this.onended();
  38322. }
  38323. };
  38324. /**
  38325. * Stop the sound
  38326. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  38327. */
  38328. Sound.prototype.stop = function (time) {
  38329. if (this.isPlaying) {
  38330. if (this._streaming) {
  38331. this._htmlAudioElement.pause();
  38332. // Test needed for Firefox or it will generate an Invalid State Error
  38333. if (this._htmlAudioElement.currentTime > 0) {
  38334. this._htmlAudioElement.currentTime = 0;
  38335. }
  38336. }
  38337. else {
  38338. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  38339. this._soundSource.stop(stopTime);
  38340. this._soundSource.onended = null;
  38341. if (!this.isPaused) {
  38342. this._startOffset = 0;
  38343. }
  38344. }
  38345. this.isPlaying = false;
  38346. }
  38347. };
  38348. Sound.prototype.pause = function () {
  38349. if (this.isPlaying) {
  38350. this.isPaused = true;
  38351. if (this._streaming) {
  38352. this._htmlAudioElement.pause();
  38353. }
  38354. else {
  38355. this.stop(0);
  38356. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  38357. }
  38358. }
  38359. };
  38360. Sound.prototype.setVolume = function (newVolume, time) {
  38361. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38362. if (time) {
  38363. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  38364. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  38365. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  38366. }
  38367. else {
  38368. this._soundGain.gain.value = newVolume;
  38369. }
  38370. }
  38371. this._volume = newVolume;
  38372. };
  38373. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  38374. this._playbackRate = newPlaybackRate;
  38375. if (this.isPlaying) {
  38376. if (this._streaming) {
  38377. this._htmlAudioElement.playbackRate = this._playbackRate;
  38378. }
  38379. else {
  38380. this._soundSource.playbackRate.value = this._playbackRate;
  38381. }
  38382. }
  38383. };
  38384. Sound.prototype.getVolume = function () {
  38385. return this._volume;
  38386. };
  38387. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  38388. var _this = this;
  38389. if (this._connectedMesh) {
  38390. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  38391. this._registerFunc = null;
  38392. }
  38393. this._connectedMesh = meshToConnectTo;
  38394. if (!this.spatialSound) {
  38395. this.spatialSound = true;
  38396. this._createSpatialParameters();
  38397. if (this.isPlaying && this.loop) {
  38398. this.stop();
  38399. this.play();
  38400. }
  38401. }
  38402. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  38403. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  38404. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  38405. };
  38406. Sound.prototype.detachFromMesh = function () {
  38407. if (this._connectedMesh) {
  38408. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  38409. this._registerFunc = null;
  38410. this._connectedMesh = null;
  38411. }
  38412. };
  38413. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  38414. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  38415. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  38416. this._updateDirection();
  38417. }
  38418. };
  38419. Sound.prototype.clone = function () {
  38420. var _this = this;
  38421. if (!this._streaming) {
  38422. var setBufferAndRun = function () {
  38423. if (_this._isReadyToPlay) {
  38424. clonedSound._audioBuffer = _this.getAudioBuffer();
  38425. clonedSound._isReadyToPlay = true;
  38426. if (clonedSound.autoplay) {
  38427. clonedSound.play();
  38428. }
  38429. }
  38430. else {
  38431. window.setTimeout(setBufferAndRun, 300);
  38432. }
  38433. };
  38434. var currentOptions = {
  38435. autoplay: this.autoplay, loop: this.loop,
  38436. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  38437. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  38438. refDistance: this.refDistance, distanceModel: this.distanceModel
  38439. };
  38440. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  38441. if (this.useCustomAttenuation) {
  38442. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  38443. }
  38444. clonedSound.setPosition(this._position);
  38445. clonedSound.setPlaybackRate(this._playbackRate);
  38446. setBufferAndRun();
  38447. return clonedSound;
  38448. }
  38449. else {
  38450. return null;
  38451. }
  38452. };
  38453. Sound.prototype.getAudioBuffer = function () {
  38454. return this._audioBuffer;
  38455. };
  38456. Sound.prototype.serialize = function () {
  38457. var serializationObject = {
  38458. name: this.name,
  38459. url: this.name,
  38460. autoplay: this.autoplay,
  38461. loop: this.loop,
  38462. volume: this._volume,
  38463. spatialSound: this.spatialSound,
  38464. maxDistance: this.maxDistance,
  38465. rolloffFactor: this.rolloffFactor,
  38466. refDistance: this.refDistance,
  38467. distanceModel: this.distanceModel,
  38468. playbackRate: this._playbackRate,
  38469. panningModel: this._panningModel,
  38470. soundTrackId: this.soundTrackId
  38471. };
  38472. if (this.spatialSound) {
  38473. if (this._connectedMesh)
  38474. serializationObject.connectedMeshId = this._connectedMesh.id;
  38475. serializationObject.position = this._position.asArray();
  38476. serializationObject.refDistance = this.refDistance;
  38477. serializationObject.distanceModel = this.distanceModel;
  38478. serializationObject.isDirectional = this._isDirectional;
  38479. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  38480. serializationObject.coneInnerAngle = this._coneInnerAngle;
  38481. serializationObject.coneOuterAngle = this._coneOuterAngle;
  38482. serializationObject.coneOuterGain = this._coneOuterGain;
  38483. }
  38484. return serializationObject;
  38485. };
  38486. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  38487. var soundName = parsedSound.name;
  38488. var soundUrl;
  38489. if (parsedSound.url) {
  38490. soundUrl = rootUrl + parsedSound.url;
  38491. }
  38492. else {
  38493. soundUrl = rootUrl + soundName;
  38494. }
  38495. var options = {
  38496. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  38497. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  38498. rolloffFactor: parsedSound.rolloffFactor,
  38499. refDistance: parsedSound.refDistance,
  38500. distanceModel: parsedSound.distanceModel,
  38501. playbackRate: parsedSound.playbackRate
  38502. };
  38503. var newSound;
  38504. if (!sourceSound) {
  38505. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  38506. scene._addPendingData(newSound);
  38507. }
  38508. else {
  38509. var setBufferAndRun = function () {
  38510. if (sourceSound._isReadyToPlay) {
  38511. newSound._audioBuffer = sourceSound.getAudioBuffer();
  38512. newSound._isReadyToPlay = true;
  38513. if (newSound.autoplay) {
  38514. newSound.play();
  38515. }
  38516. }
  38517. else {
  38518. window.setTimeout(setBufferAndRun, 300);
  38519. }
  38520. };
  38521. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  38522. setBufferAndRun();
  38523. }
  38524. if (parsedSound.position) {
  38525. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  38526. newSound.setPosition(soundPosition);
  38527. }
  38528. if (parsedSound.isDirectional) {
  38529. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  38530. if (parsedSound.localDirectionToMesh) {
  38531. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  38532. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  38533. }
  38534. }
  38535. if (parsedSound.connectedMeshId) {
  38536. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  38537. if (connectedMesh) {
  38538. newSound.attachToMesh(connectedMesh);
  38539. }
  38540. }
  38541. return newSound;
  38542. };
  38543. return Sound;
  38544. }());
  38545. BABYLON.Sound = Sound;
  38546. })(BABYLON || (BABYLON = {}));
  38547. //# sourceMappingURL=babylon.sound.js.map
  38548. var BABYLON;
  38549. (function (BABYLON) {
  38550. var SoundTrack = (function () {
  38551. function SoundTrack(scene, options) {
  38552. this.id = -1;
  38553. this._isMainTrack = false;
  38554. this._isInitialized = false;
  38555. this._scene = scene;
  38556. this.soundCollection = new Array();
  38557. this._options = options;
  38558. if (!this._isMainTrack) {
  38559. this._scene.soundTracks.push(this);
  38560. this.id = this._scene.soundTracks.length - 1;
  38561. }
  38562. }
  38563. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  38564. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38565. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  38566. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  38567. if (this._options) {
  38568. if (this._options.volume) {
  38569. this._outputAudioNode.gain.value = this._options.volume;
  38570. }
  38571. if (this._options.mainTrack) {
  38572. this._isMainTrack = this._options.mainTrack;
  38573. }
  38574. }
  38575. this._isInitialized = true;
  38576. }
  38577. };
  38578. SoundTrack.prototype.dispose = function () {
  38579. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38580. if (this._connectedAnalyser) {
  38581. this._connectedAnalyser.stopDebugCanvas();
  38582. }
  38583. while (this.soundCollection.length) {
  38584. this.soundCollection[0].dispose();
  38585. }
  38586. if (this._outputAudioNode) {
  38587. this._outputAudioNode.disconnect();
  38588. }
  38589. this._outputAudioNode = null;
  38590. }
  38591. };
  38592. SoundTrack.prototype.AddSound = function (sound) {
  38593. if (!this._isInitialized) {
  38594. this._initializeSoundTrackAudioGraph();
  38595. }
  38596. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38597. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  38598. }
  38599. if (sound.soundTrackId) {
  38600. if (sound.soundTrackId === -1) {
  38601. this._scene.mainSoundTrack.RemoveSound(sound);
  38602. }
  38603. else {
  38604. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  38605. }
  38606. }
  38607. this.soundCollection.push(sound);
  38608. sound.soundTrackId = this.id;
  38609. };
  38610. SoundTrack.prototype.RemoveSound = function (sound) {
  38611. var index = this.soundCollection.indexOf(sound);
  38612. if (index !== -1) {
  38613. this.soundCollection.splice(index, 1);
  38614. }
  38615. };
  38616. SoundTrack.prototype.setVolume = function (newVolume) {
  38617. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38618. this._outputAudioNode.gain.value = newVolume;
  38619. }
  38620. };
  38621. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  38622. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38623. for (var i = 0; i < this.soundCollection.length; i++) {
  38624. this.soundCollection[i].switchPanningModelToHRTF();
  38625. }
  38626. }
  38627. };
  38628. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  38629. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38630. for (var i = 0; i < this.soundCollection.length; i++) {
  38631. this.soundCollection[i].switchPanningModelToEqualPower();
  38632. }
  38633. }
  38634. };
  38635. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  38636. if (this._connectedAnalyser) {
  38637. this._connectedAnalyser.stopDebugCanvas();
  38638. }
  38639. this._connectedAnalyser = analyser;
  38640. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38641. this._outputAudioNode.disconnect();
  38642. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  38643. }
  38644. };
  38645. return SoundTrack;
  38646. }());
  38647. BABYLON.SoundTrack = SoundTrack;
  38648. })(BABYLON || (BABYLON = {}));
  38649. //# sourceMappingURL=babylon.soundtrack.js.map
  38650. var BABYLON;
  38651. (function (BABYLON) {
  38652. /**
  38653. * Special Glow Blur post process only blurring the alpha channel
  38654. * It enforces keeping the most luminous color in the color channel.
  38655. */
  38656. var GlowBlurPostProcess = (function (_super) {
  38657. __extends(GlowBlurPostProcess, _super);
  38658. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  38659. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38660. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  38661. _this.direction = direction;
  38662. _this.blurWidth = blurWidth;
  38663. _this.onApplyObservable.add(function (effect) {
  38664. effect.setFloat2("screenSize", _this.width, _this.height);
  38665. effect.setVector2("direction", _this.direction);
  38666. effect.setFloat("blurWidth", _this.blurWidth);
  38667. });
  38668. return _this;
  38669. }
  38670. return GlowBlurPostProcess;
  38671. }(BABYLON.PostProcess));
  38672. /**
  38673. * The highlight layer Helps adding a glow effect around a mesh.
  38674. *
  38675. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  38676. * glowy meshes to your scene.
  38677. *
  38678. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  38679. */
  38680. var HighlightLayer = (function () {
  38681. /**
  38682. * Instantiates a new highlight Layer and references it to the scene..
  38683. * @param name The name of the layer
  38684. * @param scene The scene to use the layer in
  38685. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  38686. */
  38687. function HighlightLayer(name, scene, options) {
  38688. this._vertexBuffers = {};
  38689. this._mainTextureDesiredSize = { width: 0, height: 0 };
  38690. this._meshes = {};
  38691. this._maxSize = 0;
  38692. this._shouldRender = false;
  38693. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  38694. this._excludedMeshes = {};
  38695. /**
  38696. * Specifies whether or not the inner glow is ACTIVE in the layer.
  38697. */
  38698. this.innerGlow = true;
  38699. /**
  38700. * Specifies whether or not the outer glow is ACTIVE in the layer.
  38701. */
  38702. this.outerGlow = true;
  38703. /**
  38704. * Specifies wether the highlight layer is enabled or not.
  38705. */
  38706. this.isEnabled = true;
  38707. /**
  38708. * An event triggered when the highlight layer has been disposed.
  38709. * @type {BABYLON.Observable}
  38710. */
  38711. this.onDisposeObservable = new BABYLON.Observable();
  38712. /**
  38713. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  38714. * @type {BABYLON.Observable}
  38715. */
  38716. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  38717. /**
  38718. * An event triggered when the highlight layer is being blurred.
  38719. * @type {BABYLON.Observable}
  38720. */
  38721. this.onBeforeBlurObservable = new BABYLON.Observable();
  38722. /**
  38723. * An event triggered when the highlight layer has been blurred.
  38724. * @type {BABYLON.Observable}
  38725. */
  38726. this.onAfterBlurObservable = new BABYLON.Observable();
  38727. /**
  38728. * An event triggered when the glowing blurred texture is being merged in the scene.
  38729. * @type {BABYLON.Observable}
  38730. */
  38731. this.onBeforeComposeObservable = new BABYLON.Observable();
  38732. /**
  38733. * An event triggered when the glowing blurred texture has been merged in the scene.
  38734. * @type {BABYLON.Observable}
  38735. */
  38736. this.onAfterComposeObservable = new BABYLON.Observable();
  38737. /**
  38738. * An event triggered when the highlight layer changes its size.
  38739. * @type {BABYLON.Observable}
  38740. */
  38741. this.onSizeChangedObservable = new BABYLON.Observable();
  38742. this._scene = scene;
  38743. var engine = scene.getEngine();
  38744. this._engine = engine;
  38745. this._maxSize = this._engine.getCaps().maxTextureSize;
  38746. this._scene.highlightLayers.push(this);
  38747. // Warn on stencil.
  38748. if (!this._engine.isStencilEnable) {
  38749. 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 }");
  38750. }
  38751. // Adapt options
  38752. this._options = options || {
  38753. mainTextureRatio: 0.25,
  38754. blurTextureSizeRatio: 0.5,
  38755. blurHorizontalSize: 1,
  38756. blurVerticalSize: 1,
  38757. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  38758. };
  38759. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  38760. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  38761. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  38762. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  38763. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  38764. // VBO
  38765. var vertices = [];
  38766. vertices.push(1, 1);
  38767. vertices.push(-1, 1);
  38768. vertices.push(-1, -1);
  38769. vertices.push(1, -1);
  38770. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  38771. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  38772. // Indices
  38773. var indices = [];
  38774. indices.push(0);
  38775. indices.push(1);
  38776. indices.push(2);
  38777. indices.push(0);
  38778. indices.push(2);
  38779. indices.push(3);
  38780. this._indexBuffer = engine.createIndexBuffer(indices);
  38781. // Effect
  38782. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  38783. // Render target
  38784. this.setMainTextureSize();
  38785. // Create Textures and post processes
  38786. this.createTextureAndPostProcesses();
  38787. }
  38788. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  38789. /**
  38790. * Gets the horizontal size of the blur.
  38791. */
  38792. get: function () {
  38793. return this._horizontalBlurPostprocess.blurWidth;
  38794. },
  38795. /**
  38796. * Specifies the horizontal size of the blur.
  38797. */
  38798. set: function (value) {
  38799. this._horizontalBlurPostprocess.blurWidth = value;
  38800. },
  38801. enumerable: true,
  38802. configurable: true
  38803. });
  38804. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  38805. /**
  38806. * Gets the vertical size of the blur.
  38807. */
  38808. get: function () {
  38809. return this._verticalBlurPostprocess.blurWidth;
  38810. },
  38811. /**
  38812. * Specifies the vertical size of the blur.
  38813. */
  38814. set: function (value) {
  38815. this._verticalBlurPostprocess.blurWidth = value;
  38816. },
  38817. enumerable: true,
  38818. configurable: true
  38819. });
  38820. Object.defineProperty(HighlightLayer.prototype, "camera", {
  38821. /**
  38822. * Gets the camera attached to the layer.
  38823. */
  38824. get: function () {
  38825. return this._options.camera;
  38826. },
  38827. enumerable: true,
  38828. configurable: true
  38829. });
  38830. /**
  38831. * Creates the render target textures and post processes used in the highlight layer.
  38832. */
  38833. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  38834. var _this = this;
  38835. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  38836. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  38837. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  38838. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  38839. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  38840. width: this._mainTextureDesiredSize.width,
  38841. height: this._mainTextureDesiredSize.height
  38842. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  38843. this._mainTexture.activeCamera = this._options.camera;
  38844. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38845. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38846. this._mainTexture.anisotropicFilteringLevel = 1;
  38847. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38848. this._mainTexture.renderParticles = false;
  38849. this._mainTexture.renderList = null;
  38850. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  38851. width: blurTextureWidth,
  38852. height: blurTextureHeight
  38853. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  38854. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38855. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38856. this._blurTexture.anisotropicFilteringLevel = 16;
  38857. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  38858. this._blurTexture.renderParticles = false;
  38859. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38860. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  38861. effect.setTexture("textureSampler", _this._mainTexture);
  38862. });
  38863. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  38864. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38865. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  38866. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38867. });
  38868. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38869. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  38870. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38871. });
  38872. }
  38873. else {
  38874. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38875. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  38876. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38877. });
  38878. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38879. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  38880. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38881. });
  38882. }
  38883. this._mainTexture.onAfterUnbindObservable.add(function () {
  38884. _this.onBeforeBlurObservable.notifyObservers(_this);
  38885. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  38886. _this.onAfterBlurObservable.notifyObservers(_this);
  38887. });
  38888. // Custom render function
  38889. var renderSubMesh = function (subMesh) {
  38890. var mesh = subMesh.getRenderingMesh();
  38891. var scene = _this._scene;
  38892. var engine = scene.getEngine();
  38893. // Culling
  38894. engine.setState(subMesh.getMaterial().backFaceCulling);
  38895. // Managing instances
  38896. var batch = mesh._getInstancesRenderList(subMesh._id);
  38897. if (batch.mustReturn) {
  38898. return;
  38899. }
  38900. // Excluded Mesh
  38901. if (_this._excludedMeshes[mesh.uniqueId]) {
  38902. return;
  38903. }
  38904. ;
  38905. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  38906. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  38907. var material = subMesh.getMaterial();
  38908. var emissiveTexture = null;
  38909. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  38910. emissiveTexture = material.emissiveTexture;
  38911. }
  38912. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  38913. engine.enableEffect(_this._glowMapGenerationEffect);
  38914. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  38915. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  38916. if (highlightLayerMesh) {
  38917. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  38918. }
  38919. else {
  38920. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  38921. }
  38922. // Alpha test
  38923. if (material && material.needAlphaTesting()) {
  38924. var alphaTexture = material.getAlphaTestTexture();
  38925. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  38926. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  38927. }
  38928. // Glow emissive only
  38929. if (emissiveTexture) {
  38930. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  38931. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  38932. }
  38933. // Bones
  38934. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38935. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  38936. }
  38937. // Draw
  38938. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  38939. }
  38940. else {
  38941. // Need to reset refresh rate of the shadowMap
  38942. _this._mainTexture.resetRefreshCounter();
  38943. }
  38944. };
  38945. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  38946. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  38947. var index;
  38948. for (index = 0; index < opaqueSubMeshes.length; index++) {
  38949. renderSubMesh(opaqueSubMeshes.data[index]);
  38950. }
  38951. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  38952. renderSubMesh(alphaTestSubMeshes.data[index]);
  38953. }
  38954. for (index = 0; index < transparentSubMeshes.length; index++) {
  38955. renderSubMesh(transparentSubMeshes.data[index]);
  38956. }
  38957. };
  38958. this._mainTexture.onClearObservable.add(function (engine) {
  38959. engine.clear(HighlightLayer.neutralColor, true, true, true);
  38960. });
  38961. };
  38962. /**
  38963. * Checks for the readiness of the element composing the layer.
  38964. * @param subMesh the mesh to check for
  38965. * @param useInstances specify wether or not to use instances to render the mesh
  38966. * @param emissiveTexture the associated emissive texture used to generate the glow
  38967. * @return true if ready otherwise, false
  38968. */
  38969. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  38970. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  38971. return false;
  38972. }
  38973. var defines = [];
  38974. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38975. var mesh = subMesh.getMesh();
  38976. var material = subMesh.getMaterial();
  38977. var uv1 = false;
  38978. var uv2 = false;
  38979. // Alpha test
  38980. if (material && material.needAlphaTesting()) {
  38981. var alphaTexture = material.getAlphaTestTexture();
  38982. if (alphaTexture) {
  38983. defines.push("#define ALPHATEST");
  38984. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  38985. alphaTexture.coordinatesIndex === 1) {
  38986. defines.push("#define DIFFUSEUV2");
  38987. uv2 = true;
  38988. }
  38989. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38990. defines.push("#define DIFFUSEUV1");
  38991. uv1 = true;
  38992. }
  38993. }
  38994. }
  38995. // Emissive
  38996. if (emissiveTexture) {
  38997. defines.push("#define EMISSIVE");
  38998. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  38999. emissiveTexture.coordinatesIndex === 1) {
  39000. defines.push("#define EMISSIVEUV2");
  39001. uv2 = true;
  39002. }
  39003. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39004. defines.push("#define EMISSIVEUV1");
  39005. uv1 = true;
  39006. }
  39007. }
  39008. if (uv1) {
  39009. attribs.push(BABYLON.VertexBuffer.UVKind);
  39010. defines.push("#define UV1");
  39011. }
  39012. if (uv2) {
  39013. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39014. defines.push("#define UV2");
  39015. }
  39016. // Bones
  39017. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39018. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39019. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39020. if (mesh.numBoneInfluencers > 4) {
  39021. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39022. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39023. }
  39024. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39025. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39026. }
  39027. else {
  39028. defines.push("#define NUM_BONE_INFLUENCERS 0");
  39029. }
  39030. // Instances
  39031. if (useInstances) {
  39032. defines.push("#define INSTANCES");
  39033. attribs.push("world0");
  39034. attribs.push("world1");
  39035. attribs.push("world2");
  39036. attribs.push("world3");
  39037. }
  39038. // Get correct effect
  39039. var join = defines.join("\n");
  39040. if (this._cachedDefines !== join) {
  39041. this._cachedDefines = join;
  39042. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  39043. }
  39044. return this._glowMapGenerationEffect.isReady();
  39045. };
  39046. /**
  39047. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  39048. */
  39049. HighlightLayer.prototype.render = function () {
  39050. var currentEffect = this._glowMapMergeEffect;
  39051. // Check
  39052. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  39053. return;
  39054. var engine = this._scene.getEngine();
  39055. this.onBeforeComposeObservable.notifyObservers(this);
  39056. // Render
  39057. engine.enableEffect(currentEffect);
  39058. engine.setState(false);
  39059. // Cache
  39060. var previousStencilBuffer = engine.getStencilBuffer();
  39061. var previousStencilFunction = engine.getStencilFunction();
  39062. var previousStencilMask = engine.getStencilMask();
  39063. var previousAlphaMode = engine.getAlphaMode();
  39064. // Texture
  39065. currentEffect.setTexture("textureSampler", this._blurTexture);
  39066. // VBOs
  39067. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  39068. // Draw order
  39069. engine.setAlphaMode(this._options.alphaBlendingMode);
  39070. engine.setStencilMask(0x00);
  39071. engine.setStencilBuffer(true);
  39072. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  39073. if (this.outerGlow) {
  39074. currentEffect.setFloat("offset", 0);
  39075. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  39076. engine.draw(true, 0, 6);
  39077. }
  39078. if (this.innerGlow) {
  39079. currentEffect.setFloat("offset", 1);
  39080. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  39081. engine.draw(true, 0, 6);
  39082. }
  39083. // Restore Cache
  39084. engine.setStencilFunction(previousStencilFunction);
  39085. engine.setStencilMask(previousStencilMask);
  39086. engine.setAlphaMode(previousAlphaMode);
  39087. engine.setStencilBuffer(previousStencilBuffer);
  39088. this.onAfterComposeObservable.notifyObservers(this);
  39089. // Handle size changes.
  39090. var size = this._mainTexture.getSize();
  39091. this.setMainTextureSize();
  39092. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  39093. // Recreate RTT and post processes on size change.
  39094. this.onSizeChangedObservable.notifyObservers(this);
  39095. this.disposeTextureAndPostProcesses();
  39096. this.createTextureAndPostProcesses();
  39097. }
  39098. };
  39099. /**
  39100. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  39101. * @param mesh The mesh to exclude from the highlight layer
  39102. */
  39103. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  39104. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  39105. if (!meshExcluded) {
  39106. this._excludedMeshes[mesh.uniqueId] = {
  39107. mesh: mesh,
  39108. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  39109. mesh.getEngine().setStencilBuffer(false);
  39110. }),
  39111. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  39112. mesh.getEngine().setStencilBuffer(true);
  39113. }),
  39114. };
  39115. }
  39116. };
  39117. /**
  39118. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  39119. * @param mesh The mesh to highlight
  39120. */
  39121. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  39122. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  39123. if (meshExcluded) {
  39124. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  39125. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  39126. }
  39127. this._excludedMeshes[mesh.uniqueId] = undefined;
  39128. };
  39129. /**
  39130. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  39131. * @param mesh The mesh to highlight
  39132. * @param color The color of the highlight
  39133. * @param glowEmissiveOnly Extract the glow from the emissive texture
  39134. */
  39135. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  39136. var _this = this;
  39137. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  39138. var meshHighlight = this._meshes[mesh.uniqueId];
  39139. if (meshHighlight) {
  39140. meshHighlight.color = color;
  39141. }
  39142. else {
  39143. this._meshes[mesh.uniqueId] = {
  39144. mesh: mesh,
  39145. color: color,
  39146. // Lambda required for capture due to Observable this context
  39147. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  39148. if (_this._excludedMeshes[mesh.uniqueId]) {
  39149. _this.defaultStencilReference(mesh);
  39150. }
  39151. else {
  39152. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  39153. }
  39154. }),
  39155. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  39156. glowEmissiveOnly: glowEmissiveOnly
  39157. };
  39158. }
  39159. this._shouldRender = true;
  39160. };
  39161. /**
  39162. * Remove a mesh from the highlight layer in order to make it stop glowing.
  39163. * @param mesh The mesh to highlight
  39164. */
  39165. HighlightLayer.prototype.removeMesh = function (mesh) {
  39166. var meshHighlight = this._meshes[mesh.uniqueId];
  39167. if (meshHighlight) {
  39168. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  39169. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  39170. }
  39171. this._meshes[mesh.uniqueId] = undefined;
  39172. this._shouldRender = false;
  39173. for (var meshHighlightToCheck in this._meshes) {
  39174. if (meshHighlightToCheck) {
  39175. this._shouldRender = true;
  39176. break;
  39177. }
  39178. }
  39179. };
  39180. /**
  39181. * Returns true if the layer contains information to display, otherwise false.
  39182. */
  39183. HighlightLayer.prototype.shouldRender = function () {
  39184. return this.isEnabled && this._shouldRender;
  39185. };
  39186. /**
  39187. * Sets the main texture desired size which is the closest power of two
  39188. * of the engine canvas size.
  39189. */
  39190. HighlightLayer.prototype.setMainTextureSize = function () {
  39191. if (this._options.mainTextureFixedSize) {
  39192. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  39193. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  39194. }
  39195. else {
  39196. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  39197. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  39198. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  39199. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  39200. }
  39201. };
  39202. /**
  39203. * Force the stencil to the normal expected value for none glowing parts
  39204. */
  39205. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  39206. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  39207. };
  39208. /**
  39209. * Dispose only the render target textures and post process.
  39210. */
  39211. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  39212. this._blurTexture.dispose();
  39213. this._mainTexture.dispose();
  39214. this._downSamplePostprocess.dispose();
  39215. this._horizontalBlurPostprocess.dispose();
  39216. this._verticalBlurPostprocess.dispose();
  39217. };
  39218. /**
  39219. * Dispose the highlight layer and free resources.
  39220. */
  39221. HighlightLayer.prototype.dispose = function () {
  39222. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  39223. if (vertexBuffer) {
  39224. vertexBuffer.dispose();
  39225. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  39226. }
  39227. if (this._indexBuffer) {
  39228. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39229. this._indexBuffer = null;
  39230. }
  39231. // Clean textures and post processes
  39232. this.disposeTextureAndPostProcesses();
  39233. // Clean mesh references
  39234. for (var id in this._meshes) {
  39235. var meshHighlight = this._meshes[id];
  39236. if (meshHighlight && meshHighlight.mesh) {
  39237. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  39238. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  39239. }
  39240. }
  39241. this._meshes = null;
  39242. for (var id in this._excludedMeshes) {
  39243. var meshHighlight = this._excludedMeshes[id];
  39244. if (meshHighlight) {
  39245. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  39246. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  39247. }
  39248. }
  39249. this._excludedMeshes = null;
  39250. // Remove from scene
  39251. var index = this._scene.highlightLayers.indexOf(this, 0);
  39252. if (index > -1) {
  39253. this._scene.highlightLayers.splice(index, 1);
  39254. }
  39255. // Callback
  39256. this.onDisposeObservable.notifyObservers(this);
  39257. this.onDisposeObservable.clear();
  39258. this.onBeforeRenderMainTextureObservable.clear();
  39259. this.onBeforeBlurObservable.clear();
  39260. this.onBeforeComposeObservable.clear();
  39261. this.onAfterComposeObservable.clear();
  39262. this.onSizeChangedObservable.clear();
  39263. };
  39264. return HighlightLayer;
  39265. }());
  39266. /**
  39267. * The neutral color used during the preparation of the glow effect.
  39268. * This is black by default as the blend operation is a blend operation.
  39269. */
  39270. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  39271. /**
  39272. * Stencil value used for glowing meshes.
  39273. */
  39274. HighlightLayer.glowingMeshStencilReference = 0x02;
  39275. /**
  39276. * Stencil value used for the other meshes in the scene.
  39277. */
  39278. HighlightLayer.normalMeshStencilReference = 0x01;
  39279. BABYLON.HighlightLayer = HighlightLayer;
  39280. })(BABYLON || (BABYLON = {}));
  39281. //# sourceMappingURL=babylon.highlightlayer.js.map
  39282. var BABYLON;
  39283. (function (BABYLON) {
  39284. var SIMDVector3 = (function () {
  39285. function SIMDVector3() {
  39286. }
  39287. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  39288. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  39289. };
  39290. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  39291. var m = transformation.m;
  39292. var m0 = SIMD.Float32x4.load(m, 0);
  39293. var m1 = SIMD.Float32x4.load(m, 4);
  39294. var m2 = SIMD.Float32x4.load(m, 8);
  39295. var m3 = SIMD.Float32x4.load(m, 12);
  39296. 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));
  39297. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  39298. result.x = SIMD.Float32x4.extractLane(r, 0);
  39299. result.y = SIMD.Float32x4.extractLane(r, 1);
  39300. result.z = SIMD.Float32x4.extractLane(r, 2);
  39301. };
  39302. return SIMDVector3;
  39303. }());
  39304. var SIMDMatrix = (function () {
  39305. function SIMDMatrix() {
  39306. }
  39307. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  39308. var tm = this.m;
  39309. var om = other.m;
  39310. var m0 = SIMD.Float32x4.load(om, 0);
  39311. var m1 = SIMD.Float32x4.load(om, 4);
  39312. var m2 = SIMD.Float32x4.load(om, 8);
  39313. var m3 = SIMD.Float32x4.load(om, 12);
  39314. for (var i = 0; i < 16; i += 4) {
  39315. 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)))));
  39316. }
  39317. return this;
  39318. };
  39319. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  39320. var src = this.m;
  39321. var dest = other.m;
  39322. // Load the 4 rows
  39323. var src0 = SIMD.Float32x4.load(src, 0);
  39324. var src1 = SIMD.Float32x4.load(src, 4);
  39325. var src2 = SIMD.Float32x4.load(src, 8);
  39326. var src3 = SIMD.Float32x4.load(src, 12);
  39327. // Transpose the source matrix. Sort of. Not a true transpose operation
  39328. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  39329. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  39330. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  39331. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  39332. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  39333. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  39334. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  39335. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  39336. // This is a true transposition, but it will lead to an incorrect result
  39337. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  39338. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  39339. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  39340. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  39341. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  39342. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  39343. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  39344. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  39345. // ----
  39346. tmp1 = SIMD.Float32x4.mul(row2, row3);
  39347. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39348. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  39349. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  39350. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39351. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  39352. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  39353. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  39354. // ----
  39355. tmp1 = SIMD.Float32x4.mul(row1, row2);
  39356. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39357. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  39358. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  39359. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39360. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  39361. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  39362. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  39363. // ----
  39364. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  39365. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39366. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  39367. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  39368. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  39369. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39370. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  39371. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  39372. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  39373. // ----
  39374. tmp1 = SIMD.Float32x4.mul(row0, row1);
  39375. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39376. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  39377. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  39378. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39379. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  39380. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  39381. // ----
  39382. tmp1 = SIMD.Float32x4.mul(row0, row3);
  39383. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39384. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  39385. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  39386. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39387. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  39388. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  39389. // ----
  39390. tmp1 = SIMD.Float32x4.mul(row0, row2);
  39391. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39392. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  39393. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  39394. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39395. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  39396. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  39397. // Compute determinant
  39398. var det = SIMD.Float32x4.mul(row0, minor0);
  39399. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  39400. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  39401. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  39402. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  39403. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  39404. // These shuffles aren't necessary if the faulty transposition is done
  39405. // up at the top of this function.
  39406. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  39407. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  39408. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  39409. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  39410. // Compute final values by multiplying with 1/det
  39411. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  39412. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  39413. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  39414. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  39415. return this;
  39416. };
  39417. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  39418. var out = result.m;
  39419. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  39420. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  39421. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  39422. // cc.kmVec3Subtract(f, pCenter, pEye);
  39423. var f = SIMD.Float32x4.sub(center, eye);
  39424. // cc.kmVec3Normalize(f, f);
  39425. var tmp = SIMD.Float32x4.mul(f, f);
  39426. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39427. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39428. // cc.kmVec3Assign(up, pUp);
  39429. // cc.kmVec3Normalize(up, up);
  39430. tmp = SIMD.Float32x4.mul(up, up);
  39431. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39432. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39433. // cc.kmVec3Cross(s, f, up);
  39434. 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)));
  39435. // cc.kmVec3Normalize(s, s);
  39436. tmp = SIMD.Float32x4.mul(s, s);
  39437. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39438. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39439. // cc.kmVec3Cross(u, s, f);
  39440. 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)));
  39441. // cc.kmVec3Normalize(s, s);
  39442. tmp = SIMD.Float32x4.mul(s, s);
  39443. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39444. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39445. var zero = SIMD.Float32x4.splat(0.0);
  39446. s = SIMD.Float32x4.neg(s);
  39447. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  39448. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  39449. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  39450. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  39451. 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);
  39452. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  39453. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  39454. 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)))));
  39455. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  39456. 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)))));
  39457. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  39458. 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)))));
  39459. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  39460. 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)))));
  39461. };
  39462. return SIMDMatrix;
  39463. }());
  39464. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  39465. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  39466. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  39467. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  39468. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  39469. var SIMDHelper = (function () {
  39470. function SIMDHelper() {
  39471. }
  39472. Object.defineProperty(SIMDHelper, "IsEnabled", {
  39473. get: function () {
  39474. return SIMDHelper._isEnabled;
  39475. },
  39476. enumerable: true,
  39477. configurable: true
  39478. });
  39479. SIMDHelper.DisableSIMD = function () {
  39480. // Replace functions
  39481. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  39482. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  39483. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  39484. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  39485. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  39486. SIMDHelper._isEnabled = false;
  39487. };
  39488. SIMDHelper.EnableSIMD = function () {
  39489. if (self.SIMD === undefined) {
  39490. return;
  39491. }
  39492. // check if polyfills needed
  39493. if (!self.Math.fround) {
  39494. self.Math.fround = (function (array) { return function (x) {
  39495. return array[0] = x, array[0];
  39496. }; })(new Float32Array(1));
  39497. }
  39498. if (!self.Math.imul) {
  39499. self.Math.imul = function (a, b) {
  39500. var ah = (a >>> 16) & 0xffff;
  39501. var al = a & 0xffff;
  39502. var bh = (b >>> 16) & 0xffff;
  39503. var bl = b & 0xffff;
  39504. // the shift by 0 fixes the sign on the high part
  39505. // the final |0 converts the unsigned value into a signed value
  39506. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  39507. };
  39508. }
  39509. // Replace functions
  39510. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  39511. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  39512. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  39513. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  39514. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  39515. SIMDHelper._isEnabled = true;
  39516. };
  39517. return SIMDHelper;
  39518. }());
  39519. SIMDHelper._isEnabled = false;
  39520. BABYLON.SIMDHelper = SIMDHelper;
  39521. })(BABYLON || (BABYLON = {}));
  39522. //# sourceMappingURL=babylon.math.SIMD.js.map
  39523. var BABYLON;
  39524. (function (BABYLON) {
  39525. /**
  39526. * This class describe a rectangle that were added to the map.
  39527. * You have access to its coordinates either in pixel or normalized (UV)
  39528. */
  39529. var PackedRect = (function () {
  39530. function PackedRect(root, parent, pos, size) {
  39531. this._pos = pos;
  39532. this._size = size;
  39533. this._root = root;
  39534. this._parent = parent;
  39535. this._contentSize = null;
  39536. this._bottomNode = null;
  39537. this._leftNode = null;
  39538. this._initialSize = null;
  39539. this._rightNode = null;
  39540. }
  39541. Object.defineProperty(PackedRect.prototype, "pos", {
  39542. /**
  39543. * @returns the position of this node into the map
  39544. */
  39545. get: function () {
  39546. return this._pos;
  39547. },
  39548. enumerable: true,
  39549. configurable: true
  39550. });
  39551. Object.defineProperty(PackedRect.prototype, "contentSize", {
  39552. /**
  39553. * @returns the size of the rectangle this node handles
  39554. */
  39555. get: function () {
  39556. return this._contentSize;
  39557. },
  39558. enumerable: true,
  39559. configurable: true
  39560. });
  39561. Object.defineProperty(PackedRect.prototype, "UVs", {
  39562. /**
  39563. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  39564. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  39565. */
  39566. get: function () {
  39567. return this.getUVsForCustomSize(this._root._size);
  39568. },
  39569. enumerable: true,
  39570. configurable: true
  39571. });
  39572. /**
  39573. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations) and then using only a part of the PackRect.
  39574. * This method will return the UVs for this part by given the custom size of what you really use
  39575. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  39576. */
  39577. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  39578. var mainWidth = this._root._size.width;
  39579. var mainHeight = this._root._size.height;
  39580. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  39581. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  39582. var uvs = new Array();
  39583. uvs.push(topLeft);
  39584. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  39585. uvs.push(rightBottom);
  39586. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  39587. return uvs;
  39588. };
  39589. /**
  39590. * Free this rectangle from the map.
  39591. * Call this method when you no longer need the rectangle to be in the map.
  39592. */
  39593. PackedRect.prototype.freeContent = function () {
  39594. if (!this.contentSize) {
  39595. return;
  39596. }
  39597. this._contentSize = null;
  39598. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  39599. this.attemptDefrag();
  39600. };
  39601. Object.defineProperty(PackedRect.prototype, "isUsed", {
  39602. get: function () {
  39603. return this._contentSize != null || this._leftNode != null;
  39604. },
  39605. enumerable: true,
  39606. configurable: true
  39607. });
  39608. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  39609. var node = this.findNode(contentSize);
  39610. // Not enough space...
  39611. if (!node) {
  39612. return null;
  39613. }
  39614. node.splitNode(contentSize);
  39615. return node;
  39616. };
  39617. PackedRect.prototype.findNode = function (size) {
  39618. var resNode = null;
  39619. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  39620. if (this.isUsed) {
  39621. if (this._leftNode) {
  39622. resNode = this._leftNode.findNode(size);
  39623. }
  39624. if (!resNode && this._rightNode) {
  39625. resNode = this._rightNode.findNode(size);
  39626. }
  39627. if (!resNode && this._bottomNode) {
  39628. resNode = this._bottomNode.findNode(size);
  39629. }
  39630. }
  39631. else if (this._initialSize) {
  39632. if ((size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  39633. resNode = this;
  39634. }
  39635. else {
  39636. return null;
  39637. }
  39638. }
  39639. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  39640. resNode = this;
  39641. }
  39642. return resNode;
  39643. };
  39644. PackedRect.prototype.splitNode = function (contentSize) {
  39645. // 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)
  39646. if (!this._contentSize && this._initialSize) {
  39647. this._contentSize = contentSize.clone();
  39648. 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));
  39649. return this._leftNode.splitNode(contentSize);
  39650. }
  39651. else {
  39652. this._contentSize = contentSize.clone();
  39653. this._initialSize = contentSize.clone();
  39654. if (contentSize.width !== this._size.width) {
  39655. this._rightNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x + contentSize.width, this._pos.y), new BABYLON.Size(this._size.width - contentSize.width, contentSize.height));
  39656. }
  39657. if (contentSize.height !== this._size.height) {
  39658. this._bottomNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y + contentSize.height), new BABYLON.Size(this._size.width, this._size.height - contentSize.height));
  39659. }
  39660. return this;
  39661. }
  39662. };
  39663. PackedRect.prototype.attemptDefrag = function () {
  39664. if (!this.isUsed && this.isRecursiveFree) {
  39665. this.clearNode();
  39666. if (this._parent) {
  39667. this._parent.attemptDefrag();
  39668. }
  39669. }
  39670. };
  39671. PackedRect.prototype.clearNode = function () {
  39672. this._initialSize = null;
  39673. this._rightNode = null;
  39674. this._bottomNode = null;
  39675. };
  39676. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  39677. get: function () {
  39678. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  39679. },
  39680. enumerable: true,
  39681. configurable: true
  39682. });
  39683. PackedRect.prototype.evalFreeSize = function (size) {
  39684. var levelSize = 0;
  39685. if (!this.isUsed) {
  39686. if (this._initialSize) {
  39687. levelSize = this._initialSize.surface;
  39688. }
  39689. else {
  39690. levelSize = this._size.surface;
  39691. }
  39692. }
  39693. if (this._rightNode) {
  39694. levelSize += this._rightNode.evalFreeSize(0);
  39695. }
  39696. if (this._bottomNode) {
  39697. levelSize += this._bottomNode.evalFreeSize(0);
  39698. }
  39699. return levelSize + size;
  39700. };
  39701. return PackedRect;
  39702. }());
  39703. BABYLON.PackedRect = PackedRect;
  39704. /**
  39705. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  39706. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  39707. * 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.
  39708. */
  39709. var RectPackingMap = (function (_super) {
  39710. __extends(RectPackingMap, _super);
  39711. /**
  39712. * Create an instance of the object with a dimension using the given size
  39713. * @param size The dimension of the rectangle that will contain all the sub ones.
  39714. */
  39715. function RectPackingMap(size) {
  39716. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  39717. _this._root = _this;
  39718. return _this;
  39719. }
  39720. /**
  39721. * Add a rectangle, finding the best location to store it into the map
  39722. * @param size the dimension of the rectangle to store
  39723. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  39724. */
  39725. RectPackingMap.prototype.addRect = function (size) {
  39726. var node = this.findAndSplitNode(size);
  39727. return node;
  39728. };
  39729. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  39730. /**
  39731. * Return the current space free normalized between [0;1]
  39732. * @returns {}
  39733. */
  39734. get: function () {
  39735. var freeSize = 0;
  39736. freeSize = this.evalFreeSize(freeSize);
  39737. return freeSize / (this._size.width * this._size.height);
  39738. },
  39739. enumerable: true,
  39740. configurable: true
  39741. });
  39742. return RectPackingMap;
  39743. }(PackedRect));
  39744. BABYLON.RectPackingMap = RectPackingMap;
  39745. })(BABYLON || (BABYLON = {}));
  39746. //# sourceMappingURL=babylon.rectPackingMap.js.map
  39747. var BABYLON;
  39748. (function (BABYLON) {
  39749. var DynamicFloatArrayElementInfo = (function () {
  39750. function DynamicFloatArrayElementInfo() {
  39751. }
  39752. return DynamicFloatArrayElementInfo;
  39753. }());
  39754. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  39755. /**
  39756. * 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.
  39757. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  39758. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  39759. * 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.
  39760. * 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.
  39761. * 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".
  39762. */
  39763. var DynamicFloatArray = (function () {
  39764. /**
  39765. * Construct an instance of the dynamic float array
  39766. * @param stride size of one element in float (i.e. not bytes!)
  39767. * @param initialElementCount the number of available entries at construction
  39768. */
  39769. function DynamicFloatArray(stride, initialElementCount) {
  39770. this.compareValueOffset = null;
  39771. this.sortingAscending = true;
  39772. this._stride = stride;
  39773. this.buffer = new Float32Array(stride * initialElementCount);
  39774. this._lastUsed = 0;
  39775. this._firstFree = 0;
  39776. this._allEntries = new Array(initialElementCount);
  39777. this._freeEntries = new Array(initialElementCount);
  39778. for (var i = 0; i < initialElementCount; i++) {
  39779. var element = new DynamicFloatArrayElementInfo();
  39780. element.offset = i * stride;
  39781. this._allEntries[i] = element;
  39782. this._freeEntries[initialElementCount - i - 1] = element;
  39783. }
  39784. }
  39785. /**
  39786. * Allocate an element in the array.
  39787. * @return the element info instance that contains the offset into the main buffer of the element's location.
  39788. * Beware, this offset may change when you call pack()
  39789. */
  39790. DynamicFloatArray.prototype.allocElement = function () {
  39791. if (this._freeEntries.length === 0) {
  39792. this._growBuffer();
  39793. }
  39794. var el = this._freeEntries.pop();
  39795. this._lastUsed = Math.max(el.offset, this._lastUsed);
  39796. if (el.offset === this._firstFree) {
  39797. if (this._freeEntries.length > 0) {
  39798. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  39799. }
  39800. else {
  39801. this._firstFree += this._stride;
  39802. }
  39803. }
  39804. return el;
  39805. };
  39806. /**
  39807. * Free the element corresponding to the given element info
  39808. * @param elInfo the element that describe the allocated element
  39809. */
  39810. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  39811. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  39812. this._freeEntries.push(elInfo);
  39813. };
  39814. /**
  39815. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  39816. * 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().
  39817. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  39818. */
  39819. DynamicFloatArray.prototype.pack = function () {
  39820. // no free slot? no need to pack
  39821. if (this._freeEntries.length === 0) {
  39822. return this.buffer;
  39823. }
  39824. // If the buffer is already packed the last used will always be lower than the first free
  39825. // 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.
  39826. if (this._lastUsed < this._firstFree) {
  39827. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  39828. return elementsBuffer_1;
  39829. }
  39830. var s = this._stride;
  39831. // 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
  39832. var lastFree = new DynamicFloatArrayElementInfo();
  39833. lastFree.offset = this.totalElementCount * s;
  39834. this._freeEntries.push(lastFree);
  39835. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  39836. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  39837. var firstFreeSlotOffset = sortedFree[0].offset;
  39838. var freeZoneSize = 1;
  39839. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  39840. var prevOffset = sortedFree[0].offset;
  39841. for (var i = 1; i < sortedFree.length; i++) {
  39842. // 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
  39843. if (firstFreeSlotOffset >= occupiedZoneSize) {
  39844. break;
  39845. }
  39846. var curFree = sortedFree[i];
  39847. var curOffset = curFree.offset;
  39848. // Compute the distance between this offset and the previous
  39849. var distance = curOffset - prevOffset;
  39850. // If the distance is the stride size, they are adjacent, it good, move to the next
  39851. if (distance === s) {
  39852. // Free zone is one element bigger
  39853. ++freeZoneSize;
  39854. // as we're about to iterate to the next, the cur becomes the previous...
  39855. prevOffset = curOffset;
  39856. continue;
  39857. }
  39858. // Distance is bigger, which means there's x element between the previous free and this one
  39859. var usedRange = (distance / s) - 1;
  39860. // Two cases the free zone is smaller than the data to move or bigger
  39861. // Copy what can fit in the free zone
  39862. var curMoveOffset = curOffset - s;
  39863. var copyCount = Math.min(freeZoneSize, usedRange);
  39864. for (var j = 0; j < copyCount; j++) {
  39865. var freeI = firstFreeSlotOffset / s;
  39866. var curI = curMoveOffset / s;
  39867. var moveEl = sortedAll[curI];
  39868. this._moveElement(moveEl, firstFreeSlotOffset);
  39869. var replacedEl = sortedAll[freeI];
  39870. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  39871. replacedEl.offset = curMoveOffset;
  39872. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  39873. sortedAll[freeI] = moveEl;
  39874. sortedAll[curI] = replacedEl;
  39875. curMoveOffset -= s;
  39876. firstFreeSlotOffset += s;
  39877. }
  39878. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  39879. if (freeZoneSize <= usedRange) {
  39880. firstFreeSlotOffset = curMoveOffset + s;
  39881. freeZoneSize = 1 + copyCount;
  39882. }
  39883. else {
  39884. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  39885. }
  39886. // as we're about to iterate to the next, the cur becomes the previous...
  39887. prevOffset = curOffset;
  39888. }
  39889. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  39890. this._lastUsed = firstFreeSlotOffset - s;
  39891. this._firstFree = firstFreeSlotOffset;
  39892. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  39893. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  39894. this._allEntries = sortedAll;
  39895. return elementsBuffer;
  39896. };
  39897. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  39898. for (var i = 0; i < this._stride; i++) {
  39899. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  39900. }
  39901. element.offset = destOffset;
  39902. };
  39903. DynamicFloatArray.prototype._growBuffer = function () {
  39904. // Allocate the new buffer with 50% more entries, copy the content of the current one
  39905. var newElCount = Math.floor(this.totalElementCount * 1.5);
  39906. var newBuffer = new Float32Array(newElCount * this._stride);
  39907. newBuffer.set(this.buffer);
  39908. var curCount = this.totalElementCount;
  39909. var addedCount = newElCount - this.totalElementCount;
  39910. for (var i = 0; i < addedCount; i++) {
  39911. var element = new DynamicFloatArrayElementInfo();
  39912. element.offset = (curCount + i) * this.stride;
  39913. this._allEntries.push(element);
  39914. this._freeEntries[addedCount - i - 1] = element;
  39915. }
  39916. this._firstFree = curCount * this.stride;
  39917. this.buffer = newBuffer;
  39918. };
  39919. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  39920. /**
  39921. * Get the total count of entries that can fit in the current buffer
  39922. * @returns the elements count
  39923. */
  39924. get: function () {
  39925. return this._allEntries.length;
  39926. },
  39927. enumerable: true,
  39928. configurable: true
  39929. });
  39930. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  39931. /**
  39932. * Get the count of free entries that can still be allocated without resizing the buffer
  39933. * @returns the free elements count
  39934. */
  39935. get: function () {
  39936. return this._freeEntries.length;
  39937. },
  39938. enumerable: true,
  39939. configurable: true
  39940. });
  39941. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  39942. /**
  39943. * Get the count of allocated elements
  39944. * @returns the allocated elements count
  39945. */
  39946. get: function () {
  39947. return this._allEntries.length - this._freeEntries.length;
  39948. },
  39949. enumerable: true,
  39950. configurable: true
  39951. });
  39952. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  39953. /**
  39954. * Return the size of one element in float
  39955. * @returns the size in float
  39956. */
  39957. get: function () {
  39958. return this._stride;
  39959. },
  39960. enumerable: true,
  39961. configurable: true
  39962. });
  39963. DynamicFloatArray.prototype.sort = function () {
  39964. var _this = this;
  39965. if (!this.compareValueOffset) {
  39966. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  39967. }
  39968. var count = this.usedElementCount;
  39969. // Do we have to (re)create the sort table?
  39970. if (!this._sortTable || this._sortTable.length < count) {
  39971. // 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...
  39972. var newCount = Math.min(this.totalElementCount, count * 2);
  39973. this._sortTable = new Array(newCount);
  39974. }
  39975. if (!this._sortedTable || this._sortedTable.length !== count) {
  39976. this._sortedTable = new Array(count);
  39977. }
  39978. // Because, you know...
  39979. this.pack();
  39980. //let stride = this.stride;
  39981. //for (let i = 0; i < count; i++) {
  39982. // let si = this._sortTable[i];
  39983. // if (!si) {
  39984. // si = new SortInfo();
  39985. // this._sortTable[i] = si;
  39986. // }
  39987. // si.entry = this._allEntries[i];
  39988. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  39989. // si.swapedOffset = null;
  39990. // this._sortedTable[i] = si;
  39991. //}
  39992. var curOffset = 0;
  39993. var stride = this.stride;
  39994. for (var i = 0; i < count; i++, curOffset += stride) {
  39995. var si = this._sortTable[i];
  39996. if (!si) {
  39997. si = new SortInfo();
  39998. this._sortTable[i] = si;
  39999. }
  40000. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  40001. si.offset = curOffset;
  40002. si.swapedOffset = null;
  40003. this._sortedTable[i] = si;
  40004. }
  40005. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  40006. if (this.sortingAscending) {
  40007. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  40008. }
  40009. else {
  40010. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  40011. }
  40012. var swapElements = function (src, dst) {
  40013. for (var i = 0; i < stride; i++) {
  40014. var tps = _this.buffer[dst + i];
  40015. _this.buffer[dst + i] = _this.buffer[src + i];
  40016. _this.buffer[src + i] = tps;
  40017. }
  40018. };
  40019. // 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:
  40020. // 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),
  40021. // and I still want something with a good algorithm complexity.
  40022. // 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,
  40023. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  40024. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  40025. // 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
  40026. // until we find a SortInfo object without a swapedOffset which means we got the right location
  40027. // 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
  40028. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  40029. for (var i = 0; i < count; i++) {
  40030. // Get the element to move
  40031. var sourceSI = this._sortedTable[i];
  40032. var destSI = this._sortTable[i];
  40033. var sourceOff = sourceSI.offset;
  40034. // If the source changed location, find the new one
  40035. if (sourceSI.swapedOffset) {
  40036. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  40037. var curSI = sourceSI;
  40038. while (curSI.swapedOffset) {
  40039. curSI = this._sortTable[curSI.swapedOffset / stride];
  40040. }
  40041. // Finally get the right location
  40042. sourceOff = curSI.offset;
  40043. }
  40044. // Tag the element being replaced with its new location
  40045. destSI.swapedOffset = sourceOff;
  40046. // Swap elements (only if needed)
  40047. if (sourceOff !== destSI.offset) {
  40048. swapElements(sourceOff, destSI.offset);
  40049. }
  40050. // Update the offset in the corresponding DFAE
  40051. //sourceSI.entry.offset = destSI.entry.offset;
  40052. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  40053. }
  40054. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  40055. return true;
  40056. };
  40057. return DynamicFloatArray;
  40058. }());
  40059. BABYLON.DynamicFloatArray = DynamicFloatArray;
  40060. var SortInfo = (function () {
  40061. function SortInfo() {
  40062. this.compareData = this.offset = this.swapedOffset = null;
  40063. }
  40064. return SortInfo;
  40065. }());
  40066. })(BABYLON || (BABYLON = {}));
  40067. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  40068. var BABYLON;
  40069. (function (BABYLON) {
  40070. /**
  40071. * This class given information about a given character.
  40072. */
  40073. var CharInfo = (function () {
  40074. function CharInfo() {
  40075. }
  40076. return CharInfo;
  40077. }());
  40078. BABYLON.CharInfo = CharInfo;
  40079. var FontTexture = (function (_super) {
  40080. __extends(FontTexture, _super);
  40081. /**
  40082. * Create a new instance of the FontTexture class
  40083. * @param name the name of the texture
  40084. * @param font the font to use, use the W3C CSS notation
  40085. * @param scene the scene that owns the texture
  40086. * @param maxCharCount the approximative maximum count of characters that could fit in the texture. This is an approximation because most of the fonts are proportional (each char has its own Width). The 'W' character's width is used to compute the size of the texture based on the given maxCharCount
  40087. * @param samplingMode the texture sampling mode
  40088. * @param superSample if true the FontTexture will be created with a font of a size twice bigger than the given one but all properties (lineHeight, charWidth, etc.) will be according to the original size. This is made to improve the text quality.
  40089. */
  40090. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample, signedDistanceField) {
  40091. if (maxCharCount === void 0) { maxCharCount = 200; }
  40092. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40093. if (superSample === void 0) { superSample = false; }
  40094. if (signedDistanceField === void 0) { signedDistanceField = false; }
  40095. var _this = _super.call(this, null, scene, true, false, samplingMode) || this;
  40096. _this._charInfos = {};
  40097. _this._curCharCount = 0;
  40098. _this._lastUpdateCharCount = -1;
  40099. _this._usedCounter = 1;
  40100. _this.name = name;
  40101. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40102. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40103. _this._sdfScale = 8;
  40104. _this._signedDistanceField = signedDistanceField;
  40105. _this._superSample = false;
  40106. // SDF will use supersample no matter what, the resolution is otherwise too poor to produce correct result
  40107. if (superSample || signedDistanceField) {
  40108. var sfont = _this.getSuperSampleFont(font);
  40109. if (sfont) {
  40110. _this._superSample = true;
  40111. font = sfont;
  40112. }
  40113. }
  40114. // First canvas creation to determine the size of the texture to create
  40115. _this._canvas = document.createElement("canvas");
  40116. _this._context = _this._canvas.getContext("2d");
  40117. _this._context.font = font;
  40118. _this._context.fillStyle = "white";
  40119. _this._context.textBaseline = "top";
  40120. _this._cachedFontId = null;
  40121. var res = _this.getFontHeight(font);
  40122. _this._lineHeightSuper = res.height + 4;
  40123. _this._lineHeight = _this._superSample ? (Math.ceil(_this._lineHeightSuper / 2)) : _this._lineHeightSuper;
  40124. _this._offset = res.offset - 1;
  40125. _this._xMargin = 1 + Math.ceil(_this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  40126. _this._yMargin = _this._xMargin;
  40127. var maxCharWidth = _this._context.measureText("W").width;
  40128. _this._spaceWidthSuper = _this._context.measureText(" ").width;
  40129. _this._spaceWidth = _this._superSample ? (_this._spaceWidthSuper / 2) : _this._spaceWidthSuper;
  40130. // This is an approximate size, but should always be able to fit at least the maxCharCount
  40131. var totalEstSurface = (_this._lineHeightSuper + _this._yMargin) * (maxCharWidth + _this._xMargin) * maxCharCount;
  40132. var edge = Math.sqrt(totalEstSurface);
  40133. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  40134. // Create the texture that will store the font characters
  40135. _this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  40136. var textureSize = _this.getSize();
  40137. _this.hasAlpha = _this._signedDistanceField === false;
  40138. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  40139. _this._canvas = document.createElement("canvas");
  40140. _this._canvas.width = textureSize.width;
  40141. _this._canvas.height = textureSize.height;
  40142. _this._context = _this._canvas.getContext("2d");
  40143. _this._context.textBaseline = "top";
  40144. _this._context.font = font;
  40145. _this._context.fillStyle = "white";
  40146. _this._context.imageSmoothingEnabled = false;
  40147. _this._context.clearRect(0, 0, textureSize.width, textureSize.height);
  40148. // Create a canvas for the signed distance field mode, we only have to store one char, the purpose is to render a char scaled _sdfScale times
  40149. // into this 2D context, then get the bitmap data, create the sdf char and push the result in the _context (which hold the whole Font Texture content)
  40150. // So you can see this context as an intermediate one, because it is.
  40151. if (_this._signedDistanceField) {
  40152. var sdfC = document.createElement("canvas");
  40153. var s = _this._sdfScale;
  40154. sdfC.width = maxCharWidth * s;
  40155. sdfC.height = _this._lineHeightSuper * s;
  40156. var sdfCtx = sdfC.getContext("2d");
  40157. sdfCtx.scale(s, s);
  40158. sdfCtx.textBaseline = "top";
  40159. sdfCtx.font = font;
  40160. sdfCtx.fillStyle = "white";
  40161. sdfCtx.imageSmoothingEnabled = false;
  40162. _this._sdfCanvas = sdfC;
  40163. _this._sdfContext = sdfCtx;
  40164. }
  40165. _this._currentFreePosition = BABYLON.Vector2.Zero();
  40166. // Add the basic ASCII based characters
  40167. for (var i = 0x20; i < 0x7F; i++) {
  40168. var c = String.fromCharCode(i);
  40169. _this.getChar(c);
  40170. }
  40171. _this.update();
  40172. return _this;
  40173. }
  40174. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  40175. get: function () {
  40176. return this._superSample;
  40177. },
  40178. enumerable: true,
  40179. configurable: true
  40180. });
  40181. Object.defineProperty(FontTexture.prototype, "isSignedDistanceField", {
  40182. get: function () {
  40183. return this._signedDistanceField;
  40184. },
  40185. enumerable: true,
  40186. configurable: true
  40187. });
  40188. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  40189. get: function () {
  40190. return this._spaceWidth;
  40191. },
  40192. enumerable: true,
  40193. configurable: true
  40194. });
  40195. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  40196. get: function () {
  40197. return this._lineHeight;
  40198. },
  40199. enumerable: true,
  40200. configurable: true
  40201. });
  40202. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  40203. if (supersample === void 0) { supersample = false; }
  40204. if (signedDistanceField === void 0) { signedDistanceField = false; }
  40205. var s = scene;
  40206. if (!s.__fontTextureCache__) {
  40207. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  40208. }
  40209. var dic = s.__fontTextureCache__;
  40210. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  40211. var ft = dic.get(lfn);
  40212. if (ft) {
  40213. ++ft._usedCounter;
  40214. return ft;
  40215. }
  40216. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample, signedDistanceField);
  40217. ft._cachedFontId = lfn;
  40218. dic.add(lfn, ft);
  40219. return ft;
  40220. };
  40221. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  40222. if (supersample === void 0) { supersample = false; }
  40223. if (signedDistanceField === void 0) { signedDistanceField = false; }
  40224. var s = scene;
  40225. var dic = s.__fontTextureCache__;
  40226. if (!dic) {
  40227. return;
  40228. }
  40229. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  40230. var font = dic.get(lfn);
  40231. if (--font._usedCounter === 0) {
  40232. dic.remove(lfn);
  40233. font.dispose();
  40234. }
  40235. };
  40236. /**
  40237. * Make sure the given char is present in the font map.
  40238. * @param char the character to get or add
  40239. * @return the CharInfo instance corresponding to the given character
  40240. */
  40241. FontTexture.prototype.getChar = function (char) {
  40242. if (char.length !== 1) {
  40243. return null;
  40244. }
  40245. var info = this._charInfos[char];
  40246. if (info) {
  40247. return info;
  40248. }
  40249. info = new CharInfo();
  40250. var measure = this._context.measureText(char);
  40251. var textureSize = this.getSize();
  40252. // we reached the end of the current line?
  40253. var width = Math.round(measure.width);
  40254. if (this._currentFreePosition.x + width + this._xMargin > textureSize.width) {
  40255. this._currentFreePosition.x = 0;
  40256. this._currentFreePosition.y += this._lineHeightSuper + this._yMargin;
  40257. // No more room?
  40258. if (this._currentFreePosition.y > textureSize.height) {
  40259. return this.getChar("!");
  40260. }
  40261. }
  40262. // In sdf mode we render the character in an intermediate 2D context which scale the character this._sdfScale times (which is required to compute the sdf map accurately)
  40263. if (this._signedDistanceField) {
  40264. this._sdfContext.clearRect(0, 0, this._sdfCanvas.width, this._sdfCanvas.height);
  40265. this._sdfContext.fillText(char, 0, -this._offset);
  40266. var data = this._sdfContext.getImageData(0, 0, width * this._sdfScale, this._sdfCanvas.height);
  40267. var res = this._computeSDFChar(data);
  40268. this._context.putImageData(res, this._currentFreePosition.x, this._currentFreePosition.y);
  40269. }
  40270. else {
  40271. // Draw the character in the HTML canvas
  40272. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  40273. }
  40274. // Fill the CharInfo object
  40275. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  40276. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  40277. if (this._signedDistanceField) {
  40278. var off = 1 / textureSize.width;
  40279. info.topLeftUV.addInPlace(new BABYLON.Vector2(off, off));
  40280. info.bottomRightUV.addInPlace(new BABYLON.Vector2(off, off));
  40281. }
  40282. info.charWidth = this._superSample ? (width / 2) : width;
  40283. // Add the info structure
  40284. this._charInfos[char] = info;
  40285. this._curCharCount++;
  40286. // Set the next position
  40287. this._currentFreePosition.x += width + this._xMargin;
  40288. return info;
  40289. };
  40290. FontTexture.prototype._computeSDFChar = function (source) {
  40291. var scl = this._sdfScale;
  40292. var sw = source.width;
  40293. var sh = source.height;
  40294. var dw = sw / scl;
  40295. var dh = sh / scl;
  40296. var roffx = 0;
  40297. var roffy = 0;
  40298. // We shouldn't look beyond half of the biggest between width and height
  40299. var radius = scl;
  40300. var br = radius - 1;
  40301. var lookupSrc = function (dx, dy, offX, offY, lookVis) {
  40302. var sx = dx * scl;
  40303. var sy = dy * scl;
  40304. // Looking out of the area? return true to make the test going on
  40305. if (((sx + offX) < 0) || ((sx + offX) >= sw) || ((sy + offY) < 0) || ((sy + offY) >= sh)) {
  40306. return true;
  40307. }
  40308. // Get the pixel we want
  40309. var val = source.data[(((sy + offY) * sw) + (sx + offX)) * 4];
  40310. var res = (val > 0) === lookVis;
  40311. if (!res) {
  40312. roffx = offX;
  40313. roffy = offY;
  40314. }
  40315. return res;
  40316. };
  40317. var lookupArea = function (dx, dy, lookVis) {
  40318. // Fast rejection test, if we have the same result in N, S, W, E at a distance which is the radius-1 then it means the data will be consistent in this area. That's because we've scale the rendering of the letter "radius" times, so a letter's pixel will be at least radius wide
  40319. if (lookupSrc(dx, dy, 0, br, lookVis) &&
  40320. lookupSrc(dx, dy, 0, -br, lookVis) &&
  40321. lookupSrc(dx, dy, -br, 0, lookVis) &&
  40322. lookupSrc(dx, dy, br, 0, lookVis)) {
  40323. return 0;
  40324. }
  40325. for (var i = 1; i <= radius; i++) {
  40326. // Quick test N, S, W, E
  40327. if (!lookupSrc(dx, dy, 0, i, lookVis) || !lookupSrc(dx, dy, 0, -i, lookVis) || !lookupSrc(dx, dy, -i, 0, lookVis) || !lookupSrc(dx, dy, i, 0, lookVis)) {
  40328. return i * i; // Squared Distance is simple to compute in this case
  40329. }
  40330. // Test the frame area (except the N, S, W, E spots) from the nearest point from the center to the further one
  40331. for (var j = 1; j <= i; j++) {
  40332. if (!lookupSrc(dx, dy, -j, i, lookVis) || !lookupSrc(dx, dy, j, i, lookVis) ||
  40333. !lookupSrc(dx, dy, i, -j, lookVis) || !lookupSrc(dx, dy, i, j, lookVis) ||
  40334. !lookupSrc(dx, dy, -j, -i, lookVis) || !lookupSrc(dx, dy, j, -i, lookVis) ||
  40335. !lookupSrc(dx, dy, -i, -j, lookVis) || !lookupSrc(dx, dy, -i, j, lookVis)) {
  40336. // We found the nearest texel having and opposite state, store the squared length
  40337. var res_1 = (i * i) + (j * j);
  40338. var count = 1;
  40339. // To improve quality we will sample the texels around this one, so it's 8 samples, we consider only the one having an opposite state, add them to the current res and will will compute the average at the end
  40340. if (!lookupSrc(dx, dy, roffx - 1, roffy, lookVis)) {
  40341. res_1 += (roffx - 1) * (roffx - 1) + roffy * roffy;
  40342. ++count;
  40343. }
  40344. if (!lookupSrc(dx, dy, roffx + 1, roffy, lookVis)) {
  40345. res_1 += (roffx + 1) * (roffx + 1) + roffy * roffy;
  40346. ++count;
  40347. }
  40348. if (!lookupSrc(dx, dy, roffx, roffy - 1, lookVis)) {
  40349. res_1 += roffx * roffx + (roffy - 1) * (roffy - 1);
  40350. ++count;
  40351. }
  40352. if (!lookupSrc(dx, dy, roffx, roffy + 1, lookVis)) {
  40353. res_1 += roffx * roffx + (roffy + 1) * (roffy + 1);
  40354. ++count;
  40355. }
  40356. if (!lookupSrc(dx, dy, roffx - 1, roffy - 1, lookVis)) {
  40357. res_1 += (roffx - 1) * (roffx - 1) + (roffy - 1) * (roffy - 1);
  40358. ++count;
  40359. }
  40360. if (!lookupSrc(dx, dy, roffx + 1, roffy + 1, lookVis)) {
  40361. res_1 += (roffx + 1) * (roffx + 1) + (roffy + 1) * (roffy + 1);
  40362. ++count;
  40363. }
  40364. if (!lookupSrc(dx, dy, roffx + 1, roffy - 1, lookVis)) {
  40365. res_1 += (roffx + 1) * (roffx + 1) + (roffy - 1) * (roffy - 1);
  40366. ++count;
  40367. }
  40368. if (!lookupSrc(dx, dy, roffx - 1, roffy + 1, lookVis)) {
  40369. res_1 += (roffx - 1) * (roffx - 1) + (roffy + 1) * (roffy + 1);
  40370. ++count;
  40371. }
  40372. // Compute the average based on the accumulated distance
  40373. return res_1 / count;
  40374. }
  40375. }
  40376. }
  40377. return 0;
  40378. };
  40379. var tmp = new Array(dw * dh);
  40380. for (var y = 0; y < dh; y++) {
  40381. for (var x = 0; x < dw; x++) {
  40382. var curState = lookupSrc(x, y, 0, 0, true);
  40383. var d = lookupArea(x, y, curState);
  40384. if (d === 0) {
  40385. d = radius * radius * 2;
  40386. }
  40387. tmp[(y * dw) + x] = curState ? d : -d;
  40388. }
  40389. }
  40390. var res = this._context.createImageData(dw, dh);
  40391. var size = dw * dh;
  40392. for (var j = 0; j < size; j++) {
  40393. var d = tmp[j];
  40394. var sign = (d < 0) ? -1 : 1;
  40395. d = Math.sqrt(Math.abs(d)) * sign;
  40396. d *= 127.5 / radius;
  40397. d += 127.5;
  40398. if (d < 0) {
  40399. d = 0;
  40400. }
  40401. else if (d > 255) {
  40402. d = 255;
  40403. }
  40404. d += 0.5;
  40405. res.data[j * 4 + 0] = d;
  40406. res.data[j * 4 + 1] = d;
  40407. res.data[j * 4 + 2] = d;
  40408. res.data[j * 4 + 3] = 255;
  40409. }
  40410. return res;
  40411. };
  40412. FontTexture.prototype.measureText = function (text, tabulationSize) {
  40413. if (tabulationSize === void 0) { tabulationSize = 4; }
  40414. var maxWidth = 0;
  40415. var curWidth = 0;
  40416. var lineCount = 1;
  40417. var charxpos = 0;
  40418. // Parse each char of the string
  40419. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  40420. var char = text_1[_i];
  40421. // Next line feed?
  40422. if (char === "\n") {
  40423. maxWidth = Math.max(maxWidth, curWidth);
  40424. charxpos = 0;
  40425. curWidth = 0;
  40426. ++lineCount;
  40427. continue;
  40428. }
  40429. // Tabulation ?
  40430. if (char === "\t") {
  40431. var nextPos = charxpos + tabulationSize;
  40432. nextPos = nextPos - (nextPos % tabulationSize);
  40433. curWidth += (nextPos - charxpos) * this.spaceWidth;
  40434. charxpos = nextPos;
  40435. continue;
  40436. }
  40437. if (char < " ") {
  40438. continue;
  40439. }
  40440. curWidth += this.getChar(char).charWidth;
  40441. ++charxpos;
  40442. }
  40443. maxWidth = Math.max(maxWidth, curWidth);
  40444. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  40445. };
  40446. FontTexture.prototype.getSuperSampleFont = function (font) {
  40447. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  40448. var regex = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\"\sa-z]+?)\s*$/;
  40449. var res = font.toLocaleLowerCase().match(regex);
  40450. if (res == null) {
  40451. return null;
  40452. }
  40453. var size = parseInt(res[4]);
  40454. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  40455. var newFont = "";
  40456. for (var j = 1; j < res.length; j++) {
  40457. if (res[j] != null) {
  40458. newFont += res[j] + " ";
  40459. }
  40460. }
  40461. return newFont;
  40462. };
  40463. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  40464. FontTexture.prototype.getFontHeight = function (font) {
  40465. var fontDraw = document.createElement("canvas");
  40466. var ctx = fontDraw.getContext('2d');
  40467. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  40468. ctx.textBaseline = 'top';
  40469. ctx.fillStyle = 'white';
  40470. ctx.font = font;
  40471. ctx.fillText('jH|', 0, 0);
  40472. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  40473. var start = -1;
  40474. var end = -1;
  40475. for (var row = 0; row < fontDraw.height; row++) {
  40476. for (var column = 0; column < fontDraw.width; column++) {
  40477. var index = (row * fontDraw.width + column) * 4;
  40478. if (pixels[index] === 0) {
  40479. if (column === fontDraw.width - 1 && start !== -1) {
  40480. end = row;
  40481. row = fontDraw.height;
  40482. break;
  40483. }
  40484. continue;
  40485. }
  40486. else {
  40487. if (start === -1) {
  40488. start = row;
  40489. }
  40490. break;
  40491. }
  40492. }
  40493. }
  40494. return { height: (end - start) + 1, offset: start - 1 };
  40495. };
  40496. Object.defineProperty(FontTexture.prototype, "canRescale", {
  40497. get: function () {
  40498. return false;
  40499. },
  40500. enumerable: true,
  40501. configurable: true
  40502. });
  40503. FontTexture.prototype.getContext = function () {
  40504. return this._context;
  40505. };
  40506. /**
  40507. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  40508. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  40509. */
  40510. FontTexture.prototype.update = function () {
  40511. // Update only if there's new char added since the previous update
  40512. if (this._lastUpdateCharCount < this._curCharCount) {
  40513. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  40514. this._lastUpdateCharCount = this._curCharCount;
  40515. }
  40516. };
  40517. // cloning should be prohibited, there's no point to duplicate this texture at all
  40518. FontTexture.prototype.clone = function () {
  40519. return null;
  40520. };
  40521. /**
  40522. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  40523. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  40524. */
  40525. FontTexture.prototype.incCachedFontTextureCounter = function () {
  40526. ++this._usedCounter;
  40527. };
  40528. /**
  40529. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  40530. */
  40531. FontTexture.prototype.decCachedFontTextureCounter = function () {
  40532. var s = this.getScene();
  40533. var dic = s.__fontTextureCache__;
  40534. if (!dic) {
  40535. return;
  40536. }
  40537. if (--this._usedCounter === 0) {
  40538. dic.remove(this._cachedFontId);
  40539. this.dispose();
  40540. }
  40541. };
  40542. return FontTexture;
  40543. }(BABYLON.Texture));
  40544. BABYLON.FontTexture = FontTexture;
  40545. })(BABYLON || (BABYLON = {}));
  40546. //# sourceMappingURL=babylon.fontTexture.js.map
  40547. var BABYLON;
  40548. (function (BABYLON) {
  40549. var MapTexture = (function (_super) {
  40550. __extends(MapTexture, _super);
  40551. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  40552. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40553. if (useMipMap === void 0) { useMipMap = false; }
  40554. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  40555. _this.name = name;
  40556. _this._size = size;
  40557. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40558. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40559. // Create the rectPackMap that will allocate portion of the texture
  40560. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  40561. // Create the texture that will store the content
  40562. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  40563. return _this;
  40564. }
  40565. /**
  40566. * Allocate a rectangle of a given size in the texture map
  40567. * @param size the size of the rectangle to allocation
  40568. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  40569. */
  40570. MapTexture.prototype.allocateRect = function (size) {
  40571. return this._rectPackingMap.addRect(size);
  40572. };
  40573. /**
  40574. * Free a given rectangle from the texture map
  40575. * @param rectInfo the instance corresponding to the rect to free.
  40576. */
  40577. MapTexture.prototype.freeRect = function (rectInfo) {
  40578. if (rectInfo) {
  40579. rectInfo.freeContent();
  40580. }
  40581. };
  40582. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  40583. /**
  40584. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  40585. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  40586. * @returns {}
  40587. */
  40588. get: function () {
  40589. return this._rectPackingMap.freeSpace;
  40590. },
  40591. enumerable: true,
  40592. configurable: true
  40593. });
  40594. /**
  40595. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  40596. * 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.
  40597. * Don't forget to call unbindTexture when you're done rendering
  40598. * @param rect the zone to render to
  40599. * @param clear true to clear the portion's color/depth data
  40600. */
  40601. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  40602. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  40603. };
  40604. /**
  40605. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  40606. * 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.
  40607. * Don't forget to call unbindTexture when you're done rendering
  40608. * @param pos the position into the texture
  40609. * @param size the portion to fit the clip space to
  40610. * @param clear true to clear the portion's color/depth data
  40611. */
  40612. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  40613. var engine = this.getScene().getEngine();
  40614. engine.bindFramebuffer(this._texture);
  40615. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  40616. if (clear) {
  40617. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  40618. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  40619. }
  40620. };
  40621. /**
  40622. * Unbind the texture map from the rendering engine.
  40623. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  40624. * @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.
  40625. */
  40626. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  40627. // Dump ?
  40628. if (dumpForDebug) {
  40629. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  40630. }
  40631. var engine = this.getScene().getEngine();
  40632. if (this._replacedViewport) {
  40633. engine.setViewport(this._replacedViewport);
  40634. this._replacedViewport = null;
  40635. }
  40636. engine.unBindFramebuffer(this._texture);
  40637. };
  40638. Object.defineProperty(MapTexture.prototype, "canRescale", {
  40639. get: function () {
  40640. return false;
  40641. },
  40642. enumerable: true,
  40643. configurable: true
  40644. });
  40645. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  40646. // Anyway, there's not much point to use this method for this kind of texture I guess
  40647. MapTexture.prototype.clone = function () {
  40648. return null;
  40649. };
  40650. return MapTexture;
  40651. }(BABYLON.Texture));
  40652. BABYLON.MapTexture = MapTexture;
  40653. })(BABYLON || (BABYLON = {}));
  40654. //# sourceMappingURL=babylon.mapTexture.js.map
  40655. var BABYLON;
  40656. (function (BABYLON) {
  40657. var ShaderMaterial = (function (_super) {
  40658. __extends(ShaderMaterial, _super);
  40659. function ShaderMaterial(name, scene, shaderPath, options) {
  40660. var _this = _super.call(this, name, scene) || this;
  40661. _this._textures = {};
  40662. _this._textureArrays = {};
  40663. _this._floats = {};
  40664. _this._floatsArrays = {};
  40665. _this._colors3 = {};
  40666. _this._colors4 = {};
  40667. _this._vectors2 = {};
  40668. _this._vectors3 = {};
  40669. _this._vectors4 = {};
  40670. _this._matrices = {};
  40671. _this._matrices3x3 = {};
  40672. _this._matrices2x2 = {};
  40673. _this._vectors3Arrays = {};
  40674. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  40675. _this._shaderPath = shaderPath;
  40676. options.needAlphaBlending = options.needAlphaBlending || false;
  40677. options.needAlphaTesting = options.needAlphaTesting || false;
  40678. options.attributes = options.attributes || ["position", "normal", "uv"];
  40679. options.uniforms = options.uniforms || ["worldViewProjection"];
  40680. options.samplers = options.samplers || [];
  40681. options.defines = options.defines || [];
  40682. _this._options = options;
  40683. return _this;
  40684. }
  40685. ShaderMaterial.prototype.getClassName = function () {
  40686. return "ShaderMaterial";
  40687. };
  40688. ShaderMaterial.prototype.needAlphaBlending = function () {
  40689. return this._options.needAlphaBlending;
  40690. };
  40691. ShaderMaterial.prototype.needAlphaTesting = function () {
  40692. return this._options.needAlphaTesting;
  40693. };
  40694. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  40695. if (this._options.uniforms.indexOf(uniformName) === -1) {
  40696. this._options.uniforms.push(uniformName);
  40697. }
  40698. };
  40699. ShaderMaterial.prototype.setTexture = function (name, texture) {
  40700. if (this._options.samplers.indexOf(name) === -1) {
  40701. this._options.samplers.push(name);
  40702. }
  40703. this._textures[name] = texture;
  40704. return this;
  40705. };
  40706. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  40707. if (this._options.samplers.indexOf(name) === -1) {
  40708. this._options.samplers.push(name);
  40709. }
  40710. this._checkUniform(name);
  40711. this._textureArrays[name] = textures;
  40712. return this;
  40713. };
  40714. ShaderMaterial.prototype.setFloat = function (name, value) {
  40715. this._checkUniform(name);
  40716. this._floats[name] = value;
  40717. return this;
  40718. };
  40719. ShaderMaterial.prototype.setFloats = function (name, value) {
  40720. this._checkUniform(name);
  40721. this._floatsArrays[name] = value;
  40722. return this;
  40723. };
  40724. ShaderMaterial.prototype.setColor3 = function (name, value) {
  40725. this._checkUniform(name);
  40726. this._colors3[name] = value;
  40727. return this;
  40728. };
  40729. ShaderMaterial.prototype.setColor4 = function (name, value) {
  40730. this._checkUniform(name);
  40731. this._colors4[name] = value;
  40732. return this;
  40733. };
  40734. ShaderMaterial.prototype.setVector2 = function (name, value) {
  40735. this._checkUniform(name);
  40736. this._vectors2[name] = value;
  40737. return this;
  40738. };
  40739. ShaderMaterial.prototype.setVector3 = function (name, value) {
  40740. this._checkUniform(name);
  40741. this._vectors3[name] = value;
  40742. return this;
  40743. };
  40744. ShaderMaterial.prototype.setVector4 = function (name, value) {
  40745. this._checkUniform(name);
  40746. this._vectors4[name] = value;
  40747. return this;
  40748. };
  40749. ShaderMaterial.prototype.setMatrix = function (name, value) {
  40750. this._checkUniform(name);
  40751. this._matrices[name] = value;
  40752. return this;
  40753. };
  40754. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  40755. this._checkUniform(name);
  40756. this._matrices3x3[name] = value;
  40757. return this;
  40758. };
  40759. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  40760. this._checkUniform(name);
  40761. this._matrices2x2[name] = value;
  40762. return this;
  40763. };
  40764. ShaderMaterial.prototype.setArray3 = function (name, value) {
  40765. this._checkUniform(name);
  40766. this._vectors3Arrays[name] = value;
  40767. return this;
  40768. };
  40769. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  40770. if (!mesh) {
  40771. return true;
  40772. }
  40773. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  40774. return false;
  40775. }
  40776. return false;
  40777. };
  40778. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  40779. var scene = this.getScene();
  40780. var engine = scene.getEngine();
  40781. if (!this.checkReadyOnEveryCall) {
  40782. if (this._renderId === scene.getRenderId()) {
  40783. if (this._checkCache(scene, mesh, useInstances)) {
  40784. return true;
  40785. }
  40786. }
  40787. }
  40788. // Instances
  40789. var defines = [];
  40790. var fallbacks = new BABYLON.EffectFallbacks();
  40791. if (useInstances) {
  40792. defines.push("#define INSTANCES");
  40793. }
  40794. for (var index = 0; index < this._options.defines.length; index++) {
  40795. defines.push(this._options.defines[index]);
  40796. }
  40797. // Bones
  40798. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  40799. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  40800. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  40801. fallbacks.addCPUSkinningFallback(0, mesh);
  40802. }
  40803. // Alpha test
  40804. if (engine.getAlphaTesting()) {
  40805. defines.push("#define ALPHATEST");
  40806. }
  40807. var previousEffect = this._effect;
  40808. var join = defines.join("\n");
  40809. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  40810. if (!this._effect.isReady()) {
  40811. return false;
  40812. }
  40813. if (previousEffect !== this._effect) {
  40814. scene.resetCachedMaterial();
  40815. }
  40816. this._renderId = scene.getRenderId();
  40817. return true;
  40818. };
  40819. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40820. var scene = this.getScene();
  40821. if (this._options.uniforms.indexOf("world") !== -1) {
  40822. this._effect.setMatrix("world", world);
  40823. }
  40824. if (this._options.uniforms.indexOf("worldView") !== -1) {
  40825. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  40826. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  40827. }
  40828. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  40829. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  40830. }
  40831. };
  40832. ShaderMaterial.prototype.bind = function (world, mesh) {
  40833. // Std values
  40834. this.bindOnlyWorldMatrix(world);
  40835. if (this.getScene().getCachedMaterial() !== this) {
  40836. if (this._options.uniforms.indexOf("view") !== -1) {
  40837. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  40838. }
  40839. if (this._options.uniforms.indexOf("projection") !== -1) {
  40840. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  40841. }
  40842. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  40843. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  40844. }
  40845. // Bones
  40846. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  40847. var name;
  40848. // Texture
  40849. for (name in this._textures) {
  40850. this._effect.setTexture(name, this._textures[name]);
  40851. }
  40852. // Texture arrays
  40853. for (name in this._textureArrays) {
  40854. this._effect.setTextureArray(name, this._textureArrays[name]);
  40855. }
  40856. // Float
  40857. for (name in this._floats) {
  40858. this._effect.setFloat(name, this._floats[name]);
  40859. }
  40860. // Float s
  40861. for (name in this._floatsArrays) {
  40862. this._effect.setArray(name, this._floatsArrays[name]);
  40863. }
  40864. // Color3
  40865. for (name in this._colors3) {
  40866. this._effect.setColor3(name, this._colors3[name]);
  40867. }
  40868. // Color4
  40869. for (name in this._colors4) {
  40870. var color = this._colors4[name];
  40871. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  40872. }
  40873. // Vector2
  40874. for (name in this._vectors2) {
  40875. this._effect.setVector2(name, this._vectors2[name]);
  40876. }
  40877. // Vector3
  40878. for (name in this._vectors3) {
  40879. this._effect.setVector3(name, this._vectors3[name]);
  40880. }
  40881. // Vector4
  40882. for (name in this._vectors4) {
  40883. this._effect.setVector4(name, this._vectors4[name]);
  40884. }
  40885. // Matrix
  40886. for (name in this._matrices) {
  40887. this._effect.setMatrix(name, this._matrices[name]);
  40888. }
  40889. // Matrix 3x3
  40890. for (name in this._matrices3x3) {
  40891. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  40892. }
  40893. // Matrix 2x2
  40894. for (name in this._matrices2x2) {
  40895. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  40896. }
  40897. // Vector3Array
  40898. for (name in this._vectors3Arrays) {
  40899. this._effect.setArray3(name, this._vectors3Arrays[name]);
  40900. }
  40901. }
  40902. _super.prototype.bind.call(this, world, mesh);
  40903. };
  40904. ShaderMaterial.prototype.clone = function (name) {
  40905. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  40906. return newShaderMaterial;
  40907. };
  40908. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40909. if (forceDisposeTextures) {
  40910. var name;
  40911. for (name in this._textures) {
  40912. this._textures[name].dispose();
  40913. }
  40914. for (name in this._textureArrays) {
  40915. var array = this._textureArrays[name];
  40916. for (var index = 0; index < array.length; index++) {
  40917. array[index].dispose();
  40918. }
  40919. }
  40920. }
  40921. this._textures = {};
  40922. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40923. };
  40924. ShaderMaterial.prototype.serialize = function () {
  40925. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40926. serializationObject.customType = "BABYLON.ShaderMaterial";
  40927. serializationObject.options = this._options;
  40928. serializationObject.shaderPath = this._shaderPath;
  40929. var name;
  40930. // Texture
  40931. serializationObject.textures = {};
  40932. for (name in this._textures) {
  40933. serializationObject.textures[name] = this._textures[name].serialize();
  40934. }
  40935. // Texture arrays
  40936. serializationObject.textureArrays = {};
  40937. for (name in this._textureArrays) {
  40938. serializationObject.textureArrays[name] = [];
  40939. var array = this._textureArrays[name];
  40940. for (var index = 0; index < array.length; index++) {
  40941. serializationObject.textureArrays[name].push(array[index].serialize());
  40942. }
  40943. }
  40944. // Float
  40945. serializationObject.floats = {};
  40946. for (name in this._floats) {
  40947. serializationObject.floats[name] = this._floats[name];
  40948. }
  40949. // Float s
  40950. serializationObject.floatArrays = {};
  40951. for (name in this._floatsArrays) {
  40952. serializationObject.floatArrays[name] = this._floatsArrays[name];
  40953. }
  40954. // Color3
  40955. serializationObject.colors3 = {};
  40956. for (name in this._colors3) {
  40957. serializationObject.colors3[name] = this._colors3[name].asArray();
  40958. }
  40959. // Color4
  40960. serializationObject.colors4 = {};
  40961. for (name in this._colors4) {
  40962. serializationObject.colors4[name] = this._colors4[name].asArray();
  40963. }
  40964. // Vector2
  40965. serializationObject.vectors2 = {};
  40966. for (name in this._vectors2) {
  40967. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  40968. }
  40969. // Vector3
  40970. serializationObject.vectors3 = {};
  40971. for (name in this._vectors3) {
  40972. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  40973. }
  40974. // Vector4
  40975. serializationObject.vectors4 = {};
  40976. for (name in this._vectors4) {
  40977. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  40978. }
  40979. // Matrix
  40980. serializationObject.matrices = {};
  40981. for (name in this._matrices) {
  40982. serializationObject.matrices[name] = this._matrices[name].asArray();
  40983. }
  40984. // Matrix 3x3
  40985. serializationObject.matrices3x3 = {};
  40986. for (name in this._matrices3x3) {
  40987. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  40988. }
  40989. // Matrix 2x2
  40990. serializationObject.matrices2x2 = {};
  40991. for (name in this._matrices2x2) {
  40992. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  40993. }
  40994. // Vector3Array
  40995. serializationObject.vectors3Arrays = {};
  40996. for (name in this._vectors3Arrays) {
  40997. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  40998. }
  40999. return serializationObject;
  41000. };
  41001. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  41002. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  41003. var name;
  41004. // Texture
  41005. for (name in source.textures) {
  41006. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  41007. }
  41008. // Texture arrays
  41009. for (name in source.textureArrays) {
  41010. var array = source.textureArrays[name];
  41011. var textureArray = new Array();
  41012. for (var index = 0; index < array.length; index++) {
  41013. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  41014. }
  41015. material.setTextureArray(name, textureArray);
  41016. }
  41017. // Float
  41018. for (name in source.floats) {
  41019. material.setFloat(name, source.floats[name]);
  41020. }
  41021. // Float s
  41022. for (name in source.floatsArrays) {
  41023. material.setFloats(name, source.floatsArrays[name]);
  41024. }
  41025. // Color3
  41026. for (name in source.colors3) {
  41027. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  41028. }
  41029. // Color4
  41030. for (name in source.colors4) {
  41031. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  41032. }
  41033. // Vector2
  41034. for (name in source.vectors2) {
  41035. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  41036. }
  41037. // Vector3
  41038. for (name in source.vectors3) {
  41039. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  41040. }
  41041. // Vector4
  41042. for (name in source.vectors4) {
  41043. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  41044. }
  41045. // Matrix
  41046. for (name in source.matrices) {
  41047. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  41048. }
  41049. // Matrix 3x3
  41050. for (name in source.matrices3x3) {
  41051. material.setMatrix3x3(name, source.matrices3x3[name]);
  41052. }
  41053. // Matrix 2x2
  41054. for (name in source.matrices2x2) {
  41055. material.setMatrix2x2(name, source.matrices2x2[name]);
  41056. }
  41057. // Vector3Array
  41058. for (name in source.vectors3Arrays) {
  41059. material.setArray3(name, source.vectors3Arrays[name]);
  41060. }
  41061. return material;
  41062. };
  41063. return ShaderMaterial;
  41064. }(BABYLON.Material));
  41065. BABYLON.ShaderMaterial = ShaderMaterial;
  41066. })(BABYLON || (BABYLON = {}));
  41067. //# sourceMappingURL=babylon.shaderMaterial.js.map
  41068. var BABYLON;
  41069. (function (BABYLON) {
  41070. var Internals;
  41071. (function (Internals) {
  41072. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  41073. // All values and structures referenced from:
  41074. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  41075. var DDS_MAGIC = 0x20534444;
  41076. 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;
  41077. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  41078. 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;
  41079. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  41080. function FourCCToInt32(value) {
  41081. return value.charCodeAt(0) +
  41082. (value.charCodeAt(1) << 8) +
  41083. (value.charCodeAt(2) << 16) +
  41084. (value.charCodeAt(3) << 24);
  41085. }
  41086. function Int32ToFourCC(value) {
  41087. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  41088. }
  41089. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  41090. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  41091. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  41092. var headerLengthInt = 31; // The header length in 32 bit ints
  41093. // Offsets into the header array
  41094. var off_magic = 0;
  41095. var off_size = 1;
  41096. var off_flags = 2;
  41097. var off_height = 3;
  41098. var off_width = 4;
  41099. var off_mipmapCount = 7;
  41100. var off_pfFlags = 20;
  41101. var off_pfFourCC = 21;
  41102. var off_RGBbpp = 22;
  41103. var off_RMask = 23;
  41104. var off_GMask = 24;
  41105. var off_BMask = 25;
  41106. var off_AMask = 26;
  41107. var off_caps1 = 27;
  41108. var off_caps2 = 28;
  41109. ;
  41110. var DDSTools = (function () {
  41111. function DDSTools() {
  41112. }
  41113. DDSTools.GetDDSInfo = function (arrayBuffer) {
  41114. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  41115. var mipmapCount = 1;
  41116. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  41117. mipmapCount = Math.max(1, header[off_mipmapCount]);
  41118. }
  41119. return {
  41120. width: header[off_width],
  41121. height: header[off_height],
  41122. mipmapCount: mipmapCount,
  41123. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  41124. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  41125. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  41126. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  41127. };
  41128. };
  41129. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41130. var byteArray = new Uint8Array(dataLength);
  41131. var srcData = new Uint8Array(arrayBuffer);
  41132. var index = 0;
  41133. for (var y = height - 1; y >= 0; y--) {
  41134. for (var x = 0; x < width; x++) {
  41135. var srcPos = dataOffset + (x + y * width) * 4;
  41136. byteArray[index + 2] = srcData[srcPos];
  41137. byteArray[index + 1] = srcData[srcPos + 1];
  41138. byteArray[index] = srcData[srcPos + 2];
  41139. byteArray[index + 3] = srcData[srcPos + 3];
  41140. index += 4;
  41141. }
  41142. }
  41143. return byteArray;
  41144. };
  41145. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41146. var byteArray = new Uint8Array(dataLength);
  41147. var srcData = new Uint8Array(arrayBuffer);
  41148. var index = 0;
  41149. for (var y = height - 1; y >= 0; y--) {
  41150. for (var x = 0; x < width; x++) {
  41151. var srcPos = dataOffset + (x + y * width) * 3;
  41152. byteArray[index + 2] = srcData[srcPos];
  41153. byteArray[index + 1] = srcData[srcPos + 1];
  41154. byteArray[index] = srcData[srcPos + 2];
  41155. index += 3;
  41156. }
  41157. }
  41158. return byteArray;
  41159. };
  41160. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41161. var byteArray = new Uint8Array(dataLength);
  41162. var srcData = new Uint8Array(arrayBuffer);
  41163. var index = 0;
  41164. for (var y = height - 1; y >= 0; y--) {
  41165. for (var x = 0; x < width; x++) {
  41166. var srcPos = dataOffset + (x + y * width);
  41167. byteArray[index] = srcData[srcPos];
  41168. index++;
  41169. }
  41170. }
  41171. return byteArray;
  41172. };
  41173. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  41174. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  41175. if (header[off_magic] != DDS_MAGIC) {
  41176. BABYLON.Tools.Error("Invalid magic number in DDS header");
  41177. return;
  41178. }
  41179. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  41180. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  41181. return;
  41182. }
  41183. if (info.isFourCC) {
  41184. fourCC = header[off_pfFourCC];
  41185. switch (fourCC) {
  41186. case FOURCC_DXT1:
  41187. blockBytes = 8;
  41188. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  41189. break;
  41190. case FOURCC_DXT3:
  41191. blockBytes = 16;
  41192. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  41193. break;
  41194. case FOURCC_DXT5:
  41195. blockBytes = 16;
  41196. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  41197. break;
  41198. default:
  41199. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  41200. return;
  41201. }
  41202. }
  41203. mipmapCount = 1;
  41204. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  41205. mipmapCount = Math.max(1, header[off_mipmapCount]);
  41206. }
  41207. var bpp = header[off_RGBbpp];
  41208. for (var face = 0; face < faces; face++) {
  41209. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  41210. width = header[off_width];
  41211. height = header[off_height];
  41212. dataOffset = header[off_size] + 4;
  41213. for (i = 0; i < mipmapCount; ++i) {
  41214. if (info.isRGB) {
  41215. if (bpp === 24) {
  41216. dataLength = width * height * 3;
  41217. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41218. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  41219. }
  41220. else {
  41221. dataLength = width * height * 4;
  41222. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41223. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  41224. }
  41225. }
  41226. else if (info.isLuminance) {
  41227. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  41228. var unpaddedRowSize = width;
  41229. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  41230. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  41231. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41232. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  41233. }
  41234. else {
  41235. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  41236. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  41237. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  41238. }
  41239. dataOffset += dataLength;
  41240. width *= 0.5;
  41241. height *= 0.5;
  41242. width = Math.max(1.0, width);
  41243. height = Math.max(1.0, height);
  41244. }
  41245. }
  41246. };
  41247. return DDSTools;
  41248. }());
  41249. Internals.DDSTools = DDSTools;
  41250. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41251. })(BABYLON || (BABYLON = {}));
  41252. //# sourceMappingURL=babylon.tools.dds.js.map
  41253. var BABYLON;
  41254. (function (BABYLON) {
  41255. var Internals;
  41256. (function (Internals) {
  41257. /**
  41258. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  41259. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  41260. */
  41261. var KhronosTextureContainer = (function () {
  41262. /**
  41263. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  41264. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  41265. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  41266. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  41267. */
  41268. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  41269. this.arrayBuffer = arrayBuffer;
  41270. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  41271. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  41272. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  41273. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  41274. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  41275. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  41276. BABYLON.Tools.Error("texture missing KTX identifier");
  41277. return;
  41278. }
  41279. // load the reset of the header in native 32 bit int
  41280. var header = new Int32Array(this.arrayBuffer, 12, 13);
  41281. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  41282. var oppositeEndianess = header[0] === 0x01020304;
  41283. // read all the header elements in order they exist in the file, without modification (sans endainness)
  41284. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  41285. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  41286. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  41287. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  41288. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  41289. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  41290. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  41291. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  41292. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  41293. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  41294. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  41295. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  41296. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  41297. if (this.glType !== 0) {
  41298. BABYLON.Tools.Error("only compressed formats currently supported");
  41299. return;
  41300. }
  41301. else {
  41302. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  41303. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  41304. }
  41305. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  41306. BABYLON.Tools.Error("only 2D textures currently supported");
  41307. return;
  41308. }
  41309. if (this.numberOfArrayElements !== 0) {
  41310. BABYLON.Tools.Error("texture arrays not currently supported");
  41311. return;
  41312. }
  41313. if (this.numberOfFaces !== facesExpected) {
  41314. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  41315. return;
  41316. }
  41317. // we now have a completely validated file, so could use existence of loadType as success
  41318. // would need to make this more elaborate & adjust checks above to support more than one load type
  41319. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  41320. }
  41321. // not as fast hardware based, but will probably never need to use
  41322. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  41323. return ((val & 0xFF) << 24)
  41324. | ((val & 0xFF00) << 8)
  41325. | ((val >> 8) & 0xFF00)
  41326. | ((val >> 24) & 0xFF);
  41327. };
  41328. /**
  41329. * It is assumed that the texture has already been created & is currently bound
  41330. */
  41331. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  41332. switch (this.loadType) {
  41333. case KhronosTextureContainer.COMPRESSED_2D:
  41334. this._upload2DCompressedLevels(gl, loadMipmaps);
  41335. break;
  41336. case KhronosTextureContainer.TEX_2D:
  41337. case KhronosTextureContainer.COMPRESSED_3D:
  41338. case KhronosTextureContainer.TEX_3D:
  41339. }
  41340. };
  41341. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  41342. // initialize width & height for level 1
  41343. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  41344. var width = this.pixelWidth;
  41345. var height = this.pixelHeight;
  41346. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  41347. for (var level = 0; level < mipmapCount; level++) {
  41348. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  41349. for (var face = 0; face < this.numberOfFaces; face++) {
  41350. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  41351. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  41352. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  41353. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  41354. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  41355. }
  41356. width = Math.max(1.0, width * 0.5);
  41357. height = Math.max(1.0, height * 0.5);
  41358. }
  41359. };
  41360. return KhronosTextureContainer;
  41361. }());
  41362. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  41363. // load types
  41364. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  41365. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  41366. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  41367. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  41368. Internals.KhronosTextureContainer = KhronosTextureContainer;
  41369. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41370. })(BABYLON || (BABYLON = {}));
  41371. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  41372. var BABYLON;
  41373. (function (BABYLON) {
  41374. var CannonJSPlugin = (function () {
  41375. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  41376. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  41377. if (iterations === void 0) { iterations = 10; }
  41378. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  41379. this.name = "CannonJSPlugin";
  41380. this._physicsMaterials = [];
  41381. this._fixedTimeStep = 1 / 60;
  41382. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  41383. this._currentCollisionGroup = 2;
  41384. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  41385. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  41386. this._tmpPosition = BABYLON.Vector3.Zero();
  41387. this._tmpQuaternion = new BABYLON.Quaternion();
  41388. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  41389. this._tmpDeltaRotation = new BABYLON.Quaternion();
  41390. this._tmpUnityRotation = new BABYLON.Quaternion();
  41391. if (!this.isSupported()) {
  41392. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  41393. return;
  41394. }
  41395. this.world = new CANNON.World();
  41396. this.world.broadphase = new CANNON.NaiveBroadphase();
  41397. this.world.solver.iterations = iterations;
  41398. }
  41399. CannonJSPlugin.prototype.setGravity = function (gravity) {
  41400. this.world.gravity.copy(gravity);
  41401. };
  41402. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  41403. this._fixedTimeStep = timeStep;
  41404. };
  41405. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  41406. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  41407. };
  41408. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  41409. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41410. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41411. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  41412. };
  41413. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  41414. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41415. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41416. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  41417. };
  41418. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  41419. //parent-child relationship. Does this impostor has a parent impostor?
  41420. if (impostor.parent) {
  41421. if (impostor.physicsBody) {
  41422. this.removePhysicsBody(impostor);
  41423. //TODO is that needed?
  41424. impostor.forceUpdate();
  41425. }
  41426. return;
  41427. }
  41428. //should a new body be created for this impostor?
  41429. if (impostor.isBodyInitRequired()) {
  41430. var shape = this._createShape(impostor);
  41431. //unregister events, if body is being changed
  41432. var oldBody = impostor.physicsBody;
  41433. if (oldBody) {
  41434. this.removePhysicsBody(impostor);
  41435. }
  41436. //create the body and material
  41437. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  41438. var bodyCreationObject = {
  41439. mass: impostor.getParam("mass"),
  41440. material: material
  41441. };
  41442. // A simple extend, in case native options were used.
  41443. var nativeOptions = impostor.getParam("nativeOptions");
  41444. for (var key in nativeOptions) {
  41445. if (nativeOptions.hasOwnProperty(key)) {
  41446. bodyCreationObject[key] = nativeOptions[key];
  41447. }
  41448. }
  41449. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  41450. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  41451. this.world.addEventListener("preStep", impostor.beforeStep);
  41452. this.world.addEventListener("postStep", impostor.afterStep);
  41453. impostor.physicsBody.addShape(shape);
  41454. this.world.add(impostor.physicsBody);
  41455. //try to keep the body moving in the right direction by taking old properties.
  41456. //Should be tested!
  41457. if (oldBody) {
  41458. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  41459. impostor.physicsBody[param].copy(oldBody[param]);
  41460. });
  41461. }
  41462. this._processChildMeshes(impostor);
  41463. }
  41464. //now update the body's transformation
  41465. this._updatePhysicsBodyTransformation(impostor);
  41466. };
  41467. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  41468. var _this = this;
  41469. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  41470. if (meshChildren.length) {
  41471. var processMesh = function (localPosition, mesh) {
  41472. var childImpostor = mesh.getPhysicsImpostor();
  41473. if (childImpostor) {
  41474. var parent = childImpostor.parent;
  41475. if (parent !== mainImpostor) {
  41476. var localPosition = mesh.position;
  41477. if (childImpostor.physicsBody) {
  41478. _this.removePhysicsBody(childImpostor);
  41479. childImpostor.physicsBody = null;
  41480. }
  41481. childImpostor.parent = mainImpostor;
  41482. childImpostor.resetUpdateFlags();
  41483. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  41484. //Add the mass of the children.
  41485. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  41486. }
  41487. }
  41488. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  41489. };
  41490. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  41491. }
  41492. };
  41493. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  41494. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  41495. this.world.removeEventListener("preStep", impostor.beforeStep);
  41496. this.world.removeEventListener("postStep", impostor.afterStep);
  41497. this.world.remove(impostor.physicsBody);
  41498. };
  41499. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  41500. var mainBody = impostorJoint.mainImpostor.physicsBody;
  41501. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  41502. if (!mainBody || !connectedBody) {
  41503. return;
  41504. }
  41505. var constraint;
  41506. var jointData = impostorJoint.joint.jointData;
  41507. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  41508. var constraintData = {
  41509. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  41510. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  41511. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  41512. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  41513. maxForce: jointData.nativeParams.maxForce,
  41514. collideConnected: !!jointData.collision
  41515. };
  41516. //Not needed, Cannon has a collideConnected flag
  41517. /*if (!jointData.collision) {
  41518. //add 1st body to a collision group of its own, if it is not in 1
  41519. if (mainBody.collisionFilterGroup === 1) {
  41520. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  41521. this._currentCollisionGroup <<= 1;
  41522. }
  41523. if (connectedBody.collisionFilterGroup === 1) {
  41524. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  41525. this._currentCollisionGroup <<= 1;
  41526. }
  41527. //add their mask to the collisionFilterMask of each other:
  41528. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  41529. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  41530. }*/
  41531. switch (impostorJoint.joint.type) {
  41532. case BABYLON.PhysicsJoint.HingeJoint:
  41533. case BABYLON.PhysicsJoint.Hinge2Joint:
  41534. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  41535. break;
  41536. case BABYLON.PhysicsJoint.DistanceJoint:
  41537. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  41538. break;
  41539. case BABYLON.PhysicsJoint.SpringJoint:
  41540. var springData = jointData;
  41541. constraint = new CANNON.Spring(mainBody, connectedBody, {
  41542. restLength: springData.length,
  41543. stiffness: springData.stiffness,
  41544. damping: springData.damping,
  41545. localAnchorA: constraintData.pivotA,
  41546. localAnchorB: constraintData.pivotB
  41547. });
  41548. break;
  41549. case BABYLON.PhysicsJoint.LockJoint:
  41550. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  41551. break;
  41552. case BABYLON.PhysicsJoint.PointToPointJoint:
  41553. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  41554. default:
  41555. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  41556. break;
  41557. }
  41558. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  41559. constraint.collideConnected = !!jointData.collision;
  41560. impostorJoint.joint.physicsJoint = constraint;
  41561. //don't add spring as constraint, as it is not one.
  41562. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  41563. this.world.addConstraint(constraint);
  41564. }
  41565. else {
  41566. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  41567. constraint.applyForce();
  41568. });
  41569. }
  41570. };
  41571. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  41572. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  41573. };
  41574. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  41575. var index;
  41576. var mat;
  41577. for (index = 0; index < this._physicsMaterials.length; index++) {
  41578. mat = this._physicsMaterials[index];
  41579. if (mat.friction === friction && mat.restitution === restitution) {
  41580. return mat;
  41581. }
  41582. }
  41583. var currentMat = new CANNON.Material(name);
  41584. currentMat.friction = friction;
  41585. currentMat.restitution = restitution;
  41586. this._physicsMaterials.push(currentMat);
  41587. return currentMat;
  41588. };
  41589. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  41590. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  41591. };
  41592. CannonJSPlugin.prototype._createShape = function (impostor) {
  41593. var object = impostor.object;
  41594. var returnValue;
  41595. var extendSize = impostor.getObjectExtendSize();
  41596. switch (impostor.type) {
  41597. case BABYLON.PhysicsEngine.SphereImpostor:
  41598. var radiusX = extendSize.x;
  41599. var radiusY = extendSize.y;
  41600. var radiusZ = extendSize.z;
  41601. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  41602. break;
  41603. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  41604. case BABYLON.PhysicsImpostor.CylinderImpostor:
  41605. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  41606. break;
  41607. case BABYLON.PhysicsImpostor.BoxImpostor:
  41608. var box = extendSize.scale(0.5);
  41609. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  41610. break;
  41611. case BABYLON.PhysicsImpostor.PlaneImpostor:
  41612. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  41613. returnValue = new CANNON.Plane();
  41614. break;
  41615. case BABYLON.PhysicsImpostor.MeshImpostor:
  41616. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  41617. var rawFaces = object.getIndices ? object.getIndices() : [];
  41618. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  41619. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  41620. break;
  41621. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  41622. returnValue = this._createHeightmap(object);
  41623. break;
  41624. case BABYLON.PhysicsImpostor.ParticleImpostor:
  41625. returnValue = new CANNON.Particle();
  41626. break;
  41627. }
  41628. return returnValue;
  41629. };
  41630. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  41631. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41632. var matrix = [];
  41633. //For now pointDepth will not be used and will be automatically calculated.
  41634. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  41635. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  41636. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  41637. var elementSize = dim * 2 / arraySize;
  41638. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  41639. for (var i = 0; i < pos.length; i = i + 3) {
  41640. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  41641. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  41642. var y = pos[i + 1] + minY;
  41643. if (!matrix[x]) {
  41644. matrix[x] = [];
  41645. }
  41646. if (!matrix[x][z]) {
  41647. matrix[x][z] = y;
  41648. }
  41649. matrix[x][z] = Math.max(y, matrix[x][z]);
  41650. }
  41651. for (var x = 0; x <= arraySize; ++x) {
  41652. if (!matrix[x]) {
  41653. var loc = 1;
  41654. while (!matrix[(x + loc) % arraySize]) {
  41655. loc++;
  41656. }
  41657. matrix[x] = matrix[(x + loc) % arraySize].slice();
  41658. }
  41659. for (var z = 0; z <= arraySize; ++z) {
  41660. if (!matrix[x][z]) {
  41661. var loc = 1;
  41662. var newValue;
  41663. while (newValue === undefined) {
  41664. newValue = matrix[x][(z + loc++) % arraySize];
  41665. }
  41666. matrix[x][z] = newValue;
  41667. }
  41668. }
  41669. }
  41670. var shape = new CANNON.Heightfield(matrix, {
  41671. elementSize: elementSize
  41672. });
  41673. //For future reference, needed for body transformation
  41674. shape.minY = minY;
  41675. return shape;
  41676. };
  41677. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  41678. var object = impostor.object;
  41679. //make sure it is updated...
  41680. object.computeWorldMatrix && object.computeWorldMatrix(true);
  41681. // The delta between the mesh position and the mesh bounding box center
  41682. var center = impostor.getObjectCenter();
  41683. var extendSize = impostor.getObjectExtendSize();
  41684. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  41685. this._tmpPosition.copyFrom(center);
  41686. var quaternion = object.rotationQuaternion;
  41687. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  41688. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  41689. //-90 DEG in X, precalculated
  41690. quaternion = quaternion.multiply(this._minus90X);
  41691. //Invert! (Precalculated, 90 deg in X)
  41692. //No need to clone. this will never change.
  41693. impostor.setDeltaRotation(this._plus90X);
  41694. }
  41695. //If it is a heightfield, if should be centered.
  41696. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  41697. var mesh = object;
  41698. //calculate the correct body position:
  41699. var rotationQuaternion = mesh.rotationQuaternion;
  41700. mesh.rotationQuaternion = this._tmpUnityRotation;
  41701. mesh.computeWorldMatrix(true);
  41702. //get original center with no rotation
  41703. var c = center.clone();
  41704. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  41705. //rotation is back
  41706. mesh.rotationQuaternion = rotationQuaternion;
  41707. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  41708. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  41709. mesh.setPivotMatrix(p);
  41710. mesh.computeWorldMatrix(true);
  41711. //calculate the translation
  41712. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  41713. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  41714. //add it inverted to the delta
  41715. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  41716. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  41717. mesh.setPivotMatrix(oldPivot);
  41718. mesh.computeWorldMatrix(true);
  41719. }
  41720. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  41721. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  41722. this._tmpPosition.copyFrom(object.position);
  41723. }
  41724. impostor.setDeltaPosition(this._tmpDeltaPosition);
  41725. //Now update the impostor object
  41726. impostor.physicsBody.position.copy(this._tmpPosition);
  41727. impostor.physicsBody.quaternion.copy(quaternion);
  41728. };
  41729. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  41730. impostor.object.position.copyFrom(impostor.physicsBody.position);
  41731. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  41732. };
  41733. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  41734. impostor.physicsBody.position.copy(newPosition);
  41735. impostor.physicsBody.quaternion.copy(newRotation);
  41736. };
  41737. CannonJSPlugin.prototype.isSupported = function () {
  41738. return window.CANNON !== undefined;
  41739. };
  41740. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  41741. impostor.physicsBody.velocity.copy(velocity);
  41742. };
  41743. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  41744. impostor.physicsBody.angularVelocity.copy(velocity);
  41745. };
  41746. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  41747. var v = impostor.physicsBody.velocity;
  41748. if (!v)
  41749. return null;
  41750. return new BABYLON.Vector3(v.x, v.y, v.z);
  41751. };
  41752. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  41753. var v = impostor.physicsBody.angularVelocity;
  41754. if (!v)
  41755. return null;
  41756. return new BABYLON.Vector3(v.x, v.y, v.z);
  41757. };
  41758. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  41759. impostor.physicsBody.mass = mass;
  41760. impostor.physicsBody.updateMassProperties();
  41761. };
  41762. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  41763. impostor.physicsBody.sleep();
  41764. };
  41765. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  41766. impostor.physicsBody.wakeUp();
  41767. };
  41768. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  41769. joint.physicsJoint.distance = maxDistance;
  41770. };
  41771. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  41772. if (!motorIndex) {
  41773. joint.physicsJoint.enableMotor();
  41774. }
  41775. };
  41776. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  41777. if (!motorIndex) {
  41778. joint.physicsJoint.disableMotor();
  41779. }
  41780. };
  41781. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  41782. if (!motorIndex) {
  41783. joint.physicsJoint.enableMotor();
  41784. joint.physicsJoint.setMotorSpeed(speed);
  41785. if (maxForce) {
  41786. this.setLimit(joint, maxForce);
  41787. }
  41788. }
  41789. };
  41790. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  41791. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  41792. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  41793. };
  41794. CannonJSPlugin.prototype.dispose = function () {
  41795. //nothing to do, actually.
  41796. };
  41797. return CannonJSPlugin;
  41798. }());
  41799. BABYLON.CannonJSPlugin = CannonJSPlugin;
  41800. })(BABYLON || (BABYLON = {}));
  41801. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  41802. var BABYLON;
  41803. (function (BABYLON) {
  41804. var OimoJSPlugin = (function () {
  41805. function OimoJSPlugin(iterations) {
  41806. this.name = "OimoJSPlugin";
  41807. this._tmpImpostorsArray = [];
  41808. this._tmpPositionVector = BABYLON.Vector3.Zero();
  41809. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  41810. this.world.worldscale(1);
  41811. this.world.clear();
  41812. //making sure no stats are calculated
  41813. this.world.isNoStat = true;
  41814. }
  41815. OimoJSPlugin.prototype.setGravity = function (gravity) {
  41816. this.world.gravity.copy(gravity);
  41817. };
  41818. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  41819. this.world.timeStep = timeStep;
  41820. };
  41821. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  41822. var _this = this;
  41823. impostors.forEach(function (impostor) {
  41824. impostor.beforeStep();
  41825. });
  41826. this.world.step();
  41827. impostors.forEach(function (impostor) {
  41828. impostor.afterStep();
  41829. //update the ordered impostors array
  41830. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  41831. });
  41832. //check for collisions
  41833. var contact = this.world.contacts;
  41834. while (contact !== null) {
  41835. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  41836. contact = contact.next;
  41837. continue;
  41838. }
  41839. //is this body colliding with any other? get the impostor
  41840. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  41841. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  41842. if (!mainImpostor || !collidingImpostor) {
  41843. contact = contact.next;
  41844. continue;
  41845. }
  41846. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  41847. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  41848. contact = contact.next;
  41849. }
  41850. };
  41851. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  41852. var mass = impostor.physicsBody.massInfo.mass;
  41853. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  41854. };
  41855. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  41856. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  41857. this.applyImpulse(impostor, force, contactPoint);
  41858. };
  41859. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  41860. var _this = this;
  41861. //parent-child relationship. Does this impostor has a parent impostor?
  41862. if (impostor.parent) {
  41863. if (impostor.physicsBody) {
  41864. this.removePhysicsBody(impostor);
  41865. //TODO is that needed?
  41866. impostor.forceUpdate();
  41867. }
  41868. return;
  41869. }
  41870. if (impostor.isBodyInitRequired()) {
  41871. var bodyConfig = {
  41872. name: impostor.uniqueId,
  41873. //Oimo must have mass, also for static objects.
  41874. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  41875. size: [],
  41876. type: [],
  41877. pos: [],
  41878. rot: [],
  41879. move: impostor.getParam("mass") !== 0,
  41880. //Supporting older versions of Oimo
  41881. world: this.world
  41882. };
  41883. var impostors = [impostor];
  41884. var addToArray = function (parent) {
  41885. if (!parent.getChildMeshes)
  41886. return;
  41887. parent.getChildMeshes().forEach(function (m) {
  41888. if (m.physicsImpostor) {
  41889. impostors.push(m.physicsImpostor);
  41890. m.physicsImpostor._init();
  41891. }
  41892. });
  41893. };
  41894. addToArray(impostor.object);
  41895. var checkWithEpsilon_1 = function (value) {
  41896. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  41897. };
  41898. impostors.forEach(function (i) {
  41899. //get the correct bounding box
  41900. var oldQuaternion = i.object.rotationQuaternion;
  41901. var rot = new OIMO.Euler().setFromQuaternion({
  41902. x: impostor.object.rotationQuaternion.x,
  41903. y: impostor.object.rotationQuaternion.y,
  41904. z: impostor.object.rotationQuaternion.z,
  41905. s: impostor.object.rotationQuaternion.w
  41906. });
  41907. var extendSize = i.getObjectExtendSize();
  41908. if (i === impostor) {
  41909. var center = impostor.getObjectCenter();
  41910. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  41911. //Can also use Array.prototype.push.apply
  41912. bodyConfig.pos.push(center.x);
  41913. bodyConfig.pos.push(center.y);
  41914. bodyConfig.pos.push(center.z);
  41915. //tmp solution
  41916. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  41917. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  41918. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  41919. }
  41920. else {
  41921. bodyConfig.pos.push(i.object.position.x);
  41922. bodyConfig.pos.push(i.object.position.y);
  41923. bodyConfig.pos.push(i.object.position.z);
  41924. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  41925. bodyConfig.rot.push(0);
  41926. bodyConfig.rot.push(0);
  41927. bodyConfig.rot.push(0);
  41928. }
  41929. // register mesh
  41930. switch (i.type) {
  41931. case BABYLON.PhysicsImpostor.ParticleImpostor:
  41932. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  41933. case BABYLON.PhysicsImpostor.SphereImpostor:
  41934. var radiusX = extendSize.x;
  41935. var radiusY = extendSize.y;
  41936. var radiusZ = extendSize.z;
  41937. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  41938. bodyConfig.type.push('sphere');
  41939. //due to the way oimo works with compounds, add 3 times
  41940. bodyConfig.size.push(size);
  41941. bodyConfig.size.push(size);
  41942. bodyConfig.size.push(size);
  41943. break;
  41944. case BABYLON.PhysicsImpostor.CylinderImpostor:
  41945. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  41946. var sizeY = checkWithEpsilon_1(extendSize.y);
  41947. bodyConfig.type.push('cylinder');
  41948. bodyConfig.size.push(sizeX);
  41949. bodyConfig.size.push(sizeY);
  41950. //due to the way oimo works with compounds, add one more value.
  41951. bodyConfig.size.push(sizeY);
  41952. break;
  41953. case BABYLON.PhysicsImpostor.PlaneImpostor:
  41954. case BABYLON.PhysicsImpostor.BoxImpostor:
  41955. default:
  41956. var sizeX = checkWithEpsilon_1(extendSize.x);
  41957. var sizeY = checkWithEpsilon_1(extendSize.y);
  41958. var sizeZ = checkWithEpsilon_1(extendSize.z);
  41959. bodyConfig.type.push('box');
  41960. bodyConfig.size.push(sizeX);
  41961. bodyConfig.size.push(sizeY);
  41962. bodyConfig.size.push(sizeZ);
  41963. break;
  41964. }
  41965. //actually not needed, but hey...
  41966. i.object.rotationQuaternion = oldQuaternion;
  41967. });
  41968. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  41969. }
  41970. else {
  41971. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  41972. }
  41973. impostor.setDeltaPosition(this._tmpPositionVector);
  41974. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  41975. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  41976. };
  41977. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  41978. //impostor.physicsBody.dispose();
  41979. //Same as : (older oimo versions)
  41980. this.world.removeRigidBody(impostor.physicsBody);
  41981. };
  41982. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  41983. var mainBody = impostorJoint.mainImpostor.physicsBody;
  41984. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  41985. if (!mainBody || !connectedBody) {
  41986. return;
  41987. }
  41988. var jointData = impostorJoint.joint.jointData;
  41989. var options = jointData.nativeParams || {};
  41990. var type;
  41991. var nativeJointData = {
  41992. body1: mainBody,
  41993. body2: connectedBody,
  41994. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  41995. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  41996. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  41997. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  41998. min: options.min,
  41999. max: options.max,
  42000. collision: options.collision || jointData.collision,
  42001. spring: options.spring,
  42002. //supporting older version of Oimo
  42003. world: this.world
  42004. };
  42005. switch (impostorJoint.joint.type) {
  42006. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  42007. type = "jointBall";
  42008. break;
  42009. case BABYLON.PhysicsJoint.SpringJoint:
  42010. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  42011. var springData = jointData;
  42012. nativeJointData.min = springData.length || nativeJointData.min;
  42013. //Max should also be set, just make sure it is at least min
  42014. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  42015. case BABYLON.PhysicsJoint.DistanceJoint:
  42016. type = "jointDistance";
  42017. nativeJointData.max = jointData.maxDistance;
  42018. break;
  42019. case BABYLON.PhysicsJoint.PrismaticJoint:
  42020. type = "jointPrisme";
  42021. break;
  42022. case BABYLON.PhysicsJoint.SliderJoint:
  42023. type = "jointSlide";
  42024. break;
  42025. case BABYLON.PhysicsJoint.WheelJoint:
  42026. type = "jointWheel";
  42027. break;
  42028. case BABYLON.PhysicsJoint.HingeJoint:
  42029. default:
  42030. type = "jointHinge";
  42031. break;
  42032. }
  42033. nativeJointData.type = type;
  42034. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  42035. };
  42036. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  42037. //Bug in Oimo prevents us from disposing a joint in the playground
  42038. //joint.joint.physicsJoint.dispose();
  42039. //So we will bruteforce it!
  42040. try {
  42041. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  42042. }
  42043. catch (e) {
  42044. BABYLON.Tools.Warn(e);
  42045. }
  42046. };
  42047. OimoJSPlugin.prototype.isSupported = function () {
  42048. return OIMO !== undefined;
  42049. };
  42050. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  42051. if (!impostor.physicsBody.sleeping) {
  42052. //TODO check that
  42053. if (impostor.physicsBody.shapes.next) {
  42054. var parentShape = this._getLastShape(impostor.physicsBody);
  42055. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  42056. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  42057. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  42058. }
  42059. else {
  42060. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  42061. }
  42062. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  42063. impostor.object.rotationQuaternion.normalize();
  42064. }
  42065. };
  42066. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  42067. var body = impostor.physicsBody;
  42068. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  42069. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  42070. body.syncShapes();
  42071. body.awake();
  42072. };
  42073. OimoJSPlugin.prototype._getLastShape = function (body) {
  42074. var lastShape = body.shapes;
  42075. while (lastShape.next) {
  42076. lastShape = lastShape.next;
  42077. }
  42078. return lastShape;
  42079. };
  42080. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  42081. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  42082. };
  42083. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  42084. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  42085. };
  42086. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  42087. var v = impostor.physicsBody.linearVelocity;
  42088. if (!v)
  42089. return null;
  42090. return new BABYLON.Vector3(v.x, v.y, v.z);
  42091. };
  42092. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  42093. var v = impostor.physicsBody.angularVelocity;
  42094. if (!v)
  42095. return null;
  42096. return new BABYLON.Vector3(v.x, v.y, v.z);
  42097. };
  42098. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  42099. var staticBody = mass === 0;
  42100. //this will actually set the body's density and not its mass.
  42101. //But this is how oimo treats the mass variable.
  42102. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  42103. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  42104. };
  42105. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  42106. impostor.physicsBody.sleep();
  42107. };
  42108. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  42109. impostor.physicsBody.awake();
  42110. };
  42111. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  42112. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  42113. if (minDistance !== void 0) {
  42114. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  42115. }
  42116. };
  42117. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  42118. //TODO separate rotational and transational motors.
  42119. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  42120. if (motor) {
  42121. motor.setMotor(speed, maxForce);
  42122. }
  42123. };
  42124. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  42125. //TODO separate rotational and transational motors.
  42126. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  42127. if (motor) {
  42128. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  42129. }
  42130. };
  42131. OimoJSPlugin.prototype.dispose = function () {
  42132. this.world.clear();
  42133. };
  42134. return OimoJSPlugin;
  42135. }());
  42136. BABYLON.OimoJSPlugin = OimoJSPlugin;
  42137. })(BABYLON || (BABYLON = {}));
  42138. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  42139. var BABYLON;
  42140. (function (BABYLON) {
  42141. var DisplayPassPostProcess = (function (_super) {
  42142. __extends(DisplayPassPostProcess, _super);
  42143. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  42144. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  42145. }
  42146. return DisplayPassPostProcess;
  42147. }(BABYLON.PostProcess));
  42148. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  42149. })(BABYLON || (BABYLON = {}));
  42150. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  42151. var BABYLON;
  42152. (function (BABYLON) {
  42153. var SimplificationSettings = (function () {
  42154. function SimplificationSettings(quality, distance, optimizeMesh) {
  42155. this.quality = quality;
  42156. this.distance = distance;
  42157. this.optimizeMesh = optimizeMesh;
  42158. }
  42159. return SimplificationSettings;
  42160. }());
  42161. BABYLON.SimplificationSettings = SimplificationSettings;
  42162. var SimplificationQueue = (function () {
  42163. function SimplificationQueue() {
  42164. this.running = false;
  42165. this._simplificationArray = [];
  42166. }
  42167. SimplificationQueue.prototype.addTask = function (task) {
  42168. this._simplificationArray.push(task);
  42169. };
  42170. SimplificationQueue.prototype.executeNext = function () {
  42171. var task = this._simplificationArray.pop();
  42172. if (task) {
  42173. this.running = true;
  42174. this.runSimplification(task);
  42175. }
  42176. else {
  42177. this.running = false;
  42178. }
  42179. };
  42180. SimplificationQueue.prototype.runSimplification = function (task) {
  42181. var _this = this;
  42182. if (task.parallelProcessing) {
  42183. //parallel simplifier
  42184. task.settings.forEach(function (setting) {
  42185. var simplifier = _this.getSimplifier(task);
  42186. simplifier.simplify(setting, function (newMesh) {
  42187. task.mesh.addLODLevel(setting.distance, newMesh);
  42188. newMesh.isVisible = true;
  42189. //check if it is the last
  42190. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  42191. //all done, run the success callback.
  42192. task.successCallback();
  42193. }
  42194. _this.executeNext();
  42195. });
  42196. });
  42197. }
  42198. else {
  42199. //single simplifier.
  42200. var simplifier = this.getSimplifier(task);
  42201. var runDecimation = function (setting, callback) {
  42202. simplifier.simplify(setting, function (newMesh) {
  42203. task.mesh.addLODLevel(setting.distance, newMesh);
  42204. newMesh.isVisible = true;
  42205. //run the next quality level
  42206. callback();
  42207. });
  42208. };
  42209. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  42210. runDecimation(task.settings[loop.index], function () {
  42211. loop.executeNext();
  42212. });
  42213. }, function () {
  42214. //execution ended, run the success callback.
  42215. if (task.successCallback) {
  42216. task.successCallback();
  42217. }
  42218. _this.executeNext();
  42219. });
  42220. }
  42221. };
  42222. SimplificationQueue.prototype.getSimplifier = function (task) {
  42223. switch (task.simplificationType) {
  42224. case SimplificationType.QUADRATIC:
  42225. default:
  42226. return new QuadraticErrorSimplification(task.mesh);
  42227. }
  42228. };
  42229. return SimplificationQueue;
  42230. }());
  42231. BABYLON.SimplificationQueue = SimplificationQueue;
  42232. /**
  42233. * The implemented types of simplification.
  42234. * At the moment only Quadratic Error Decimation is implemented.
  42235. */
  42236. var SimplificationType;
  42237. (function (SimplificationType) {
  42238. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  42239. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  42240. var DecimationTriangle = (function () {
  42241. function DecimationTriangle(vertices) {
  42242. this.vertices = vertices;
  42243. this.error = new Array(4);
  42244. this.deleted = false;
  42245. this.isDirty = false;
  42246. this.deletePending = false;
  42247. this.borderFactor = 0;
  42248. }
  42249. return DecimationTriangle;
  42250. }());
  42251. BABYLON.DecimationTriangle = DecimationTriangle;
  42252. var DecimationVertex = (function () {
  42253. function DecimationVertex(position, id) {
  42254. this.position = position;
  42255. this.id = id;
  42256. this.isBorder = true;
  42257. this.q = new QuadraticMatrix();
  42258. this.triangleCount = 0;
  42259. this.triangleStart = 0;
  42260. this.originalOffsets = [];
  42261. }
  42262. DecimationVertex.prototype.updatePosition = function (newPosition) {
  42263. this.position.copyFrom(newPosition);
  42264. };
  42265. return DecimationVertex;
  42266. }());
  42267. BABYLON.DecimationVertex = DecimationVertex;
  42268. var QuadraticMatrix = (function () {
  42269. function QuadraticMatrix(data) {
  42270. this.data = new Array(10);
  42271. for (var i = 0; i < 10; ++i) {
  42272. if (data && data[i]) {
  42273. this.data[i] = data[i];
  42274. }
  42275. else {
  42276. this.data[i] = 0;
  42277. }
  42278. }
  42279. }
  42280. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  42281. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  42282. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  42283. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  42284. return det;
  42285. };
  42286. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  42287. for (var i = 0; i < 10; ++i) {
  42288. this.data[i] += matrix.data[i];
  42289. }
  42290. };
  42291. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  42292. for (var i = 0; i < 10; ++i) {
  42293. this.data[i] += data[i];
  42294. }
  42295. };
  42296. QuadraticMatrix.prototype.add = function (matrix) {
  42297. var m = new QuadraticMatrix();
  42298. for (var i = 0; i < 10; ++i) {
  42299. m.data[i] = this.data[i] + matrix.data[i];
  42300. }
  42301. return m;
  42302. };
  42303. QuadraticMatrix.FromData = function (a, b, c, d) {
  42304. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  42305. };
  42306. //returning an array to avoid garbage collection
  42307. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  42308. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  42309. };
  42310. return QuadraticMatrix;
  42311. }());
  42312. BABYLON.QuadraticMatrix = QuadraticMatrix;
  42313. var Reference = (function () {
  42314. function Reference(vertexId, triangleId) {
  42315. this.vertexId = vertexId;
  42316. this.triangleId = triangleId;
  42317. }
  42318. return Reference;
  42319. }());
  42320. BABYLON.Reference = Reference;
  42321. /**
  42322. * An implementation of the Quadratic Error simplification algorithm.
  42323. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  42324. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  42325. * @author RaananW
  42326. */
  42327. var QuadraticErrorSimplification = (function () {
  42328. function QuadraticErrorSimplification(_mesh) {
  42329. this._mesh = _mesh;
  42330. this.initialized = false;
  42331. this.syncIterations = 5000;
  42332. this.aggressiveness = 7;
  42333. this.decimationIterations = 100;
  42334. this.boundingBoxEpsilon = BABYLON.Epsilon;
  42335. }
  42336. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  42337. var _this = this;
  42338. this.initDecimatedMesh();
  42339. //iterating through the submeshes array, one after the other.
  42340. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  42341. _this.initWithMesh(loop.index, function () {
  42342. _this.runDecimation(settings, loop.index, function () {
  42343. loop.executeNext();
  42344. });
  42345. }, settings.optimizeMesh);
  42346. }, function () {
  42347. setTimeout(function () {
  42348. successCallback(_this._reconstructedMesh);
  42349. }, 0);
  42350. });
  42351. };
  42352. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  42353. var _this = this;
  42354. var gCount = 0;
  42355. triangle.vertices.forEach(function (vertex) {
  42356. var count = 0;
  42357. var vPos = vertex.position;
  42358. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  42359. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  42360. ++count;
  42361. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  42362. ++count;
  42363. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  42364. ++count;
  42365. if (count > 1) {
  42366. ++gCount;
  42367. }
  42368. ;
  42369. });
  42370. if (gCount > 1) {
  42371. console.log(triangle, gCount);
  42372. }
  42373. return gCount > 1;
  42374. };
  42375. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  42376. var _this = this;
  42377. var targetCount = ~~(this.triangles.length * settings.quality);
  42378. var deletedTriangles = 0;
  42379. var triangleCount = this.triangles.length;
  42380. var iterationFunction = function (iteration, callback) {
  42381. setTimeout(function () {
  42382. if (iteration % 5 === 0) {
  42383. _this.updateMesh(iteration === 0);
  42384. }
  42385. for (var i = 0; i < _this.triangles.length; ++i) {
  42386. _this.triangles[i].isDirty = false;
  42387. }
  42388. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  42389. var trianglesIterator = function (i) {
  42390. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  42391. var t = _this.triangles[tIdx];
  42392. if (!t)
  42393. return;
  42394. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  42395. return;
  42396. }
  42397. for (var j = 0; j < 3; ++j) {
  42398. if (t.error[j] < threshold) {
  42399. var deleted0 = [];
  42400. var deleted1 = [];
  42401. var v0 = t.vertices[j];
  42402. var v1 = t.vertices[(j + 1) % 3];
  42403. if (v0.isBorder || v1.isBorder)
  42404. continue;
  42405. var p = BABYLON.Vector3.Zero();
  42406. var n = BABYLON.Vector3.Zero();
  42407. var uv = BABYLON.Vector2.Zero();
  42408. var color = new BABYLON.Color4(0, 0, 0, 1);
  42409. _this.calculateError(v0, v1, p, n, uv, color);
  42410. var delTr = [];
  42411. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  42412. continue;
  42413. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  42414. continue;
  42415. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  42416. continue;
  42417. var uniqueArray = [];
  42418. delTr.forEach(function (deletedT) {
  42419. if (uniqueArray.indexOf(deletedT) === -1) {
  42420. deletedT.deletePending = true;
  42421. uniqueArray.push(deletedT);
  42422. }
  42423. });
  42424. if (uniqueArray.length % 2 !== 0) {
  42425. continue;
  42426. }
  42427. v0.q = v1.q.add(v0.q);
  42428. v0.updatePosition(p);
  42429. var tStart = _this.references.length;
  42430. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  42431. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  42432. var tCount = _this.references.length - tStart;
  42433. if (tCount <= v0.triangleCount) {
  42434. if (tCount) {
  42435. for (var c = 0; c < tCount; c++) {
  42436. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  42437. }
  42438. }
  42439. }
  42440. else {
  42441. v0.triangleStart = tStart;
  42442. }
  42443. v0.triangleCount = tCount;
  42444. break;
  42445. }
  42446. }
  42447. };
  42448. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  42449. }, 0);
  42450. };
  42451. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  42452. if (triangleCount - deletedTriangles <= targetCount)
  42453. loop.breakLoop();
  42454. else {
  42455. iterationFunction(loop.index, function () {
  42456. loop.executeNext();
  42457. });
  42458. }
  42459. }, function () {
  42460. setTimeout(function () {
  42461. //reconstruct this part of the mesh
  42462. _this.reconstructMesh(submeshIndex);
  42463. successCallback();
  42464. }, 0);
  42465. });
  42466. };
  42467. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  42468. var _this = this;
  42469. this.vertices = [];
  42470. this.triangles = [];
  42471. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42472. var indices = this._mesh.getIndices();
  42473. var submesh = this._mesh.subMeshes[submeshIndex];
  42474. var findInVertices = function (positionToSearch) {
  42475. if (optimizeMesh) {
  42476. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  42477. if (_this.vertices[ii].position.equals(positionToSearch)) {
  42478. return _this.vertices[ii];
  42479. }
  42480. }
  42481. }
  42482. return null;
  42483. };
  42484. var vertexReferences = [];
  42485. var vertexInit = function (i) {
  42486. var offset = i + submesh.verticesStart;
  42487. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  42488. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  42489. vertex.originalOffsets.push(offset);
  42490. if (vertex.id === _this.vertices.length) {
  42491. _this.vertices.push(vertex);
  42492. }
  42493. vertexReferences.push(vertex.id);
  42494. };
  42495. //var totalVertices = mesh.getTotalVertices();
  42496. var totalVertices = submesh.verticesCount;
  42497. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  42498. var indicesInit = function (i) {
  42499. var offset = (submesh.indexStart / 3) + i;
  42500. var pos = (offset * 3);
  42501. var i0 = indices[pos + 0];
  42502. var i1 = indices[pos + 1];
  42503. var i2 = indices[pos + 2];
  42504. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  42505. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  42506. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  42507. var triangle = new DecimationTriangle([v0, v1, v2]);
  42508. triangle.originalOffset = pos;
  42509. _this.triangles.push(triangle);
  42510. };
  42511. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  42512. _this.init(callback);
  42513. });
  42514. });
  42515. };
  42516. QuadraticErrorSimplification.prototype.init = function (callback) {
  42517. var _this = this;
  42518. var triangleInit1 = function (i) {
  42519. var t = _this.triangles[i];
  42520. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  42521. for (var j = 0; j < 3; j++) {
  42522. 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))));
  42523. }
  42524. };
  42525. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  42526. var triangleInit2 = function (i) {
  42527. var t = _this.triangles[i];
  42528. for (var j = 0; j < 3; ++j) {
  42529. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  42530. }
  42531. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  42532. };
  42533. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  42534. _this.initialized = true;
  42535. callback();
  42536. });
  42537. });
  42538. };
  42539. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  42540. var newTriangles = [];
  42541. var i;
  42542. for (i = 0; i < this.vertices.length; ++i) {
  42543. this.vertices[i].triangleCount = 0;
  42544. }
  42545. var t;
  42546. var j;
  42547. for (i = 0; i < this.triangles.length; ++i) {
  42548. if (!this.triangles[i].deleted) {
  42549. t = this.triangles[i];
  42550. for (j = 0; j < 3; ++j) {
  42551. t.vertices[j].triangleCount = 1;
  42552. }
  42553. newTriangles.push(t);
  42554. }
  42555. }
  42556. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  42557. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  42558. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  42559. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  42560. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42561. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42562. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42563. var vertexCount = 0;
  42564. for (i = 0; i < this.vertices.length; ++i) {
  42565. var vertex = this.vertices[i];
  42566. vertex.id = vertexCount;
  42567. if (vertex.triangleCount) {
  42568. vertex.originalOffsets.forEach(function (originalOffset) {
  42569. newPositionData.push(vertex.position.x);
  42570. newPositionData.push(vertex.position.y);
  42571. newPositionData.push(vertex.position.z);
  42572. newNormalData.push(normalData[originalOffset * 3]);
  42573. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  42574. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  42575. if (uvs && uvs.length) {
  42576. newUVsData.push(uvs[(originalOffset * 2)]);
  42577. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  42578. }
  42579. else if (colorsData && colorsData.length) {
  42580. newColorsData.push(colorsData[(originalOffset * 4)]);
  42581. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  42582. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  42583. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  42584. }
  42585. ++vertexCount;
  42586. });
  42587. }
  42588. }
  42589. var startingIndex = this._reconstructedMesh.getTotalIndices();
  42590. var startingVertex = this._reconstructedMesh.getTotalVertices();
  42591. var submeshesArray = this._reconstructedMesh.subMeshes;
  42592. this._reconstructedMesh.subMeshes = [];
  42593. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  42594. var originalIndices = this._mesh.getIndices();
  42595. for (i = 0; i < newTriangles.length; ++i) {
  42596. t = newTriangles[i]; //now get the new referencing point for each vertex
  42597. [0, 1, 2].forEach(function (idx) {
  42598. var id = originalIndices[t.originalOffset + idx];
  42599. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  42600. if (offset < 0)
  42601. offset = 0;
  42602. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  42603. });
  42604. }
  42605. //overwriting the old vertex buffers and indices.
  42606. this._reconstructedMesh.setIndices(newIndicesArray);
  42607. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  42608. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  42609. if (newUVsData.length > 0)
  42610. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  42611. if (newColorsData.length > 0)
  42612. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  42613. //create submesh
  42614. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  42615. if (submeshIndex > 0) {
  42616. this._reconstructedMesh.subMeshes = [];
  42617. submeshesArray.forEach(function (submesh) {
  42618. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  42619. });
  42620. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  42621. }
  42622. };
  42623. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  42624. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  42625. this._reconstructedMesh.material = this._mesh.material;
  42626. this._reconstructedMesh.parent = this._mesh.parent;
  42627. this._reconstructedMesh.isVisible = false;
  42628. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  42629. };
  42630. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  42631. for (var i = 0; i < vertex1.triangleCount; ++i) {
  42632. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  42633. if (t.deleted)
  42634. continue;
  42635. var s = this.references[vertex1.triangleStart + i].vertexId;
  42636. var v1 = t.vertices[(s + 1) % 3];
  42637. var v2 = t.vertices[(s + 2) % 3];
  42638. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  42639. deletedArray[i] = true;
  42640. delTr.push(t);
  42641. continue;
  42642. }
  42643. var d1 = v1.position.subtract(point);
  42644. d1 = d1.normalize();
  42645. var d2 = v2.position.subtract(point);
  42646. d2 = d2.normalize();
  42647. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  42648. return true;
  42649. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  42650. deletedArray[i] = false;
  42651. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  42652. return true;
  42653. }
  42654. return false;
  42655. };
  42656. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  42657. var newDeleted = deletedTriangles;
  42658. for (var i = 0; i < vertex.triangleCount; ++i) {
  42659. var ref = this.references[vertex.triangleStart + i];
  42660. var t = this.triangles[ref.triangleId];
  42661. if (t.deleted)
  42662. continue;
  42663. if (deletedArray[i] && t.deletePending) {
  42664. t.deleted = true;
  42665. newDeleted++;
  42666. continue;
  42667. }
  42668. t.vertices[ref.vertexId] = origVertex;
  42669. t.isDirty = true;
  42670. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  42671. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  42672. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  42673. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  42674. this.references.push(ref);
  42675. }
  42676. return newDeleted;
  42677. };
  42678. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  42679. for (var i = 0; i < this.vertices.length; ++i) {
  42680. var vCount = [];
  42681. var vId = [];
  42682. var v = this.vertices[i];
  42683. var j;
  42684. for (j = 0; j < v.triangleCount; ++j) {
  42685. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  42686. for (var ii = 0; ii < 3; ii++) {
  42687. var ofs = 0;
  42688. var vv = triangle.vertices[ii];
  42689. while (ofs < vCount.length) {
  42690. if (vId[ofs] === vv.id)
  42691. break;
  42692. ++ofs;
  42693. }
  42694. if (ofs === vCount.length) {
  42695. vCount.push(1);
  42696. vId.push(vv.id);
  42697. }
  42698. else {
  42699. vCount[ofs]++;
  42700. }
  42701. }
  42702. }
  42703. for (j = 0; j < vCount.length; ++j) {
  42704. if (vCount[j] === 1) {
  42705. this.vertices[vId[j]].isBorder = true;
  42706. }
  42707. else {
  42708. this.vertices[vId[j]].isBorder = false;
  42709. }
  42710. }
  42711. }
  42712. };
  42713. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  42714. if (identifyBorders === void 0) { identifyBorders = false; }
  42715. var i;
  42716. if (!identifyBorders) {
  42717. var newTrianglesVector = [];
  42718. for (i = 0; i < this.triangles.length; ++i) {
  42719. if (!this.triangles[i].deleted) {
  42720. newTrianglesVector.push(this.triangles[i]);
  42721. }
  42722. }
  42723. this.triangles = newTrianglesVector;
  42724. }
  42725. for (i = 0; i < this.vertices.length; ++i) {
  42726. this.vertices[i].triangleCount = 0;
  42727. this.vertices[i].triangleStart = 0;
  42728. }
  42729. var t;
  42730. var j;
  42731. var v;
  42732. for (i = 0; i < this.triangles.length; ++i) {
  42733. t = this.triangles[i];
  42734. for (j = 0; j < 3; ++j) {
  42735. v = t.vertices[j];
  42736. v.triangleCount++;
  42737. }
  42738. }
  42739. var tStart = 0;
  42740. for (i = 0; i < this.vertices.length; ++i) {
  42741. this.vertices[i].triangleStart = tStart;
  42742. tStart += this.vertices[i].triangleCount;
  42743. this.vertices[i].triangleCount = 0;
  42744. }
  42745. var newReferences = new Array(this.triangles.length * 3);
  42746. for (i = 0; i < this.triangles.length; ++i) {
  42747. t = this.triangles[i];
  42748. for (j = 0; j < 3; ++j) {
  42749. v = t.vertices[j];
  42750. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  42751. v.triangleCount++;
  42752. }
  42753. }
  42754. this.references = newReferences;
  42755. if (identifyBorders) {
  42756. this.identifyBorder();
  42757. }
  42758. };
  42759. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  42760. var x = point.x;
  42761. var y = point.y;
  42762. var z = point.z;
  42763. 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
  42764. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  42765. };
  42766. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  42767. var q = vertex1.q.add(vertex2.q);
  42768. var border = vertex1.isBorder && vertex2.isBorder;
  42769. var error = 0;
  42770. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  42771. if (qDet !== 0 && !border) {
  42772. if (!pointResult) {
  42773. pointResult = BABYLON.Vector3.Zero();
  42774. }
  42775. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  42776. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  42777. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  42778. error = this.vertexError(q, pointResult);
  42779. }
  42780. else {
  42781. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  42782. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  42783. var error1 = this.vertexError(q, vertex1.position);
  42784. var error2 = this.vertexError(q, vertex2.position);
  42785. var error3 = this.vertexError(q, p3);
  42786. error = Math.min(error1, error2, error3);
  42787. if (error === error1) {
  42788. if (pointResult) {
  42789. pointResult.copyFrom(vertex1.position);
  42790. }
  42791. }
  42792. else if (error === error2) {
  42793. if (pointResult) {
  42794. pointResult.copyFrom(vertex2.position);
  42795. }
  42796. }
  42797. else {
  42798. if (pointResult) {
  42799. pointResult.copyFrom(p3);
  42800. }
  42801. }
  42802. }
  42803. return error;
  42804. };
  42805. return QuadraticErrorSimplification;
  42806. }());
  42807. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  42808. })(BABYLON || (BABYLON = {}));
  42809. //# sourceMappingURL=babylon.meshSimplification.js.map
  42810. var BABYLON;
  42811. (function (BABYLON) {
  42812. var serializedGeometries = [];
  42813. var serializeGeometry = function (geometry, serializationGeometries) {
  42814. if (serializedGeometries[geometry.id]) {
  42815. return;
  42816. }
  42817. if (geometry.doNotSerialize) {
  42818. return;
  42819. }
  42820. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  42821. serializationGeometries.boxes.push(geometry.serialize());
  42822. }
  42823. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  42824. serializationGeometries.spheres.push(geometry.serialize());
  42825. }
  42826. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  42827. serializationGeometries.cylinders.push(geometry.serialize());
  42828. }
  42829. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  42830. serializationGeometries.toruses.push(geometry.serialize());
  42831. }
  42832. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  42833. serializationGeometries.grounds.push(geometry.serialize());
  42834. }
  42835. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  42836. serializationGeometries.planes.push(geometry.serialize());
  42837. }
  42838. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  42839. serializationGeometries.torusKnots.push(geometry.serialize());
  42840. }
  42841. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  42842. throw new Error("Unknown primitive type");
  42843. }
  42844. else {
  42845. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  42846. }
  42847. serializedGeometries[geometry.id] = true;
  42848. };
  42849. var serializeMesh = function (mesh, serializationScene) {
  42850. var serializationObject = {};
  42851. serializationObject.name = mesh.name;
  42852. serializationObject.id = mesh.id;
  42853. if (BABYLON.Tags.HasTags(mesh)) {
  42854. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  42855. }
  42856. serializationObject.position = mesh.position.asArray();
  42857. if (mesh.rotationQuaternion) {
  42858. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  42859. }
  42860. else if (mesh.rotation) {
  42861. serializationObject.rotation = mesh.rotation.asArray();
  42862. }
  42863. serializationObject.scaling = mesh.scaling.asArray();
  42864. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  42865. serializationObject.isEnabled = mesh.isEnabled();
  42866. serializationObject.isVisible = mesh.isVisible;
  42867. serializationObject.infiniteDistance = mesh.infiniteDistance;
  42868. serializationObject.pickable = mesh.isPickable;
  42869. serializationObject.receiveShadows = mesh.receiveShadows;
  42870. serializationObject.billboardMode = mesh.billboardMode;
  42871. serializationObject.visibility = mesh.visibility;
  42872. serializationObject.checkCollisions = mesh.checkCollisions;
  42873. serializationObject.isBlocker = mesh.isBlocker;
  42874. // Parent
  42875. if (mesh.parent) {
  42876. serializationObject.parentId = mesh.parent.id;
  42877. }
  42878. // Geometry
  42879. var geometry = mesh._geometry;
  42880. if (geometry) {
  42881. var geometryId = geometry.id;
  42882. serializationObject.geometryId = geometryId;
  42883. if (!mesh.getScene().getGeometryByID(geometryId)) {
  42884. // 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
  42885. serializeGeometry(geometry, serializationScene.geometries);
  42886. }
  42887. // SubMeshes
  42888. serializationObject.subMeshes = [];
  42889. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  42890. var subMesh = mesh.subMeshes[subIndex];
  42891. serializationObject.subMeshes.push({
  42892. materialIndex: subMesh.materialIndex,
  42893. verticesStart: subMesh.verticesStart,
  42894. verticesCount: subMesh.verticesCount,
  42895. indexStart: subMesh.indexStart,
  42896. indexCount: subMesh.indexCount
  42897. });
  42898. }
  42899. }
  42900. // Material
  42901. if (mesh.material) {
  42902. serializationObject.materialId = mesh.material.id;
  42903. }
  42904. else {
  42905. mesh.material = null;
  42906. }
  42907. // Skeleton
  42908. if (mesh.skeleton) {
  42909. serializationObject.skeletonId = mesh.skeleton.id;
  42910. }
  42911. // Physics
  42912. //TODO implement correct serialization for physics impostors.
  42913. if (mesh.getPhysicsImpostor()) {
  42914. serializationObject.physicsMass = mesh.getPhysicsMass();
  42915. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  42916. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  42917. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  42918. }
  42919. // Metadata
  42920. if (mesh.metadata) {
  42921. serializationObject.metadata = mesh.metadata;
  42922. }
  42923. // Instances
  42924. serializationObject.instances = [];
  42925. for (var index = 0; index < mesh.instances.length; index++) {
  42926. var instance = mesh.instances[index];
  42927. var serializationInstance = {
  42928. name: instance.name,
  42929. position: instance.position.asArray(),
  42930. scaling: instance.scaling.asArray()
  42931. };
  42932. if (instance.rotationQuaternion) {
  42933. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  42934. }
  42935. else if (instance.rotation) {
  42936. serializationInstance.rotation = instance.rotation.asArray();
  42937. }
  42938. serializationObject.instances.push(serializationInstance);
  42939. // Animations
  42940. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  42941. serializationInstance.ranges = instance.serializeAnimationRanges();
  42942. }
  42943. // Animations
  42944. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  42945. serializationObject.ranges = mesh.serializeAnimationRanges();
  42946. // Layer mask
  42947. serializationObject.layerMask = mesh.layerMask;
  42948. // Alpha
  42949. serializationObject.alphaIndex = mesh.alphaIndex;
  42950. serializationObject.hasVertexAlpha = mesh.hasVertexAlpha;
  42951. // Overlay
  42952. serializationObject.overlayAlpha = mesh.overlayAlpha;
  42953. serializationObject.overlayColor = mesh.overlayColor.asArray();
  42954. serializationObject.renderOverlay = mesh.renderOverlay;
  42955. // Fog
  42956. serializationObject.applyFog = mesh.applyFog;
  42957. // Action Manager
  42958. if (mesh.actionManager) {
  42959. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  42960. }
  42961. return serializationObject;
  42962. };
  42963. var finalizeSingleMesh = function (mesh, serializationObject) {
  42964. //only works if the mesh is already loaded
  42965. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  42966. //serialize material
  42967. if (mesh.material) {
  42968. if (mesh.material instanceof BABYLON.StandardMaterial) {
  42969. serializationObject.materials = serializationObject.materials || [];
  42970. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  42971. serializationObject.materials.push(mesh.material.serialize());
  42972. }
  42973. }
  42974. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  42975. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  42976. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  42977. serializationObject.multiMaterials.push(mesh.material.serialize());
  42978. }
  42979. }
  42980. }
  42981. //serialize geometry
  42982. var geometry = mesh._geometry;
  42983. if (geometry) {
  42984. if (!serializationObject.geometries) {
  42985. serializationObject.geometries = {};
  42986. serializationObject.geometries.boxes = [];
  42987. serializationObject.geometries.spheres = [];
  42988. serializationObject.geometries.cylinders = [];
  42989. serializationObject.geometries.toruses = [];
  42990. serializationObject.geometries.grounds = [];
  42991. serializationObject.geometries.planes = [];
  42992. serializationObject.geometries.torusKnots = [];
  42993. serializationObject.geometries.vertexData = [];
  42994. }
  42995. serializeGeometry(geometry, serializationObject.geometries);
  42996. }
  42997. // Skeletons
  42998. if (mesh.skeleton) {
  42999. serializationObject.skeletons = serializationObject.skeletons || [];
  43000. serializationObject.skeletons.push(mesh.skeleton.serialize());
  43001. }
  43002. //serialize the actual mesh
  43003. serializationObject.meshes = serializationObject.meshes || [];
  43004. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  43005. }
  43006. };
  43007. var SceneSerializer = (function () {
  43008. function SceneSerializer() {
  43009. }
  43010. SceneSerializer.ClearCache = function () {
  43011. serializedGeometries = [];
  43012. };
  43013. SceneSerializer.Serialize = function (scene) {
  43014. var serializationObject = {};
  43015. // Scene
  43016. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  43017. serializationObject.autoClear = scene.autoClear;
  43018. serializationObject.clearColor = scene.clearColor.asArray();
  43019. serializationObject.ambientColor = scene.ambientColor.asArray();
  43020. serializationObject.gravity = scene.gravity.asArray();
  43021. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  43022. serializationObject.workerCollisions = scene.workerCollisions;
  43023. // Fog
  43024. if (scene.fogMode && scene.fogMode !== 0) {
  43025. serializationObject.fogMode = scene.fogMode;
  43026. serializationObject.fogColor = scene.fogColor.asArray();
  43027. serializationObject.fogStart = scene.fogStart;
  43028. serializationObject.fogEnd = scene.fogEnd;
  43029. serializationObject.fogDensity = scene.fogDensity;
  43030. }
  43031. //Physics
  43032. if (scene.isPhysicsEnabled()) {
  43033. serializationObject.physicsEnabled = true;
  43034. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  43035. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  43036. }
  43037. // Metadata
  43038. if (scene.metadata) {
  43039. serializationObject.metadata = scene.metadata;
  43040. }
  43041. // Lights
  43042. serializationObject.lights = [];
  43043. var index;
  43044. var light;
  43045. for (index = 0; index < scene.lights.length; index++) {
  43046. light = scene.lights[index];
  43047. if (!light.doNotSerialize) {
  43048. serializationObject.lights.push(light.serialize());
  43049. }
  43050. }
  43051. // Cameras
  43052. serializationObject.cameras = [];
  43053. for (index = 0; index < scene.cameras.length; index++) {
  43054. var camera = scene.cameras[index];
  43055. if (!camera.doNotSerialize) {
  43056. serializationObject.cameras.push(camera.serialize());
  43057. }
  43058. }
  43059. if (scene.activeCamera) {
  43060. serializationObject.activeCameraID = scene.activeCamera.id;
  43061. }
  43062. // Animations
  43063. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  43064. // Materials
  43065. serializationObject.materials = [];
  43066. serializationObject.multiMaterials = [];
  43067. var material;
  43068. for (index = 0; index < scene.materials.length; index++) {
  43069. material = scene.materials[index];
  43070. if (!material.doNotSerialize) {
  43071. serializationObject.materials.push(material.serialize());
  43072. }
  43073. }
  43074. // MultiMaterials
  43075. serializationObject.multiMaterials = [];
  43076. for (index = 0; index < scene.multiMaterials.length; index++) {
  43077. var multiMaterial = scene.multiMaterials[index];
  43078. serializationObject.multiMaterials.push(multiMaterial.serialize());
  43079. }
  43080. // Skeletons
  43081. serializationObject.skeletons = [];
  43082. for (index = 0; index < scene.skeletons.length; index++) {
  43083. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  43084. }
  43085. // Geometries
  43086. serializationObject.geometries = {};
  43087. serializationObject.geometries.boxes = [];
  43088. serializationObject.geometries.spheres = [];
  43089. serializationObject.geometries.cylinders = [];
  43090. serializationObject.geometries.toruses = [];
  43091. serializationObject.geometries.grounds = [];
  43092. serializationObject.geometries.planes = [];
  43093. serializationObject.geometries.torusKnots = [];
  43094. serializationObject.geometries.vertexData = [];
  43095. serializedGeometries = [];
  43096. var geometries = scene.getGeometries();
  43097. for (index = 0; index < geometries.length; index++) {
  43098. var geometry = geometries[index];
  43099. if (geometry.isReady()) {
  43100. serializeGeometry(geometry, serializationObject.geometries);
  43101. }
  43102. }
  43103. // Meshes
  43104. serializationObject.meshes = [];
  43105. for (index = 0; index < scene.meshes.length; index++) {
  43106. var abstractMesh = scene.meshes[index];
  43107. if (abstractMesh instanceof BABYLON.Mesh) {
  43108. var mesh = abstractMesh;
  43109. if (!mesh.doNotSerialize) {
  43110. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  43111. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  43112. }
  43113. }
  43114. }
  43115. }
  43116. // Particles Systems
  43117. serializationObject.particleSystems = [];
  43118. for (index = 0; index < scene.particleSystems.length; index++) {
  43119. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  43120. }
  43121. // Lens flares
  43122. serializationObject.lensFlareSystems = [];
  43123. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  43124. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  43125. }
  43126. // Shadows
  43127. serializationObject.shadowGenerators = [];
  43128. for (index = 0; index < scene.lights.length; index++) {
  43129. light = scene.lights[index];
  43130. var shadowGenerator = light.getShadowGenerator();
  43131. // Only support serialization for official generator so far.
  43132. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  43133. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  43134. }
  43135. }
  43136. // Action Manager
  43137. if (scene.actionManager) {
  43138. serializationObject.actions = scene.actionManager.serialize("scene");
  43139. }
  43140. // Audio
  43141. serializationObject.sounds = [];
  43142. for (index = 0; index < scene.soundTracks.length; index++) {
  43143. var soundtrack = scene.soundTracks[index];
  43144. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  43145. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  43146. }
  43147. }
  43148. return serializationObject;
  43149. };
  43150. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  43151. if (withParents === void 0) { withParents = false; }
  43152. if (withChildren === void 0) { withChildren = false; }
  43153. var serializationObject = {};
  43154. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  43155. if (withParents || withChildren) {
  43156. //deliberate for loop! not for each, appended should be processed as well.
  43157. for (var i = 0; i < toSerialize.length; ++i) {
  43158. if (withChildren) {
  43159. toSerialize[i].getDescendants().forEach(function (node) {
  43160. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  43161. toSerialize.push(node);
  43162. }
  43163. });
  43164. }
  43165. //make sure the array doesn't contain the object already
  43166. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  43167. toSerialize.push(toSerialize[i].parent);
  43168. }
  43169. }
  43170. }
  43171. toSerialize.forEach(function (mesh) {
  43172. finalizeSingleMesh(mesh, serializationObject);
  43173. });
  43174. return serializationObject;
  43175. };
  43176. return SceneSerializer;
  43177. }());
  43178. BABYLON.SceneSerializer = SceneSerializer;
  43179. })(BABYLON || (BABYLON = {}));
  43180. //# sourceMappingURL=babylon.sceneSerializer.js.map
  43181. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  43182. // Huge respect for a such great lib.
  43183. // Earcut license:
  43184. // Copyright (c) 2016, Mapbox
  43185. //
  43186. // Permission to use, copy, modify, and/or distribute this software for any purpose
  43187. // with or without fee is hereby granted, provided that the above copyright notice
  43188. // and this permission notice appear in all copies.
  43189. //
  43190. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  43191. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  43192. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  43193. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  43194. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  43195. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  43196. // THIS SOFTWARE.
  43197. var Earcut;
  43198. (function (Earcut) {
  43199. /**
  43200. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  43201. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  43202. * @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).
  43203. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  43204. */
  43205. function earcut(data, holeIndices, dim) {
  43206. dim = dim || 2;
  43207. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  43208. if (!outerNode)
  43209. return triangles;
  43210. var minX, minY, maxX, maxY, x, y, size;
  43211. if (hasHoles)
  43212. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  43213. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  43214. if (data.length > 80 * dim) {
  43215. minX = maxX = data[0];
  43216. minY = maxY = data[1];
  43217. for (var i = dim; i < outerLen; i += dim) {
  43218. x = data[i];
  43219. y = data[i + 1];
  43220. if (x < minX)
  43221. minX = x;
  43222. if (y < minY)
  43223. minY = y;
  43224. if (x > maxX)
  43225. maxX = x;
  43226. if (y > maxY)
  43227. maxY = y;
  43228. }
  43229. // minX, minY and size are later used to transform coords into integers for z-order calculation
  43230. size = Math.max(maxX - minX, maxY - minY);
  43231. }
  43232. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  43233. return triangles;
  43234. }
  43235. Earcut.earcut = earcut;
  43236. // create a circular doubly linked list from polygon points in the specified winding order
  43237. function linkedList(data, start, end, dim, clockwise) {
  43238. var i, last;
  43239. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  43240. for (i = start; i < end; i += dim)
  43241. last = insertNode(i, data[i], data[i + 1], last);
  43242. }
  43243. else {
  43244. for (i = end - dim; i >= start; i -= dim)
  43245. last = insertNode(i, data[i], data[i + 1], last);
  43246. }
  43247. if (last && equals(last, last.next)) {
  43248. removeNode(last);
  43249. last = last.next;
  43250. }
  43251. return last;
  43252. }
  43253. // eliminate colinear or duplicate points
  43254. function filterPoints(start, end) {
  43255. if (!start)
  43256. return start;
  43257. if (!end)
  43258. end = start;
  43259. var p = start, again;
  43260. do {
  43261. again = false;
  43262. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  43263. removeNode(p);
  43264. p = end = p.prev;
  43265. if (p === p.next)
  43266. return null;
  43267. again = true;
  43268. }
  43269. else {
  43270. p = p.next;
  43271. }
  43272. } while (again || p !== end);
  43273. return end;
  43274. }
  43275. // main ear slicing loop which triangulates a polygon (given as a linked list)
  43276. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  43277. if (!ear)
  43278. return;
  43279. // interlink polygon nodes in z-order
  43280. if (!pass && size)
  43281. indexCurve(ear, minX, minY, size);
  43282. var stop = ear, prev, next;
  43283. // iterate through ears, slicing them one by one
  43284. while (ear.prev !== ear.next) {
  43285. prev = ear.prev;
  43286. next = ear.next;
  43287. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  43288. // cut off the triangle
  43289. triangles.push(prev.i / dim);
  43290. triangles.push(ear.i / dim);
  43291. triangles.push(next.i / dim);
  43292. removeNode(ear);
  43293. // skipping the next vertice leads to less sliver triangles
  43294. ear = next.next;
  43295. stop = next.next;
  43296. continue;
  43297. }
  43298. ear = next;
  43299. // if we looped through the whole remaining polygon and can't find any more ears
  43300. if (ear === stop) {
  43301. // try filtering points and slicing again
  43302. if (!pass) {
  43303. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  43304. }
  43305. else if (pass === 1) {
  43306. ear = cureLocalIntersections(ear, triangles, dim);
  43307. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  43308. }
  43309. else if (pass === 2) {
  43310. splitEarcut(ear, triangles, dim, minX, minY, size);
  43311. }
  43312. break;
  43313. }
  43314. }
  43315. }
  43316. // check whether a polygon node forms a valid ear with adjacent nodes
  43317. function isEar(ear) {
  43318. var a = ear.prev, b = ear, c = ear.next;
  43319. if (area(a, b, c) >= 0)
  43320. return false; // reflex, can't be an ear
  43321. // now make sure we don't have other points inside the potential ear
  43322. var p = ear.next.next;
  43323. while (p !== ear.prev) {
  43324. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43325. area(p.prev, p, p.next) >= 0)
  43326. return false;
  43327. p = p.next;
  43328. }
  43329. return true;
  43330. }
  43331. function isEarHashed(ear, minX, minY, size) {
  43332. var a = ear.prev, b = ear, c = ear.next;
  43333. if (area(a, b, c) >= 0)
  43334. return false; // reflex, can't be an ear
  43335. // triangle bbox; min & max are calculated like this for speed
  43336. 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);
  43337. // z-order range for the current triangle bbox;
  43338. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  43339. // first look for points inside the triangle in increasing z-order
  43340. var p = ear.nextZ;
  43341. while (p && p.z <= maxZ) {
  43342. if (p !== ear.prev &&
  43343. p !== ear.next &&
  43344. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43345. area(p.prev, p, p.next) >= 0)
  43346. return false;
  43347. p = p.nextZ;
  43348. }
  43349. // then look for points in decreasing z-order
  43350. p = ear.prevZ;
  43351. while (p && p.z >= minZ) {
  43352. if (p !== ear.prev &&
  43353. p !== ear.next &&
  43354. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43355. area(p.prev, p, p.next) >= 0)
  43356. return false;
  43357. p = p.prevZ;
  43358. }
  43359. return true;
  43360. }
  43361. // go through all polygon nodes and cure small local self-intersections
  43362. function cureLocalIntersections(start, triangles, dim) {
  43363. var p = start;
  43364. do {
  43365. var a = p.prev, b = p.next.next;
  43366. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  43367. triangles.push(a.i / dim);
  43368. triangles.push(p.i / dim);
  43369. triangles.push(b.i / dim);
  43370. // remove two nodes involved
  43371. removeNode(p);
  43372. removeNode(p.next);
  43373. p = start = b;
  43374. }
  43375. p = p.next;
  43376. } while (p !== start);
  43377. return p;
  43378. }
  43379. // try splitting polygon into two and triangulate them independently
  43380. function splitEarcut(start, triangles, dim, minX, minY, size) {
  43381. // look for a valid diagonal that divides the polygon into two
  43382. var a = start;
  43383. do {
  43384. var b = a.next.next;
  43385. while (b !== a.prev) {
  43386. if (a.i !== b.i && isValidDiagonal(a, b)) {
  43387. // split the polygon in two by the diagonal
  43388. var c = splitPolygon(a, b);
  43389. // filter colinear points around the cuts
  43390. a = filterPoints(a, a.next);
  43391. c = filterPoints(c, c.next);
  43392. // run earcut on each half
  43393. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  43394. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  43395. return;
  43396. }
  43397. b = b.next;
  43398. }
  43399. a = a.next;
  43400. } while (a !== start);
  43401. }
  43402. // link every hole into the outer loop, producing a single-ring polygon without holes
  43403. function eliminateHoles(data, holeIndices, outerNode, dim) {
  43404. var queue = [], i, len, start, end, list;
  43405. for (i = 0, len = holeIndices.length; i < len; i++) {
  43406. start = holeIndices[i] * dim;
  43407. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  43408. list = linkedList(data, start, end, dim, false);
  43409. if (list === list.next)
  43410. list.steiner = true;
  43411. queue.push(getLeftmost(list));
  43412. }
  43413. queue.sort(compareX);
  43414. // process holes from left to right
  43415. for (i = 0; i < queue.length; i++) {
  43416. eliminateHole(queue[i], outerNode);
  43417. outerNode = filterPoints(outerNode, outerNode.next);
  43418. }
  43419. return outerNode;
  43420. }
  43421. function compareX(a, b) {
  43422. return a.x - b.x;
  43423. }
  43424. // find a bridge between vertices that connects hole with an outer ring and and link it
  43425. function eliminateHole(hole, outerNode) {
  43426. outerNode = findHoleBridge(hole, outerNode);
  43427. if (outerNode) {
  43428. var b = splitPolygon(outerNode, hole);
  43429. filterPoints(b, b.next);
  43430. }
  43431. }
  43432. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  43433. function findHoleBridge(hole, outerNode) {
  43434. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  43435. // find a segment intersected by a ray from the hole's leftmost point to the left;
  43436. // segment's endpoint with lesser x will be potential connection point
  43437. do {
  43438. if (hy <= p.y && hy >= p.next.y) {
  43439. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  43440. if (x <= hx && x > qx) {
  43441. qx = x;
  43442. if (x === hx) {
  43443. if (hy === p.y)
  43444. return p;
  43445. if (hy === p.next.y)
  43446. return p.next;
  43447. }
  43448. m = p.x < p.next.x ? p : p.next;
  43449. }
  43450. }
  43451. p = p.next;
  43452. } while (p !== outerNode);
  43453. if (!m)
  43454. return null;
  43455. if (hx === qx)
  43456. return m.prev; // hole touches outer segment; pick lower endpoint
  43457. // look for points inside the triangle of hole point, segment intersection and endpoint;
  43458. // if there are no points found, we have a valid connection;
  43459. // otherwise choose the point of the minimum angle with the ray as connection point
  43460. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  43461. p = m.next;
  43462. while (p !== stop) {
  43463. if (hx >= p.x &&
  43464. p.x >= mx &&
  43465. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  43466. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  43467. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  43468. m = p;
  43469. tanMin = tan;
  43470. }
  43471. }
  43472. p = p.next;
  43473. }
  43474. return m;
  43475. }
  43476. // interlink polygon nodes in z-order
  43477. function indexCurve(start, minX, minY, size) {
  43478. var p = start;
  43479. do {
  43480. if (p.z === null)
  43481. p.z = zOrder(p.x, p.y, minX, minY, size);
  43482. p.prevZ = p.prev;
  43483. p.nextZ = p.next;
  43484. p = p.next;
  43485. } while (p !== start);
  43486. p.prevZ.nextZ = null;
  43487. p.prevZ = null;
  43488. sortLinked(p);
  43489. }
  43490. // Simon Tatham's linked list merge sort algorithm
  43491. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  43492. function sortLinked(list) {
  43493. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  43494. do {
  43495. p = list;
  43496. list = null;
  43497. tail = null;
  43498. numMerges = 0;
  43499. while (p) {
  43500. numMerges++;
  43501. q = p;
  43502. pSize = 0;
  43503. for (i = 0; i < inSize; i++) {
  43504. pSize++;
  43505. q = q.nextZ;
  43506. if (!q)
  43507. break;
  43508. }
  43509. qSize = inSize;
  43510. while (pSize > 0 || (qSize > 0 && q)) {
  43511. if (pSize === 0) {
  43512. e = q;
  43513. q = q.nextZ;
  43514. qSize--;
  43515. }
  43516. else if (qSize === 0 || !q) {
  43517. e = p;
  43518. p = p.nextZ;
  43519. pSize--;
  43520. }
  43521. else if (p.z <= q.z) {
  43522. e = p;
  43523. p = p.nextZ;
  43524. pSize--;
  43525. }
  43526. else {
  43527. e = q;
  43528. q = q.nextZ;
  43529. qSize--;
  43530. }
  43531. if (tail)
  43532. tail.nextZ = e;
  43533. else
  43534. list = e;
  43535. e.prevZ = tail;
  43536. tail = e;
  43537. }
  43538. p = q;
  43539. }
  43540. tail.nextZ = null;
  43541. inSize *= 2;
  43542. } while (numMerges > 1);
  43543. return list;
  43544. }
  43545. // z-order of a point given coords and size of the data bounding box
  43546. function zOrder(x, y, minX, minY, size) {
  43547. // coords are transformed into non-negative 15-bit integer range
  43548. x = 32767 * (x - minX) / size;
  43549. y = 32767 * (y - minY) / size;
  43550. x = (x | (x << 8)) & 0x00FF00FF;
  43551. x = (x | (x << 4)) & 0x0F0F0F0F;
  43552. x = (x | (x << 2)) & 0x33333333;
  43553. x = (x | (x << 1)) & 0x55555555;
  43554. y = (y | (y << 8)) & 0x00FF00FF;
  43555. y = (y | (y << 4)) & 0x0F0F0F0F;
  43556. y = (y | (y << 2)) & 0x33333333;
  43557. y = (y | (y << 1)) & 0x55555555;
  43558. return x | (y << 1);
  43559. }
  43560. // find the leftmost node of a polygon ring
  43561. function getLeftmost(start) {
  43562. var p = start, leftmost = start;
  43563. do {
  43564. if (p.x < leftmost.x)
  43565. leftmost = p;
  43566. p = p.next;
  43567. } while (p !== start);
  43568. return leftmost;
  43569. }
  43570. // check if a point lies within a convex triangle
  43571. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  43572. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  43573. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  43574. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  43575. }
  43576. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  43577. function isValidDiagonal(a, b) {
  43578. return a.next.i !== b.i &&
  43579. a.prev.i !== b.i &&
  43580. !intersectsPolygon(a, b) &&
  43581. locallyInside(a, b) &&
  43582. locallyInside(b, a) &&
  43583. middleInside(a, b);
  43584. }
  43585. // signed area of a triangle
  43586. function area(p, q, r) {
  43587. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  43588. }
  43589. // check if two points are equal
  43590. function equals(p1, p2) {
  43591. return p1.x === p2.x && p1.y === p2.y;
  43592. }
  43593. // check if two segments intersect
  43594. function intersects(p1, q1, p2, q2) {
  43595. if ((equals(p1, q1) && equals(p2, q2)) ||
  43596. (equals(p1, q2) && equals(p2, q1)))
  43597. return true;
  43598. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  43599. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  43600. }
  43601. // check if a polygon diagonal intersects any polygon segments
  43602. function intersectsPolygon(a, b) {
  43603. var p = a;
  43604. do {
  43605. if (p.i !== a.i &&
  43606. p.next.i !== a.i &&
  43607. p.i !== b.i &&
  43608. p.next.i !== b.i &&
  43609. intersects(p, p.next, a, b))
  43610. return true;
  43611. p = p.next;
  43612. } while (p !== a);
  43613. return false;
  43614. }
  43615. // check if a polygon diagonal is locally inside the polygon
  43616. function locallyInside(a, b) {
  43617. return area(a.prev, a, a.next) < 0
  43618. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  43619. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  43620. }
  43621. // check if the middle point of a polygon diagonal is inside the polygon
  43622. function middleInside(a, b) {
  43623. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  43624. do {
  43625. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  43626. inside = !inside;
  43627. p = p.next;
  43628. } while (p !== a);
  43629. return inside;
  43630. }
  43631. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  43632. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  43633. function splitPolygon(a, b) {
  43634. 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;
  43635. a.next = b;
  43636. b.prev = a;
  43637. a2.next = an;
  43638. an.prev = a2;
  43639. b2.next = a2;
  43640. a2.prev = b2;
  43641. bp.next = b2;
  43642. b2.prev = bp;
  43643. return b2;
  43644. }
  43645. // create a node and optionally link it with previous one (in a circular doubly linked list)
  43646. function insertNode(i, x, y, last) {
  43647. var p = new Node(i, x, y);
  43648. if (!last) {
  43649. p.prev = p;
  43650. p.next = p;
  43651. }
  43652. else {
  43653. p.next = last.next;
  43654. p.prev = last;
  43655. last.next.prev = p;
  43656. last.next = p;
  43657. }
  43658. return p;
  43659. }
  43660. function removeNode(p) {
  43661. p.next.prev = p.prev;
  43662. p.prev.next = p.next;
  43663. if (p.prevZ)
  43664. p.prevZ.nextZ = p.nextZ;
  43665. if (p.nextZ)
  43666. p.nextZ.prevZ = p.prevZ;
  43667. }
  43668. function Node(i, x, y) {
  43669. // vertice index in coordinates array
  43670. this.i = i;
  43671. // vertex coordinates
  43672. this.x = x;
  43673. this.y = y;
  43674. // previous and next vertice nodes in a polygon ring
  43675. this.prev = null;
  43676. this.next = null;
  43677. // z-order curve value
  43678. this.z = null;
  43679. // previous and next nodes in z-order
  43680. this.prevZ = null;
  43681. this.nextZ = null;
  43682. // indicates whether this is a steiner point
  43683. this.steiner = false;
  43684. }
  43685. /**
  43686. * return a percentage difference between the polygon area and its triangulation area;
  43687. * used to verify correctness of triangulation
  43688. */
  43689. function deviation(data, holeIndices, dim, triangles) {
  43690. var hasHoles = holeIndices && holeIndices.length;
  43691. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  43692. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  43693. if (hasHoles) {
  43694. for (var i = 0, len = holeIndices.length; i < len; i++) {
  43695. var start = holeIndices[i] * dim;
  43696. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  43697. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  43698. }
  43699. }
  43700. var trianglesArea = 0;
  43701. for (i = 0; i < triangles.length; i += 3) {
  43702. var a = triangles[i] * dim;
  43703. var b = triangles[i + 1] * dim;
  43704. var c = triangles[i + 2] * dim;
  43705. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  43706. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  43707. }
  43708. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  43709. }
  43710. Earcut.deviation = deviation;
  43711. ;
  43712. function signedArea(data, start, end, dim) {
  43713. var sum = 0;
  43714. for (var i = start, j = end - dim; i < end; i += dim) {
  43715. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  43716. j = i;
  43717. }
  43718. return sum;
  43719. }
  43720. /**
  43721. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  43722. */
  43723. function flatten(data) {
  43724. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  43725. for (var i = 0; i < data.length; i++) {
  43726. for (var j = 0; j < data[i].length; j++) {
  43727. for (var d = 0; d < dim; d++)
  43728. result.vertices.push(data[i][j][d]);
  43729. }
  43730. if (i > 0) {
  43731. holeIndex += data[i - 1].length;
  43732. result.holes.push(holeIndex);
  43733. }
  43734. }
  43735. return result;
  43736. }
  43737. Earcut.flatten = flatten;
  43738. ;
  43739. })(Earcut || (Earcut = {}));
  43740. //# sourceMappingURL=babylon.earcut.js.map
  43741. var BABYLON;
  43742. (function (BABYLON) {
  43743. // Unique ID when we import meshes from Babylon to CSG
  43744. var currentCSGMeshId = 0;
  43745. // # class Vertex
  43746. // Represents a vertex of a polygon. Use your own vertex class instead of this
  43747. // one to provide additional features like texture coordinates and vertex
  43748. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  43749. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  43750. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  43751. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  43752. // is not used anywhere else.
  43753. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  43754. var Vertex = (function () {
  43755. function Vertex(pos, normal, uv) {
  43756. this.pos = pos;
  43757. this.normal = normal;
  43758. this.uv = uv;
  43759. }
  43760. Vertex.prototype.clone = function () {
  43761. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  43762. };
  43763. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  43764. // orientation of a polygon is flipped.
  43765. Vertex.prototype.flip = function () {
  43766. this.normal = this.normal.scale(-1);
  43767. };
  43768. // Create a new vertex between this vertex and `other` by linearly
  43769. // interpolating all properties using a parameter of `t`. Subclasses should
  43770. // override this to interpolate additional properties.
  43771. Vertex.prototype.interpolate = function (other, t) {
  43772. 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));
  43773. };
  43774. return Vertex;
  43775. }());
  43776. // # class Plane
  43777. // Represents a plane in 3D space.
  43778. var Plane = (function () {
  43779. function Plane(normal, w) {
  43780. this.normal = normal;
  43781. this.w = w;
  43782. }
  43783. Plane.FromPoints = function (a, b, c) {
  43784. var v0 = c.subtract(a);
  43785. var v1 = b.subtract(a);
  43786. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  43787. return null;
  43788. }
  43789. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  43790. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  43791. };
  43792. Plane.prototype.clone = function () {
  43793. return new Plane(this.normal.clone(), this.w);
  43794. };
  43795. Plane.prototype.flip = function () {
  43796. this.normal.scaleInPlace(-1);
  43797. this.w = -this.w;
  43798. };
  43799. // Split `polygon` by this plane if needed, then put the polygon or polygon
  43800. // fragments in the appropriate lists. Coplanar polygons go into either
  43801. // `coplanarFront` or `coplanarBack` depending on their orientation with
  43802. // respect to this plane. Polygons in front or in back of this plane go into
  43803. // either `front` or `back`.
  43804. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  43805. var COPLANAR = 0;
  43806. var FRONT = 1;
  43807. var BACK = 2;
  43808. var SPANNING = 3;
  43809. // Classify each point as well as the entire polygon into one of the above
  43810. // four classes.
  43811. var polygonType = 0;
  43812. var types = [];
  43813. var i;
  43814. var t;
  43815. for (i = 0; i < polygon.vertices.length; i++) {
  43816. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  43817. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  43818. polygonType |= type;
  43819. types.push(type);
  43820. }
  43821. // Put the polygon in the correct list, splitting it when necessary.
  43822. switch (polygonType) {
  43823. case COPLANAR:
  43824. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  43825. break;
  43826. case FRONT:
  43827. front.push(polygon);
  43828. break;
  43829. case BACK:
  43830. back.push(polygon);
  43831. break;
  43832. case SPANNING:
  43833. var f = [], b = [];
  43834. for (i = 0; i < polygon.vertices.length; i++) {
  43835. var j = (i + 1) % polygon.vertices.length;
  43836. var ti = types[i], tj = types[j];
  43837. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  43838. if (ti !== BACK)
  43839. f.push(vi);
  43840. if (ti !== FRONT)
  43841. b.push(ti !== BACK ? vi.clone() : vi);
  43842. if ((ti | tj) === SPANNING) {
  43843. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  43844. var v = vi.interpolate(vj, t);
  43845. f.push(v);
  43846. b.push(v.clone());
  43847. }
  43848. }
  43849. var poly;
  43850. if (f.length >= 3) {
  43851. poly = new Polygon(f, polygon.shared);
  43852. if (poly.plane)
  43853. front.push(poly);
  43854. }
  43855. if (b.length >= 3) {
  43856. poly = new Polygon(b, polygon.shared);
  43857. if (poly.plane)
  43858. back.push(poly);
  43859. }
  43860. break;
  43861. }
  43862. };
  43863. return Plane;
  43864. }());
  43865. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  43866. // point is on the plane.
  43867. Plane.EPSILON = 1e-5;
  43868. // # class Polygon
  43869. // Represents a convex polygon. The vertices used to initialize a polygon must
  43870. // be coplanar and form a convex loop.
  43871. //
  43872. // Each convex polygon has a `shared` property, which is shared between all
  43873. // polygons that are clones of each other or were split from the same polygon.
  43874. // This can be used to define per-polygon properties (such as surface color).
  43875. var Polygon = (function () {
  43876. function Polygon(vertices, shared) {
  43877. this.vertices = vertices;
  43878. this.shared = shared;
  43879. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  43880. }
  43881. Polygon.prototype.clone = function () {
  43882. var vertices = this.vertices.map(function (v) { return v.clone(); });
  43883. return new Polygon(vertices, this.shared);
  43884. };
  43885. Polygon.prototype.flip = function () {
  43886. this.vertices.reverse().map(function (v) { v.flip(); });
  43887. this.plane.flip();
  43888. };
  43889. return Polygon;
  43890. }());
  43891. // # class Node
  43892. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  43893. // by picking a polygon to split along. That polygon (and all other coplanar
  43894. // polygons) are added directly to that node and the other polygons are added to
  43895. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  43896. // no distinction between internal and leaf nodes.
  43897. var Node = (function () {
  43898. function Node(polygons) {
  43899. this.plane = null;
  43900. this.front = null;
  43901. this.back = null;
  43902. this.polygons = [];
  43903. if (polygons) {
  43904. this.build(polygons);
  43905. }
  43906. }
  43907. Node.prototype.clone = function () {
  43908. var node = new Node();
  43909. node.plane = this.plane && this.plane.clone();
  43910. node.front = this.front && this.front.clone();
  43911. node.back = this.back && this.back.clone();
  43912. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  43913. return node;
  43914. };
  43915. // Convert solid space to empty space and empty space to solid space.
  43916. Node.prototype.invert = function () {
  43917. for (var i = 0; i < this.polygons.length; i++) {
  43918. this.polygons[i].flip();
  43919. }
  43920. if (this.plane) {
  43921. this.plane.flip();
  43922. }
  43923. if (this.front) {
  43924. this.front.invert();
  43925. }
  43926. if (this.back) {
  43927. this.back.invert();
  43928. }
  43929. var temp = this.front;
  43930. this.front = this.back;
  43931. this.back = temp;
  43932. };
  43933. // Recursively remove all polygons in `polygons` that are inside this BSP
  43934. // tree.
  43935. Node.prototype.clipPolygons = function (polygons) {
  43936. if (!this.plane)
  43937. return polygons.slice();
  43938. var front = [], back = [];
  43939. for (var i = 0; i < polygons.length; i++) {
  43940. this.plane.splitPolygon(polygons[i], front, back, front, back);
  43941. }
  43942. if (this.front) {
  43943. front = this.front.clipPolygons(front);
  43944. }
  43945. if (this.back) {
  43946. back = this.back.clipPolygons(back);
  43947. }
  43948. else {
  43949. back = [];
  43950. }
  43951. return front.concat(back);
  43952. };
  43953. // Remove all polygons in this BSP tree that are inside the other BSP tree
  43954. // `bsp`.
  43955. Node.prototype.clipTo = function (bsp) {
  43956. this.polygons = bsp.clipPolygons(this.polygons);
  43957. if (this.front)
  43958. this.front.clipTo(bsp);
  43959. if (this.back)
  43960. this.back.clipTo(bsp);
  43961. };
  43962. // Return a list of all polygons in this BSP tree.
  43963. Node.prototype.allPolygons = function () {
  43964. var polygons = this.polygons.slice();
  43965. if (this.front)
  43966. polygons = polygons.concat(this.front.allPolygons());
  43967. if (this.back)
  43968. polygons = polygons.concat(this.back.allPolygons());
  43969. return polygons;
  43970. };
  43971. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  43972. // new polygons are filtered down to the bottom of the tree and become new
  43973. // nodes there. Each set of polygons is partitioned using the first polygon
  43974. // (no heuristic is used to pick a good split).
  43975. Node.prototype.build = function (polygons) {
  43976. if (!polygons.length)
  43977. return;
  43978. if (!this.plane)
  43979. this.plane = polygons[0].plane.clone();
  43980. var front = [], back = [];
  43981. for (var i = 0; i < polygons.length; i++) {
  43982. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  43983. }
  43984. if (front.length) {
  43985. if (!this.front)
  43986. this.front = new Node();
  43987. this.front.build(front);
  43988. }
  43989. if (back.length) {
  43990. if (!this.back)
  43991. this.back = new Node();
  43992. this.back.build(back);
  43993. }
  43994. };
  43995. return Node;
  43996. }());
  43997. var CSG = (function () {
  43998. function CSG() {
  43999. this.polygons = new Array();
  44000. }
  44001. // Convert BABYLON.Mesh to BABYLON.CSG
  44002. CSG.FromMesh = function (mesh) {
  44003. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  44004. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  44005. if (mesh instanceof BABYLON.Mesh) {
  44006. mesh.computeWorldMatrix(true);
  44007. matrix = mesh.getWorldMatrix();
  44008. meshPosition = mesh.position.clone();
  44009. meshRotation = mesh.rotation.clone();
  44010. if (mesh.rotationQuaternion) {
  44011. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  44012. }
  44013. meshScaling = mesh.scaling.clone();
  44014. }
  44015. else {
  44016. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  44017. }
  44018. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44019. var subMeshes = mesh.subMeshes;
  44020. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  44021. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  44022. vertices = [];
  44023. for (var j = 0; j < 3; j++) {
  44024. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  44025. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  44026. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  44027. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  44028. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  44029. vertex = new Vertex(position, normal, uv);
  44030. vertices.push(vertex);
  44031. }
  44032. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  44033. // To handle the case of degenerated triangle
  44034. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  44035. if (polygon.plane)
  44036. polygons.push(polygon);
  44037. }
  44038. }
  44039. var csg = CSG.FromPolygons(polygons);
  44040. csg.matrix = matrix;
  44041. csg.position = meshPosition;
  44042. csg.rotation = meshRotation;
  44043. csg.scaling = meshScaling;
  44044. csg.rotationQuaternion = meshRotationQuaternion;
  44045. currentCSGMeshId++;
  44046. return csg;
  44047. };
  44048. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  44049. CSG.FromPolygons = function (polygons) {
  44050. var csg = new CSG();
  44051. csg.polygons = polygons;
  44052. return csg;
  44053. };
  44054. CSG.prototype.clone = function () {
  44055. var csg = new CSG();
  44056. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  44057. csg.copyTransformAttributes(this);
  44058. return csg;
  44059. };
  44060. CSG.prototype.toPolygons = function () {
  44061. return this.polygons;
  44062. };
  44063. CSG.prototype.union = function (csg) {
  44064. var a = new Node(this.clone().polygons);
  44065. var b = new Node(csg.clone().polygons);
  44066. a.clipTo(b);
  44067. b.clipTo(a);
  44068. b.invert();
  44069. b.clipTo(a);
  44070. b.invert();
  44071. a.build(b.allPolygons());
  44072. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  44073. };
  44074. CSG.prototype.unionInPlace = function (csg) {
  44075. var a = new Node(this.polygons);
  44076. var b = new Node(csg.polygons);
  44077. a.clipTo(b);
  44078. b.clipTo(a);
  44079. b.invert();
  44080. b.clipTo(a);
  44081. b.invert();
  44082. a.build(b.allPolygons());
  44083. this.polygons = a.allPolygons();
  44084. };
  44085. CSG.prototype.subtract = function (csg) {
  44086. var a = new Node(this.clone().polygons);
  44087. var b = new Node(csg.clone().polygons);
  44088. a.invert();
  44089. a.clipTo(b);
  44090. b.clipTo(a);
  44091. b.invert();
  44092. b.clipTo(a);
  44093. b.invert();
  44094. a.build(b.allPolygons());
  44095. a.invert();
  44096. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  44097. };
  44098. CSG.prototype.subtractInPlace = function (csg) {
  44099. var a = new Node(this.polygons);
  44100. var b = new Node(csg.polygons);
  44101. a.invert();
  44102. a.clipTo(b);
  44103. b.clipTo(a);
  44104. b.invert();
  44105. b.clipTo(a);
  44106. b.invert();
  44107. a.build(b.allPolygons());
  44108. a.invert();
  44109. this.polygons = a.allPolygons();
  44110. };
  44111. CSG.prototype.intersect = function (csg) {
  44112. var a = new Node(this.clone().polygons);
  44113. var b = new Node(csg.clone().polygons);
  44114. a.invert();
  44115. b.clipTo(a);
  44116. b.invert();
  44117. a.clipTo(b);
  44118. b.clipTo(a);
  44119. a.build(b.allPolygons());
  44120. a.invert();
  44121. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  44122. };
  44123. CSG.prototype.intersectInPlace = function (csg) {
  44124. var a = new Node(this.polygons);
  44125. var b = new Node(csg.polygons);
  44126. a.invert();
  44127. b.clipTo(a);
  44128. b.invert();
  44129. a.clipTo(b);
  44130. b.clipTo(a);
  44131. a.build(b.allPolygons());
  44132. a.invert();
  44133. this.polygons = a.allPolygons();
  44134. };
  44135. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  44136. // not modified.
  44137. CSG.prototype.inverse = function () {
  44138. var csg = this.clone();
  44139. csg.inverseInPlace();
  44140. return csg;
  44141. };
  44142. CSG.prototype.inverseInPlace = function () {
  44143. this.polygons.map(function (p) { p.flip(); });
  44144. };
  44145. // This is used to keep meshes transformations so they can be restored
  44146. // when we build back a Babylon Mesh
  44147. // NB : All CSG operations are performed in world coordinates
  44148. CSG.prototype.copyTransformAttributes = function (csg) {
  44149. this.matrix = csg.matrix;
  44150. this.position = csg.position;
  44151. this.rotation = csg.rotation;
  44152. this.scaling = csg.scaling;
  44153. this.rotationQuaternion = csg.rotationQuaternion;
  44154. return this;
  44155. };
  44156. // Build Raw mesh from CSG
  44157. // Coordinates here are in world space
  44158. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  44159. var matrix = this.matrix.clone();
  44160. matrix.invert();
  44161. 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;
  44162. if (keepSubMeshes) {
  44163. // Sort Polygons, since subMeshes are indices range
  44164. polygons.sort(function (a, b) {
  44165. if (a.shared.meshId === b.shared.meshId) {
  44166. return a.shared.subMeshId - b.shared.subMeshId;
  44167. }
  44168. else {
  44169. return a.shared.meshId - b.shared.meshId;
  44170. }
  44171. });
  44172. }
  44173. for (var i = 0, il = polygons.length; i < il; i++) {
  44174. polygon = polygons[i];
  44175. // Building SubMeshes
  44176. if (!subMesh_dict[polygon.shared.meshId]) {
  44177. subMesh_dict[polygon.shared.meshId] = {};
  44178. }
  44179. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  44180. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  44181. indexStart: +Infinity,
  44182. indexEnd: -Infinity,
  44183. materialIndex: polygon.shared.materialIndex
  44184. };
  44185. }
  44186. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  44187. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  44188. polygonIndices[0] = 0;
  44189. polygonIndices[1] = j - 1;
  44190. polygonIndices[2] = j;
  44191. for (var k = 0; k < 3; k++) {
  44192. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  44193. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  44194. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  44195. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  44196. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  44197. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  44198. // Check if 2 points can be merged
  44199. if (!(typeof vertex_idx !== 'undefined' &&
  44200. normals[vertex_idx * 3] === localNormal.x &&
  44201. normals[vertex_idx * 3 + 1] === localNormal.y &&
  44202. normals[vertex_idx * 3 + 2] === localNormal.z &&
  44203. uvs[vertex_idx * 2] === uv.x &&
  44204. uvs[vertex_idx * 2 + 1] === uv.y)) {
  44205. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  44206. uvs.push(uv.x, uv.y);
  44207. normals.push(normal.x, normal.y, normal.z);
  44208. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  44209. }
  44210. indices.push(vertex_idx);
  44211. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  44212. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  44213. currentIndex++;
  44214. }
  44215. }
  44216. }
  44217. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  44218. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  44219. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  44220. mesh.setIndices(indices);
  44221. if (keepSubMeshes) {
  44222. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  44223. var materialIndexOffset = 0, materialMaxIndex;
  44224. mesh.subMeshes = new Array();
  44225. for (var m in subMesh_dict) {
  44226. materialMaxIndex = -1;
  44227. for (var sm in subMesh_dict[m]) {
  44228. subMesh_obj = subMesh_dict[m][sm];
  44229. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  44230. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  44231. }
  44232. materialIndexOffset += ++materialMaxIndex;
  44233. }
  44234. }
  44235. return mesh;
  44236. };
  44237. // Build Mesh from CSG taking material and transforms into account
  44238. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  44239. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  44240. mesh.material = material;
  44241. mesh.position.copyFrom(this.position);
  44242. mesh.rotation.copyFrom(this.rotation);
  44243. if (this.rotationQuaternion) {
  44244. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  44245. }
  44246. mesh.scaling.copyFrom(this.scaling);
  44247. mesh.computeWorldMatrix(true);
  44248. return mesh;
  44249. };
  44250. return CSG;
  44251. }());
  44252. BABYLON.CSG = CSG;
  44253. })(BABYLON || (BABYLON = {}));
  44254. //# sourceMappingURL=babylon.csg.js.map
  44255. var BABYLON;
  44256. (function (BABYLON) {
  44257. var VRDistortionCorrectionPostProcess = (function (_super) {
  44258. __extends(VRDistortionCorrectionPostProcess, _super);
  44259. //ANY
  44260. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  44261. var _this = _super.call(this, name, "vrDistortionCorrection", [
  44262. 'LensCenter',
  44263. 'Scale',
  44264. 'ScaleIn',
  44265. 'HmdWarpParam'
  44266. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  44267. _this._isRightEye = isRightEye;
  44268. _this._distortionFactors = vrMetrics.distortionK;
  44269. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  44270. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  44271. _this.onSizeChangedObservable.add(function () {
  44272. _this.aspectRatio = _this.width * .5 / _this.height;
  44273. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  44274. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  44275. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  44276. });
  44277. _this.onApplyObservable.add(function (effect) {
  44278. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  44279. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  44280. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  44281. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  44282. });
  44283. return _this;
  44284. }
  44285. return VRDistortionCorrectionPostProcess;
  44286. }(BABYLON.PostProcess));
  44287. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  44288. })(BABYLON || (BABYLON = {}));
  44289. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  44290. // Mainly based on these 2 articles :
  44291. // 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
  44292. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  44293. var BABYLON;
  44294. (function (BABYLON) {
  44295. var JoystickAxis;
  44296. (function (JoystickAxis) {
  44297. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  44298. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  44299. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  44300. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  44301. var VirtualJoystick = (function () {
  44302. function VirtualJoystick(leftJoystick) {
  44303. var _this = this;
  44304. if (leftJoystick) {
  44305. this._leftJoystick = true;
  44306. }
  44307. else {
  44308. this._leftJoystick = false;
  44309. }
  44310. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  44311. VirtualJoystick._globalJoystickIndex++;
  44312. // By default left & right arrow keys are moving the X
  44313. // and up & down keys are moving the Y
  44314. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  44315. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  44316. this.reverseLeftRight = false;
  44317. this.reverseUpDown = false;
  44318. // collections of pointers
  44319. this._touches = new BABYLON.StringDictionary();
  44320. this.deltaPosition = BABYLON.Vector3.Zero();
  44321. this._joystickSensibility = 25;
  44322. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  44323. this._rotationSpeed = 25;
  44324. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  44325. this._rotateOnAxisRelativeToMesh = false;
  44326. this._onResize = function (evt) {
  44327. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  44328. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  44329. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  44330. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  44331. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  44332. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  44333. };
  44334. // injecting a canvas element on top of the canvas 3D game
  44335. if (!VirtualJoystick.vjCanvas) {
  44336. window.addEventListener("resize", this._onResize, false);
  44337. VirtualJoystick.vjCanvas = document.createElement("canvas");
  44338. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  44339. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  44340. VirtualJoystick.vjCanvas.width = window.innerWidth;
  44341. VirtualJoystick.vjCanvas.height = window.innerHeight;
  44342. VirtualJoystick.vjCanvas.style.width = "100%";
  44343. VirtualJoystick.vjCanvas.style.height = "100%";
  44344. VirtualJoystick.vjCanvas.style.position = "absolute";
  44345. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  44346. VirtualJoystick.vjCanvas.style.top = "0px";
  44347. VirtualJoystick.vjCanvas.style.left = "0px";
  44348. VirtualJoystick.vjCanvas.style.zIndex = "5";
  44349. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  44350. // Support for jQuery PEP polyfill
  44351. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  44352. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  44353. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  44354. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44355. document.body.appendChild(VirtualJoystick.vjCanvas);
  44356. }
  44357. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  44358. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  44359. this.pressed = false;
  44360. // default joystick color
  44361. this._joystickColor = "cyan";
  44362. this._joystickPointerID = -1;
  44363. // current joystick position
  44364. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  44365. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  44366. // origin joystick position
  44367. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  44368. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  44369. this._onPointerDownHandlerRef = function (evt) {
  44370. _this._onPointerDown(evt);
  44371. };
  44372. this._onPointerMoveHandlerRef = function (evt) {
  44373. _this._onPointerMove(evt);
  44374. };
  44375. this._onPointerOutHandlerRef = function (evt) {
  44376. _this._onPointerUp(evt);
  44377. };
  44378. this._onPointerUpHandlerRef = function (evt) {
  44379. _this._onPointerUp(evt);
  44380. };
  44381. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  44382. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  44383. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  44384. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  44385. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  44386. evt.preventDefault(); // Disables system menu
  44387. }, false);
  44388. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44389. }
  44390. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  44391. this._joystickSensibility = newJoystickSensibility;
  44392. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  44393. };
  44394. VirtualJoystick.prototype._onPointerDown = function (e) {
  44395. var positionOnScreenCondition;
  44396. e.preventDefault();
  44397. if (this._leftJoystick === true) {
  44398. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  44399. }
  44400. else {
  44401. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  44402. }
  44403. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  44404. // First contact will be dedicated to the virtual joystick
  44405. this._joystickPointerID = e.pointerId;
  44406. this._joystickPointerStartPos.x = e.clientX;
  44407. this._joystickPointerStartPos.y = e.clientY;
  44408. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  44409. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  44410. this._deltaJoystickVector.x = 0;
  44411. this._deltaJoystickVector.y = 0;
  44412. this.pressed = true;
  44413. this._touches.add(e.pointerId.toString(), e);
  44414. }
  44415. else {
  44416. // You can only trigger the action buttons with a joystick declared
  44417. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  44418. this._action();
  44419. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  44420. }
  44421. }
  44422. };
  44423. VirtualJoystick.prototype._onPointerMove = function (e) {
  44424. // If the current pointer is the one associated to the joystick (first touch contact)
  44425. if (this._joystickPointerID == e.pointerId) {
  44426. this._joystickPointerPos.x = e.clientX;
  44427. this._joystickPointerPos.y = e.clientY;
  44428. this._deltaJoystickVector = this._joystickPointerPos.clone();
  44429. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  44430. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  44431. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  44432. switch (this._axisTargetedByLeftAndRight) {
  44433. case JoystickAxis.X:
  44434. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  44435. break;
  44436. case JoystickAxis.Y:
  44437. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  44438. break;
  44439. case JoystickAxis.Z:
  44440. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  44441. break;
  44442. }
  44443. var directionUpDown = this.reverseUpDown ? 1 : -1;
  44444. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  44445. switch (this._axisTargetedByUpAndDown) {
  44446. case JoystickAxis.X:
  44447. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  44448. break;
  44449. case JoystickAxis.Y:
  44450. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  44451. break;
  44452. case JoystickAxis.Z:
  44453. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  44454. break;
  44455. }
  44456. }
  44457. else {
  44458. var data = this._touches.get(e.pointerId.toString());
  44459. if (data) {
  44460. data.x = e.clientX;
  44461. data.y = e.clientY;
  44462. }
  44463. }
  44464. };
  44465. VirtualJoystick.prototype._onPointerUp = function (e) {
  44466. if (this._joystickPointerID == e.pointerId) {
  44467. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  44468. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  44469. this._joystickPointerID = -1;
  44470. this.pressed = false;
  44471. }
  44472. else {
  44473. var touch = this._touches.get(e.pointerId.toString());
  44474. if (touch) {
  44475. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  44476. }
  44477. }
  44478. this._deltaJoystickVector.x = 0;
  44479. this._deltaJoystickVector.y = 0;
  44480. this._touches.remove(e.pointerId.toString());
  44481. };
  44482. /**
  44483. * Change the color of the virtual joystick
  44484. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  44485. */
  44486. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  44487. this._joystickColor = newColor;
  44488. };
  44489. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  44490. this._action = action;
  44491. };
  44492. // Define which axis you'd like to control for left & right
  44493. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  44494. switch (axis) {
  44495. case JoystickAxis.X:
  44496. case JoystickAxis.Y:
  44497. case JoystickAxis.Z:
  44498. this._axisTargetedByLeftAndRight = axis;
  44499. break;
  44500. default:
  44501. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  44502. break;
  44503. }
  44504. };
  44505. // Define which axis you'd like to control for up & down
  44506. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  44507. switch (axis) {
  44508. case JoystickAxis.X:
  44509. case JoystickAxis.Y:
  44510. case JoystickAxis.Z:
  44511. this._axisTargetedByUpAndDown = axis;
  44512. break;
  44513. default:
  44514. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  44515. break;
  44516. }
  44517. };
  44518. VirtualJoystick.prototype._clearCanvas = function () {
  44519. if (this._leftJoystick) {
  44520. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  44521. }
  44522. else {
  44523. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  44524. }
  44525. };
  44526. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  44527. var _this = this;
  44528. if (this.pressed) {
  44529. this._touches.forEach(function (touch) {
  44530. if (touch.pointerId === _this._joystickPointerID) {
  44531. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  44532. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  44533. VirtualJoystick.vjCanvasContext.beginPath();
  44534. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44535. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44536. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  44537. VirtualJoystick.vjCanvasContext.stroke();
  44538. VirtualJoystick.vjCanvasContext.closePath();
  44539. VirtualJoystick.vjCanvasContext.beginPath();
  44540. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44541. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44542. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  44543. VirtualJoystick.vjCanvasContext.stroke();
  44544. VirtualJoystick.vjCanvasContext.closePath();
  44545. VirtualJoystick.vjCanvasContext.beginPath();
  44546. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44547. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  44548. VirtualJoystick.vjCanvasContext.stroke();
  44549. VirtualJoystick.vjCanvasContext.closePath();
  44550. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  44551. }
  44552. else {
  44553. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  44554. VirtualJoystick.vjCanvasContext.beginPath();
  44555. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  44556. VirtualJoystick.vjCanvasContext.beginPath();
  44557. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  44558. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44559. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  44560. VirtualJoystick.vjCanvasContext.stroke();
  44561. VirtualJoystick.vjCanvasContext.closePath();
  44562. touch.prevX = touch.x;
  44563. touch.prevY = touch.y;
  44564. }
  44565. ;
  44566. });
  44567. }
  44568. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44569. };
  44570. VirtualJoystick.prototype.releaseCanvas = function () {
  44571. if (VirtualJoystick.vjCanvas) {
  44572. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  44573. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  44574. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  44575. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  44576. window.removeEventListener("resize", this._onResize);
  44577. document.body.removeChild(VirtualJoystick.vjCanvas);
  44578. VirtualJoystick.vjCanvas = null;
  44579. }
  44580. };
  44581. return VirtualJoystick;
  44582. }());
  44583. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  44584. VirtualJoystick._globalJoystickIndex = 0;
  44585. BABYLON.VirtualJoystick = VirtualJoystick;
  44586. })(BABYLON || (BABYLON = {}));
  44587. //# sourceMappingURL=babylon.virtualJoystick.js.map
  44588. var BABYLON;
  44589. (function (BABYLON) {
  44590. // We're mainly based on the logic defined into the FreeCamera code
  44591. var VirtualJoysticksCamera = (function (_super) {
  44592. __extends(VirtualJoysticksCamera, _super);
  44593. function VirtualJoysticksCamera(name, position, scene) {
  44594. var _this = _super.call(this, name, position, scene) || this;
  44595. _this.inputs.addVirtualJoystick();
  44596. return _this;
  44597. }
  44598. VirtualJoysticksCamera.prototype.getClassName = function () {
  44599. return "VirtualJoysticksCamera";
  44600. };
  44601. return VirtualJoysticksCamera;
  44602. }(BABYLON.FreeCamera));
  44603. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  44604. })(BABYLON || (BABYLON = {}));
  44605. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  44606. var BABYLON;
  44607. (function (BABYLON) {
  44608. var FreeCameraVirtualJoystickInput = (function () {
  44609. function FreeCameraVirtualJoystickInput() {
  44610. }
  44611. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  44612. return this._leftjoystick;
  44613. };
  44614. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  44615. return this._rightjoystick;
  44616. };
  44617. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  44618. if (this._leftjoystick) {
  44619. var camera = this.camera;
  44620. var speed = camera._computeLocalCameraSpeed() * 50;
  44621. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  44622. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  44623. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  44624. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  44625. if (!this._leftjoystick.pressed) {
  44626. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  44627. }
  44628. if (!this._rightjoystick.pressed) {
  44629. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  44630. }
  44631. }
  44632. };
  44633. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  44634. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  44635. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  44636. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  44637. this._leftjoystick.setJoystickSensibility(0.15);
  44638. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  44639. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  44640. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  44641. this._rightjoystick.reverseUpDown = true;
  44642. this._rightjoystick.setJoystickSensibility(0.05);
  44643. this._rightjoystick.setJoystickColor("yellow");
  44644. };
  44645. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  44646. this._leftjoystick.releaseCanvas();
  44647. this._rightjoystick.releaseCanvas();
  44648. };
  44649. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  44650. return "FreeCameraVirtualJoystickInput";
  44651. };
  44652. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  44653. return "virtualJoystick";
  44654. };
  44655. return FreeCameraVirtualJoystickInput;
  44656. }());
  44657. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  44658. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  44659. })(BABYLON || (BABYLON = {}));
  44660. //# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
  44661. var BABYLON;
  44662. (function (BABYLON) {
  44663. var AnaglyphPostProcess = (function (_super) {
  44664. __extends(AnaglyphPostProcess, _super);
  44665. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  44666. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  44667. _this._passedProcess = rigCameras[0]._rigPostProcess;
  44668. _this.onApplyObservable.add(function (effect) {
  44669. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  44670. });
  44671. return _this;
  44672. }
  44673. return AnaglyphPostProcess;
  44674. }(BABYLON.PostProcess));
  44675. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  44676. })(BABYLON || (BABYLON = {}));
  44677. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  44678. var BABYLON;
  44679. (function (BABYLON) {
  44680. var OutlineRenderer = (function () {
  44681. function OutlineRenderer(scene) {
  44682. this._scene = scene;
  44683. }
  44684. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  44685. var _this = this;
  44686. if (useOverlay === void 0) { useOverlay = false; }
  44687. var scene = this._scene;
  44688. var engine = this._scene.getEngine();
  44689. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  44690. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  44691. return;
  44692. }
  44693. var mesh = subMesh.getRenderingMesh();
  44694. var material = subMesh.getMaterial();
  44695. engine.enableEffect(this._effect);
  44696. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  44697. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  44698. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  44699. // Bones
  44700. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44701. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  44702. }
  44703. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  44704. // Alpha test
  44705. if (material && material.needAlphaTesting()) {
  44706. var alphaTexture = material.getAlphaTestTexture();
  44707. this._effect.setTexture("diffuseSampler", alphaTexture);
  44708. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  44709. }
  44710. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  44711. };
  44712. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  44713. var defines = [];
  44714. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  44715. var mesh = subMesh.getMesh();
  44716. var material = subMesh.getMaterial();
  44717. // Alpha test
  44718. if (material && material.needAlphaTesting()) {
  44719. defines.push("#define ALPHATEST");
  44720. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44721. attribs.push(BABYLON.VertexBuffer.UVKind);
  44722. defines.push("#define UV1");
  44723. }
  44724. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  44725. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44726. defines.push("#define UV2");
  44727. }
  44728. }
  44729. // Bones
  44730. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44731. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  44732. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  44733. if (mesh.numBoneInfluencers > 4) {
  44734. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  44735. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  44736. }
  44737. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  44738. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  44739. }
  44740. else {
  44741. defines.push("#define NUM_BONE_INFLUENCERS 0");
  44742. }
  44743. // Instances
  44744. if (useInstances) {
  44745. defines.push("#define INSTANCES");
  44746. attribs.push("world0");
  44747. attribs.push("world1");
  44748. attribs.push("world2");
  44749. attribs.push("world3");
  44750. }
  44751. // Get correct effect
  44752. var join = defines.join("\n");
  44753. if (this._cachedDefines !== join) {
  44754. this._cachedDefines = join;
  44755. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  44756. }
  44757. return this._effect.isReady();
  44758. };
  44759. return OutlineRenderer;
  44760. }());
  44761. BABYLON.OutlineRenderer = OutlineRenderer;
  44762. })(BABYLON || (BABYLON = {}));
  44763. //# sourceMappingURL=babylon.outlineRenderer.js.map
  44764. var BABYLON;
  44765. (function (BABYLON) {
  44766. var MeshAssetTask = (function () {
  44767. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  44768. this.name = name;
  44769. this.meshesNames = meshesNames;
  44770. this.rootUrl = rootUrl;
  44771. this.sceneFilename = sceneFilename;
  44772. this.isCompleted = false;
  44773. }
  44774. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44775. var _this = this;
  44776. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  44777. _this.loadedMeshes = meshes;
  44778. _this.loadedParticleSystems = particleSystems;
  44779. _this.loadedSkeletons = skeletons;
  44780. _this.isCompleted = true;
  44781. if (_this.onSuccess) {
  44782. _this.onSuccess(_this);
  44783. }
  44784. onSuccess();
  44785. }, null, function () {
  44786. if (_this.onError) {
  44787. _this.onError(_this);
  44788. }
  44789. onError();
  44790. });
  44791. };
  44792. return MeshAssetTask;
  44793. }());
  44794. BABYLON.MeshAssetTask = MeshAssetTask;
  44795. var TextFileAssetTask = (function () {
  44796. function TextFileAssetTask(name, url) {
  44797. this.name = name;
  44798. this.url = url;
  44799. this.isCompleted = false;
  44800. }
  44801. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44802. var _this = this;
  44803. BABYLON.Tools.LoadFile(this.url, function (data) {
  44804. _this.text = data;
  44805. _this.isCompleted = true;
  44806. if (_this.onSuccess) {
  44807. _this.onSuccess(_this);
  44808. }
  44809. onSuccess();
  44810. }, null, scene.database, false, function () {
  44811. if (_this.onError) {
  44812. _this.onError(_this);
  44813. }
  44814. onError();
  44815. });
  44816. };
  44817. return TextFileAssetTask;
  44818. }());
  44819. BABYLON.TextFileAssetTask = TextFileAssetTask;
  44820. var BinaryFileAssetTask = (function () {
  44821. function BinaryFileAssetTask(name, url) {
  44822. this.name = name;
  44823. this.url = url;
  44824. this.isCompleted = false;
  44825. }
  44826. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44827. var _this = this;
  44828. BABYLON.Tools.LoadFile(this.url, function (data) {
  44829. _this.data = data;
  44830. _this.isCompleted = true;
  44831. if (_this.onSuccess) {
  44832. _this.onSuccess(_this);
  44833. }
  44834. onSuccess();
  44835. }, null, scene.database, true, function () {
  44836. if (_this.onError) {
  44837. _this.onError(_this);
  44838. }
  44839. onError();
  44840. });
  44841. };
  44842. return BinaryFileAssetTask;
  44843. }());
  44844. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  44845. var ImageAssetTask = (function () {
  44846. function ImageAssetTask(name, url) {
  44847. this.name = name;
  44848. this.url = url;
  44849. this.isCompleted = false;
  44850. }
  44851. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44852. var _this = this;
  44853. var img = new Image();
  44854. BABYLON.Tools.SetCorsBehavior(this.url, img);
  44855. img.onload = function () {
  44856. _this.image = img;
  44857. _this.isCompleted = true;
  44858. if (_this.onSuccess) {
  44859. _this.onSuccess(_this);
  44860. }
  44861. onSuccess();
  44862. };
  44863. img.onerror = function () {
  44864. if (_this.onError) {
  44865. _this.onError(_this);
  44866. }
  44867. onError();
  44868. };
  44869. img.src = this.url;
  44870. };
  44871. return ImageAssetTask;
  44872. }());
  44873. BABYLON.ImageAssetTask = ImageAssetTask;
  44874. var TextureAssetTask = (function () {
  44875. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  44876. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44877. this.name = name;
  44878. this.url = url;
  44879. this.noMipmap = noMipmap;
  44880. this.invertY = invertY;
  44881. this.samplingMode = samplingMode;
  44882. this.isCompleted = false;
  44883. }
  44884. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44885. var _this = this;
  44886. var onload = function () {
  44887. _this.isCompleted = true;
  44888. if (_this.onSuccess) {
  44889. _this.onSuccess(_this);
  44890. }
  44891. onSuccess();
  44892. };
  44893. var onerror = function () {
  44894. if (_this.onError) {
  44895. _this.onError(_this);
  44896. }
  44897. onError();
  44898. };
  44899. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  44900. };
  44901. return TextureAssetTask;
  44902. }());
  44903. BABYLON.TextureAssetTask = TextureAssetTask;
  44904. var CubeTextureAssetTask = (function () {
  44905. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  44906. this.name = name;
  44907. this.url = url;
  44908. this.extensions = extensions;
  44909. this.noMipmap = noMipmap;
  44910. this.files = files;
  44911. this.isCompleted = false;
  44912. }
  44913. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44914. var _this = this;
  44915. var onload = function () {
  44916. _this.isCompleted = true;
  44917. if (_this.onSuccess) {
  44918. _this.onSuccess(_this);
  44919. }
  44920. onSuccess();
  44921. };
  44922. var onerror = function () {
  44923. if (_this.onError) {
  44924. _this.onError(_this);
  44925. }
  44926. onError();
  44927. };
  44928. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  44929. };
  44930. return CubeTextureAssetTask;
  44931. }());
  44932. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  44933. var AssetsManager = (function () {
  44934. function AssetsManager(scene) {
  44935. this.tasks = new Array();
  44936. this.waitingTasksCount = 0;
  44937. this.useDefaultLoadingScreen = true;
  44938. this._scene = scene;
  44939. }
  44940. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  44941. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  44942. this.tasks.push(task);
  44943. return task;
  44944. };
  44945. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  44946. var task = new TextFileAssetTask(taskName, url);
  44947. this.tasks.push(task);
  44948. return task;
  44949. };
  44950. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  44951. var task = new BinaryFileAssetTask(taskName, url);
  44952. this.tasks.push(task);
  44953. return task;
  44954. };
  44955. AssetsManager.prototype.addImageTask = function (taskName, url) {
  44956. var task = new ImageAssetTask(taskName, url);
  44957. this.tasks.push(task);
  44958. return task;
  44959. };
  44960. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  44961. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44962. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  44963. this.tasks.push(task);
  44964. return task;
  44965. };
  44966. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  44967. this.waitingTasksCount--;
  44968. if (this.waitingTasksCount === 0) {
  44969. if (this.onFinish) {
  44970. this.onFinish(this.tasks);
  44971. }
  44972. this._scene.getEngine().hideLoadingUI();
  44973. }
  44974. };
  44975. AssetsManager.prototype._runTask = function (task) {
  44976. var _this = this;
  44977. task.run(this._scene, function () {
  44978. if (_this.onTaskSuccess) {
  44979. _this.onTaskSuccess(task);
  44980. }
  44981. _this._decreaseWaitingTasksCount();
  44982. }, function () {
  44983. if (_this.onTaskError) {
  44984. _this.onTaskError(task);
  44985. }
  44986. _this._decreaseWaitingTasksCount();
  44987. });
  44988. };
  44989. AssetsManager.prototype.reset = function () {
  44990. this.tasks = new Array();
  44991. return this;
  44992. };
  44993. AssetsManager.prototype.load = function () {
  44994. this.waitingTasksCount = this.tasks.length;
  44995. if (this.waitingTasksCount === 0) {
  44996. if (this.onFinish) {
  44997. this.onFinish(this.tasks);
  44998. }
  44999. return this;
  45000. }
  45001. if (this.useDefaultLoadingScreen) {
  45002. this._scene.getEngine().displayLoadingUI();
  45003. }
  45004. for (var index = 0; index < this.tasks.length; index++) {
  45005. var task = this.tasks[index];
  45006. this._runTask(task);
  45007. }
  45008. return this;
  45009. };
  45010. return AssetsManager;
  45011. }());
  45012. BABYLON.AssetsManager = AssetsManager;
  45013. })(BABYLON || (BABYLON = {}));
  45014. //# sourceMappingURL=babylon.assetsManager.js.map
  45015. var BABYLON;
  45016. (function (BABYLON) {
  45017. var VRCameraMetrics = (function () {
  45018. function VRCameraMetrics() {
  45019. this.compensateDistortion = true;
  45020. }
  45021. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  45022. get: function () {
  45023. return this.hResolution / (2 * this.vResolution);
  45024. },
  45025. enumerable: true,
  45026. configurable: true
  45027. });
  45028. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  45029. get: function () {
  45030. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  45031. },
  45032. enumerable: true,
  45033. configurable: true
  45034. });
  45035. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  45036. get: function () {
  45037. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  45038. var h = (4 * meters) / this.hScreenSize;
  45039. return BABYLON.Matrix.Translation(h, 0, 0);
  45040. },
  45041. enumerable: true,
  45042. configurable: true
  45043. });
  45044. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  45045. get: function () {
  45046. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  45047. var h = (4 * meters) / this.hScreenSize;
  45048. return BABYLON.Matrix.Translation(-h, 0, 0);
  45049. },
  45050. enumerable: true,
  45051. configurable: true
  45052. });
  45053. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  45054. get: function () {
  45055. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  45056. },
  45057. enumerable: true,
  45058. configurable: true
  45059. });
  45060. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  45061. get: function () {
  45062. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  45063. },
  45064. enumerable: true,
  45065. configurable: true
  45066. });
  45067. VRCameraMetrics.GetDefault = function () {
  45068. var result = new VRCameraMetrics();
  45069. result.hResolution = 1280;
  45070. result.vResolution = 800;
  45071. result.hScreenSize = 0.149759993;
  45072. result.vScreenSize = 0.0935999975;
  45073. result.vScreenCenter = 0.0467999987,
  45074. result.eyeToScreenDistance = 0.0410000011;
  45075. result.lensSeparationDistance = 0.0635000020;
  45076. result.interpupillaryDistance = 0.0640000030;
  45077. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  45078. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  45079. result.postProcessScaleFactor = 1.714605507808412;
  45080. result.lensCenterOffset = 0.151976421;
  45081. return result;
  45082. };
  45083. return VRCameraMetrics;
  45084. }());
  45085. BABYLON.VRCameraMetrics = VRCameraMetrics;
  45086. })(BABYLON || (BABYLON = {}));
  45087. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  45088. var BABYLON;
  45089. (function (BABYLON) {
  45090. var WebVRFreeCamera = (function (_super) {
  45091. __extends(WebVRFreeCamera, _super);
  45092. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  45093. if (compensateDistortion === void 0) { compensateDistortion = false; }
  45094. if (webVROptions === void 0) { webVROptions = {}; }
  45095. var _this = _super.call(this, name, position, scene) || this;
  45096. _this.webVROptions = webVROptions;
  45097. _this._vrDevice = null;
  45098. _this._cacheState = null;
  45099. _this._vrEnabled = false;
  45100. _this._attached = false;
  45101. //using the position provided as the current position offset
  45102. _this._positionOffset = position;
  45103. //enable VR
  45104. _this.getEngine().initWebVR();
  45105. if (!_this.getEngine().vrDisplaysPromise) {
  45106. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  45107. }
  45108. else {
  45109. //TODO get the metrics updated using the device's eye parameters!
  45110. //TODO also check that the device has the right capabilities!
  45111. _this._frameData = new VRFrameData();
  45112. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  45113. if (devices.length > 0) {
  45114. _this._vrEnabled = true;
  45115. if (_this.webVROptions.displayName) {
  45116. var found = devices.some(function (device) {
  45117. if (device.displayName === _this.webVROptions.displayName) {
  45118. _this._vrDevice = device;
  45119. return true;
  45120. }
  45121. else {
  45122. return false;
  45123. }
  45124. });
  45125. if (!found) {
  45126. _this._vrDevice = devices[0];
  45127. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  45128. }
  45129. }
  45130. else {
  45131. //choose the first one
  45132. _this._vrDevice = devices[0];
  45133. }
  45134. //reset the rig parameters.
  45135. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice, frameData: _this._frameData });
  45136. if (_this._attached) {
  45137. _this.getEngine().enableVR(_this._vrDevice);
  45138. }
  45139. }
  45140. else {
  45141. BABYLON.Tools.Error("No WebVR devices found!");
  45142. }
  45143. });
  45144. }
  45145. _this.rotationQuaternion = new BABYLON.Quaternion();
  45146. _this._quaternionCache = new BABYLON.Quaternion();
  45147. return _this;
  45148. }
  45149. WebVRFreeCamera.prototype._checkInputs = function () {
  45150. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  45151. var currentPost = this._frameData.pose;
  45152. //make sure we have data
  45153. if (currentPost && currentPost.orientation) {
  45154. this._cacheState = currentPost;
  45155. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], -this._cacheState.orientation[2], -this._cacheState.orientation[3]);
  45156. if (this.webVROptions.trackPosition && this._cacheState.position) {
  45157. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  45158. //scale the position accordingly
  45159. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  45160. //add the position offset
  45161. this.position.addInPlace(this._positionOffset);
  45162. }
  45163. }
  45164. }
  45165. _super.prototype._checkInputs.call(this);
  45166. };
  45167. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  45168. _super.prototype.attachControl.call(this, element, noPreventDefault);
  45169. this._attached = true;
  45170. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45171. if (this._vrEnabled) {
  45172. this.getEngine().enableVR(this._vrDevice);
  45173. }
  45174. };
  45175. WebVRFreeCamera.prototype.detachControl = function (element) {
  45176. _super.prototype.detachControl.call(this, element);
  45177. this._vrEnabled = false;
  45178. this._attached = false;
  45179. this.getEngine().disableVR();
  45180. };
  45181. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  45182. //Backwards comp.
  45183. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  45184. //this.getEngine().switchFullscreen(requestPointerlock);
  45185. };
  45186. WebVRFreeCamera.prototype.getClassName = function () {
  45187. return "WebVRFreeCamera";
  45188. };
  45189. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  45190. //uses the vrDisplay's "resetPose()".
  45191. //pitch and roll won't be affected.
  45192. this._vrDevice.resetPose();
  45193. };
  45194. /**
  45195. *
  45196. * Set the position offset of the VR camera
  45197. * The offset will be added to the WebVR pose, after scaling it (if set).
  45198. *
  45199. * @param {Vector3} [newPosition] an optional new position. if not provided, the current camera position will be used.
  45200. *
  45201. * @memberOf WebVRFreeCamera
  45202. */
  45203. WebVRFreeCamera.prototype.setPositionOffset = function (newPosition) {
  45204. if (newPosition) {
  45205. this._positionOffset = newPosition;
  45206. }
  45207. else {
  45208. this._positionOffset.copyFrom(this.position);
  45209. }
  45210. };
  45211. return WebVRFreeCamera;
  45212. }(BABYLON.FreeCamera));
  45213. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  45214. })(BABYLON || (BABYLON = {}));
  45215. //# sourceMappingURL=babylon.webVRCamera.js.map
  45216. var BABYLON;
  45217. (function (BABYLON) {
  45218. // Standard optimizations
  45219. var SceneOptimization = (function () {
  45220. function SceneOptimization(priority) {
  45221. if (priority === void 0) { priority = 0; }
  45222. this.priority = priority;
  45223. this.apply = function (scene) {
  45224. return true; // Return true if everything that can be done was applied
  45225. };
  45226. }
  45227. return SceneOptimization;
  45228. }());
  45229. BABYLON.SceneOptimization = SceneOptimization;
  45230. var TextureOptimization = (function (_super) {
  45231. __extends(TextureOptimization, _super);
  45232. function TextureOptimization(priority, maximumSize) {
  45233. if (priority === void 0) { priority = 0; }
  45234. if (maximumSize === void 0) { maximumSize = 1024; }
  45235. var _this = _super.call(this, priority) || this;
  45236. _this.priority = priority;
  45237. _this.maximumSize = maximumSize;
  45238. _this.apply = function (scene) {
  45239. var allDone = true;
  45240. for (var index = 0; index < scene.textures.length; index++) {
  45241. var texture = scene.textures[index];
  45242. if (!texture.canRescale) {
  45243. continue;
  45244. }
  45245. var currentSize = texture.getSize();
  45246. var maxDimension = Math.max(currentSize.width, currentSize.height);
  45247. if (maxDimension > _this.maximumSize) {
  45248. texture.scale(0.5);
  45249. allDone = false;
  45250. }
  45251. }
  45252. return allDone;
  45253. };
  45254. return _this;
  45255. }
  45256. return TextureOptimization;
  45257. }(SceneOptimization));
  45258. BABYLON.TextureOptimization = TextureOptimization;
  45259. var HardwareScalingOptimization = (function (_super) {
  45260. __extends(HardwareScalingOptimization, _super);
  45261. function HardwareScalingOptimization(priority, maximumScale) {
  45262. if (priority === void 0) { priority = 0; }
  45263. if (maximumScale === void 0) { maximumScale = 2; }
  45264. var _this = _super.call(this, priority) || this;
  45265. _this.priority = priority;
  45266. _this.maximumScale = maximumScale;
  45267. _this._currentScale = 1;
  45268. _this.apply = function (scene) {
  45269. _this._currentScale++;
  45270. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  45271. return _this._currentScale >= _this.maximumScale;
  45272. };
  45273. return _this;
  45274. }
  45275. return HardwareScalingOptimization;
  45276. }(SceneOptimization));
  45277. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  45278. var ShadowsOptimization = (function (_super) {
  45279. __extends(ShadowsOptimization, _super);
  45280. function ShadowsOptimization() {
  45281. var _this = _super.apply(this, arguments) || this;
  45282. _this.apply = function (scene) {
  45283. scene.shadowsEnabled = false;
  45284. return true;
  45285. };
  45286. return _this;
  45287. }
  45288. return ShadowsOptimization;
  45289. }(SceneOptimization));
  45290. BABYLON.ShadowsOptimization = ShadowsOptimization;
  45291. var PostProcessesOptimization = (function (_super) {
  45292. __extends(PostProcessesOptimization, _super);
  45293. function PostProcessesOptimization() {
  45294. var _this = _super.apply(this, arguments) || this;
  45295. _this.apply = function (scene) {
  45296. scene.postProcessesEnabled = false;
  45297. return true;
  45298. };
  45299. return _this;
  45300. }
  45301. return PostProcessesOptimization;
  45302. }(SceneOptimization));
  45303. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  45304. var LensFlaresOptimization = (function (_super) {
  45305. __extends(LensFlaresOptimization, _super);
  45306. function LensFlaresOptimization() {
  45307. var _this = _super.apply(this, arguments) || this;
  45308. _this.apply = function (scene) {
  45309. scene.lensFlaresEnabled = false;
  45310. return true;
  45311. };
  45312. return _this;
  45313. }
  45314. return LensFlaresOptimization;
  45315. }(SceneOptimization));
  45316. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  45317. var ParticlesOptimization = (function (_super) {
  45318. __extends(ParticlesOptimization, _super);
  45319. function ParticlesOptimization() {
  45320. var _this = _super.apply(this, arguments) || this;
  45321. _this.apply = function (scene) {
  45322. scene.particlesEnabled = false;
  45323. return true;
  45324. };
  45325. return _this;
  45326. }
  45327. return ParticlesOptimization;
  45328. }(SceneOptimization));
  45329. BABYLON.ParticlesOptimization = ParticlesOptimization;
  45330. var RenderTargetsOptimization = (function (_super) {
  45331. __extends(RenderTargetsOptimization, _super);
  45332. function RenderTargetsOptimization() {
  45333. var _this = _super.apply(this, arguments) || this;
  45334. _this.apply = function (scene) {
  45335. scene.renderTargetsEnabled = false;
  45336. return true;
  45337. };
  45338. return _this;
  45339. }
  45340. return RenderTargetsOptimization;
  45341. }(SceneOptimization));
  45342. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  45343. var MergeMeshesOptimization = (function (_super) {
  45344. __extends(MergeMeshesOptimization, _super);
  45345. function MergeMeshesOptimization() {
  45346. var _this = _super.apply(this, arguments) || this;
  45347. _this._canBeMerged = function (abstractMesh) {
  45348. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  45349. return false;
  45350. }
  45351. var mesh = abstractMesh;
  45352. if (!mesh.isVisible || !mesh.isEnabled()) {
  45353. return false;
  45354. }
  45355. if (mesh.instances.length > 0) {
  45356. return false;
  45357. }
  45358. if (mesh.skeleton || mesh.hasLODLevels) {
  45359. return false;
  45360. }
  45361. if (mesh.parent) {
  45362. return false;
  45363. }
  45364. return true;
  45365. };
  45366. _this.apply = function (scene, updateSelectionTree) {
  45367. var globalPool = scene.meshes.slice(0);
  45368. var globalLength = globalPool.length;
  45369. for (var index = 0; index < globalLength; index++) {
  45370. var currentPool = new Array();
  45371. var current = globalPool[index];
  45372. // Checks
  45373. if (!_this._canBeMerged(current)) {
  45374. continue;
  45375. }
  45376. currentPool.push(current);
  45377. // Find compatible meshes
  45378. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  45379. var otherMesh = globalPool[subIndex];
  45380. if (!_this._canBeMerged(otherMesh)) {
  45381. continue;
  45382. }
  45383. if (otherMesh.material !== current.material) {
  45384. continue;
  45385. }
  45386. if (otherMesh.checkCollisions !== current.checkCollisions) {
  45387. continue;
  45388. }
  45389. currentPool.push(otherMesh);
  45390. globalLength--;
  45391. globalPool.splice(subIndex, 1);
  45392. subIndex--;
  45393. }
  45394. if (currentPool.length < 2) {
  45395. continue;
  45396. }
  45397. // Merge meshes
  45398. BABYLON.Mesh.MergeMeshes(currentPool);
  45399. }
  45400. if (updateSelectionTree != undefined) {
  45401. if (updateSelectionTree) {
  45402. scene.createOrUpdateSelectionOctree();
  45403. }
  45404. }
  45405. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  45406. scene.createOrUpdateSelectionOctree();
  45407. }
  45408. return true;
  45409. };
  45410. return _this;
  45411. }
  45412. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  45413. get: function () {
  45414. return MergeMeshesOptimization._UpdateSelectionTree;
  45415. },
  45416. set: function (value) {
  45417. MergeMeshesOptimization._UpdateSelectionTree = value;
  45418. },
  45419. enumerable: true,
  45420. configurable: true
  45421. });
  45422. return MergeMeshesOptimization;
  45423. }(SceneOptimization));
  45424. MergeMeshesOptimization._UpdateSelectionTree = false;
  45425. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  45426. // Options
  45427. var SceneOptimizerOptions = (function () {
  45428. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  45429. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  45430. if (trackerDuration === void 0) { trackerDuration = 2000; }
  45431. this.targetFrameRate = targetFrameRate;
  45432. this.trackerDuration = trackerDuration;
  45433. this.optimizations = new Array();
  45434. }
  45435. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  45436. var result = new SceneOptimizerOptions(targetFrameRate);
  45437. var priority = 0;
  45438. result.optimizations.push(new MergeMeshesOptimization(priority));
  45439. result.optimizations.push(new ShadowsOptimization(priority));
  45440. result.optimizations.push(new LensFlaresOptimization(priority));
  45441. // Next priority
  45442. priority++;
  45443. result.optimizations.push(new PostProcessesOptimization(priority));
  45444. result.optimizations.push(new ParticlesOptimization(priority));
  45445. // Next priority
  45446. priority++;
  45447. result.optimizations.push(new TextureOptimization(priority, 1024));
  45448. return result;
  45449. };
  45450. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  45451. var result = new SceneOptimizerOptions(targetFrameRate);
  45452. var priority = 0;
  45453. result.optimizations.push(new MergeMeshesOptimization(priority));
  45454. result.optimizations.push(new ShadowsOptimization(priority));
  45455. result.optimizations.push(new LensFlaresOptimization(priority));
  45456. // Next priority
  45457. priority++;
  45458. result.optimizations.push(new PostProcessesOptimization(priority));
  45459. result.optimizations.push(new ParticlesOptimization(priority));
  45460. // Next priority
  45461. priority++;
  45462. result.optimizations.push(new TextureOptimization(priority, 512));
  45463. // Next priority
  45464. priority++;
  45465. result.optimizations.push(new RenderTargetsOptimization(priority));
  45466. // Next priority
  45467. priority++;
  45468. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  45469. return result;
  45470. };
  45471. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  45472. var result = new SceneOptimizerOptions(targetFrameRate);
  45473. var priority = 0;
  45474. result.optimizations.push(new MergeMeshesOptimization(priority));
  45475. result.optimizations.push(new ShadowsOptimization(priority));
  45476. result.optimizations.push(new LensFlaresOptimization(priority));
  45477. // Next priority
  45478. priority++;
  45479. result.optimizations.push(new PostProcessesOptimization(priority));
  45480. result.optimizations.push(new ParticlesOptimization(priority));
  45481. // Next priority
  45482. priority++;
  45483. result.optimizations.push(new TextureOptimization(priority, 256));
  45484. // Next priority
  45485. priority++;
  45486. result.optimizations.push(new RenderTargetsOptimization(priority));
  45487. // Next priority
  45488. priority++;
  45489. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  45490. return result;
  45491. };
  45492. return SceneOptimizerOptions;
  45493. }());
  45494. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  45495. // Scene optimizer tool
  45496. var SceneOptimizer = (function () {
  45497. function SceneOptimizer() {
  45498. }
  45499. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  45500. // TODO: add an epsilon
  45501. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  45502. if (onSuccess) {
  45503. onSuccess();
  45504. }
  45505. return;
  45506. }
  45507. // Apply current level of optimizations
  45508. var allDone = true;
  45509. var noOptimizationApplied = true;
  45510. for (var index = 0; index < options.optimizations.length; index++) {
  45511. var optimization = options.optimizations[index];
  45512. if (optimization.priority === currentPriorityLevel) {
  45513. noOptimizationApplied = false;
  45514. allDone = allDone && optimization.apply(scene);
  45515. }
  45516. }
  45517. // If no optimization was applied, this is a failure :(
  45518. if (noOptimizationApplied) {
  45519. if (onFailure) {
  45520. onFailure();
  45521. }
  45522. return;
  45523. }
  45524. // If all optimizations were done, move to next level
  45525. if (allDone) {
  45526. currentPriorityLevel++;
  45527. }
  45528. // Let's the system running for a specific amount of time before checking FPS
  45529. scene.executeWhenReady(function () {
  45530. setTimeout(function () {
  45531. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  45532. }, options.trackerDuration);
  45533. });
  45534. };
  45535. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  45536. if (!options) {
  45537. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  45538. }
  45539. // Let's the system running for a specific amount of time before checking FPS
  45540. scene.executeWhenReady(function () {
  45541. setTimeout(function () {
  45542. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  45543. }, options.trackerDuration);
  45544. });
  45545. };
  45546. return SceneOptimizer;
  45547. }());
  45548. BABYLON.SceneOptimizer = SceneOptimizer;
  45549. })(BABYLON || (BABYLON = {}));
  45550. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  45551. var BABYLON;
  45552. (function (BABYLON) {
  45553. var Internals;
  45554. (function (Internals) {
  45555. var MeshLODLevel = (function () {
  45556. function MeshLODLevel(distance, mesh) {
  45557. this.distance = distance;
  45558. this.mesh = mesh;
  45559. }
  45560. return MeshLODLevel;
  45561. }());
  45562. Internals.MeshLODLevel = MeshLODLevel;
  45563. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45564. })(BABYLON || (BABYLON = {}));
  45565. //# sourceMappingURL=babylon.meshLODLevel.js.map
  45566. var BABYLON;
  45567. (function (BABYLON) {
  45568. var RawTexture = (function (_super) {
  45569. __extends(RawTexture, _super);
  45570. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  45571. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45572. if (invertY === void 0) { invertY = false; }
  45573. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45574. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  45575. _this.format = format;
  45576. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  45577. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45578. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45579. return _this;
  45580. }
  45581. RawTexture.prototype.update = function (data) {
  45582. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  45583. };
  45584. // Statics
  45585. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45586. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45587. if (invertY === void 0) { invertY = false; }
  45588. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45589. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  45590. };
  45591. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45592. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45593. if (invertY === void 0) { invertY = false; }
  45594. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45595. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45596. };
  45597. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45598. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45599. if (invertY === void 0) { invertY = false; }
  45600. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45601. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45602. };
  45603. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45604. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45605. if (invertY === void 0) { invertY = false; }
  45606. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45607. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  45608. };
  45609. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45610. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45611. if (invertY === void 0) { invertY = false; }
  45612. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45613. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  45614. };
  45615. return RawTexture;
  45616. }(BABYLON.Texture));
  45617. BABYLON.RawTexture = RawTexture;
  45618. })(BABYLON || (BABYLON = {}));
  45619. //# sourceMappingURL=babylon.rawTexture.js.map
  45620. var BABYLON;
  45621. (function (BABYLON) {
  45622. var IndexedVector2 = (function (_super) {
  45623. __extends(IndexedVector2, _super);
  45624. function IndexedVector2(original, index) {
  45625. var _this = _super.call(this, original.x, original.y) || this;
  45626. _this.index = index;
  45627. return _this;
  45628. }
  45629. return IndexedVector2;
  45630. }(BABYLON.Vector2));
  45631. var PolygonPoints = (function () {
  45632. function PolygonPoints() {
  45633. this.elements = new Array();
  45634. }
  45635. PolygonPoints.prototype.add = function (originalPoints) {
  45636. var _this = this;
  45637. var result = new Array();
  45638. originalPoints.forEach(function (point) {
  45639. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  45640. var newPoint = new IndexedVector2(point, _this.elements.length);
  45641. result.push(newPoint);
  45642. _this.elements.push(newPoint);
  45643. }
  45644. });
  45645. return result;
  45646. };
  45647. PolygonPoints.prototype.computeBounds = function () {
  45648. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  45649. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  45650. this.elements.forEach(function (point) {
  45651. // x
  45652. if (point.x < lmin.x) {
  45653. lmin.x = point.x;
  45654. }
  45655. else if (point.x > lmax.x) {
  45656. lmax.x = point.x;
  45657. }
  45658. // y
  45659. if (point.y < lmin.y) {
  45660. lmin.y = point.y;
  45661. }
  45662. else if (point.y > lmax.y) {
  45663. lmax.y = point.y;
  45664. }
  45665. });
  45666. return {
  45667. min: lmin,
  45668. max: lmax,
  45669. width: lmax.x - lmin.x,
  45670. height: lmax.y - lmin.y
  45671. };
  45672. };
  45673. return PolygonPoints;
  45674. }());
  45675. var Polygon = (function () {
  45676. function Polygon() {
  45677. }
  45678. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  45679. return [
  45680. new BABYLON.Vector2(xmin, ymin),
  45681. new BABYLON.Vector2(xmax, ymin),
  45682. new BABYLON.Vector2(xmax, ymax),
  45683. new BABYLON.Vector2(xmin, ymax)
  45684. ];
  45685. };
  45686. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  45687. if (cx === void 0) { cx = 0; }
  45688. if (cy === void 0) { cy = 0; }
  45689. if (numberOfSides === void 0) { numberOfSides = 32; }
  45690. var result = new Array();
  45691. var angle = 0;
  45692. var increment = (Math.PI * 2) / numberOfSides;
  45693. for (var i = 0; i < numberOfSides; i++) {
  45694. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  45695. angle -= increment;
  45696. }
  45697. return result;
  45698. };
  45699. Polygon.Parse = function (input) {
  45700. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  45701. var i, result = [];
  45702. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  45703. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  45704. }
  45705. return result;
  45706. };
  45707. Polygon.StartingAt = function (x, y) {
  45708. return BABYLON.Path2.StartingAt(x, y);
  45709. };
  45710. return Polygon;
  45711. }());
  45712. BABYLON.Polygon = Polygon;
  45713. var PolygonMeshBuilder = (function () {
  45714. function PolygonMeshBuilder(name, contours, scene) {
  45715. this._points = new PolygonPoints();
  45716. this._outlinepoints = new PolygonPoints();
  45717. this._holes = [];
  45718. this._epoints = new Array();
  45719. this._eholes = new Array();
  45720. this._name = name;
  45721. this._scene = scene;
  45722. var points;
  45723. if (contours instanceof BABYLON.Path2) {
  45724. points = contours.getPoints();
  45725. }
  45726. else {
  45727. points = contours;
  45728. }
  45729. this._addToepoint(points);
  45730. this._points.add(points);
  45731. this._outlinepoints.add(points);
  45732. }
  45733. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  45734. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  45735. var p = points_1[_i];
  45736. this._epoints.push(p.x, p.y);
  45737. }
  45738. };
  45739. PolygonMeshBuilder.prototype.addHole = function (hole) {
  45740. this._points.add(hole);
  45741. var holepoints = new PolygonPoints();
  45742. holepoints.add(hole);
  45743. this._holes.push(holepoints);
  45744. this._eholes.push(this._epoints.length / 2);
  45745. this._addToepoint(hole);
  45746. return this;
  45747. };
  45748. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  45749. var _this = this;
  45750. if (updatable === void 0) { updatable = false; }
  45751. var result = new BABYLON.Mesh(this._name, this._scene);
  45752. var normals = [];
  45753. var positions = [];
  45754. var uvs = [];
  45755. var bounds = this._points.computeBounds();
  45756. this._points.elements.forEach(function (p) {
  45757. normals.push(0, 1.0, 0);
  45758. positions.push(p.x, 0, p.y);
  45759. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  45760. });
  45761. var indices = [];
  45762. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  45763. for (var i = 0; i < res.length; i++) {
  45764. indices.push(res[i]);
  45765. }
  45766. if (depth > 0) {
  45767. var positionscount = (positions.length / 3); //get the current pointcount
  45768. this._points.elements.forEach(function (p) {
  45769. normals.push(0, -1.0, 0);
  45770. positions.push(p.x, -depth, p.y);
  45771. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  45772. });
  45773. var totalCount = indices.length;
  45774. for (var i = 0; i < totalCount; i += 3) {
  45775. var i0 = indices[i + 0];
  45776. var i1 = indices[i + 1];
  45777. var i2 = indices[i + 2];
  45778. indices.push(i2 + positionscount);
  45779. indices.push(i1 + positionscount);
  45780. indices.push(i0 + positionscount);
  45781. }
  45782. //Add the sides
  45783. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  45784. this._holes.forEach(function (hole) {
  45785. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  45786. });
  45787. }
  45788. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  45789. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  45790. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  45791. result.setIndices(indices);
  45792. return result;
  45793. };
  45794. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  45795. var StartIndex = positions.length / 3;
  45796. var ulength = 0;
  45797. for (var i = 0; i < points.elements.length; i++) {
  45798. var p = points.elements[i];
  45799. var p1;
  45800. if ((i + 1) > points.elements.length - 1) {
  45801. p1 = points.elements[0];
  45802. }
  45803. else {
  45804. p1 = points.elements[i + 1];
  45805. }
  45806. positions.push(p.x, 0, p.y);
  45807. positions.push(p.x, -depth, p.y);
  45808. positions.push(p1.x, 0, p1.y);
  45809. positions.push(p1.x, -depth, p1.y);
  45810. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  45811. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  45812. var v3 = v2.subtract(v1);
  45813. var v4 = new BABYLON.Vector3(0, 1, 0);
  45814. var vn = BABYLON.Vector3.Cross(v3, v4);
  45815. vn = vn.normalize();
  45816. uvs.push(ulength / bounds.width, 0);
  45817. uvs.push(ulength / bounds.width, 1);
  45818. ulength += v3.length();
  45819. uvs.push((ulength / bounds.width), 0);
  45820. uvs.push((ulength / bounds.width), 1);
  45821. if (!flip) {
  45822. normals.push(-vn.x, -vn.y, -vn.z);
  45823. normals.push(-vn.x, -vn.y, -vn.z);
  45824. normals.push(-vn.x, -vn.y, -vn.z);
  45825. normals.push(-vn.x, -vn.y, -vn.z);
  45826. indices.push(StartIndex);
  45827. indices.push(StartIndex + 1);
  45828. indices.push(StartIndex + 2);
  45829. indices.push(StartIndex + 1);
  45830. indices.push(StartIndex + 3);
  45831. indices.push(StartIndex + 2);
  45832. }
  45833. else {
  45834. normals.push(vn.x, vn.y, vn.z);
  45835. normals.push(vn.x, vn.y, vn.z);
  45836. normals.push(vn.x, vn.y, vn.z);
  45837. normals.push(vn.x, vn.y, vn.z);
  45838. indices.push(StartIndex);
  45839. indices.push(StartIndex + 2);
  45840. indices.push(StartIndex + 1);
  45841. indices.push(StartIndex + 1);
  45842. indices.push(StartIndex + 2);
  45843. indices.push(StartIndex + 3);
  45844. }
  45845. StartIndex += 4;
  45846. }
  45847. ;
  45848. };
  45849. return PolygonMeshBuilder;
  45850. }());
  45851. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  45852. })(BABYLON || (BABYLON = {}));
  45853. //# sourceMappingURL=babylon.polygonMesh.js.map
  45854. var BABYLON;
  45855. (function (BABYLON) {
  45856. var Octree = (function () {
  45857. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  45858. if (maxDepth === void 0) { maxDepth = 2; }
  45859. this.maxDepth = maxDepth;
  45860. this.dynamicContent = new Array();
  45861. this._maxBlockCapacity = maxBlockCapacity || 64;
  45862. this._selectionContent = new BABYLON.SmartArray(1024);
  45863. this._creationFunc = creationFunc;
  45864. }
  45865. // Methods
  45866. Octree.prototype.update = function (worldMin, worldMax, entries) {
  45867. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  45868. };
  45869. Octree.prototype.addMesh = function (entry) {
  45870. for (var index = 0; index < this.blocks.length; index++) {
  45871. var block = this.blocks[index];
  45872. block.addEntry(entry);
  45873. }
  45874. };
  45875. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  45876. this._selectionContent.reset();
  45877. for (var index = 0; index < this.blocks.length; index++) {
  45878. var block = this.blocks[index];
  45879. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  45880. }
  45881. if (allowDuplicate) {
  45882. this._selectionContent.concat(this.dynamicContent);
  45883. }
  45884. else {
  45885. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45886. }
  45887. return this._selectionContent;
  45888. };
  45889. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  45890. this._selectionContent.reset();
  45891. for (var index = 0; index < this.blocks.length; index++) {
  45892. var block = this.blocks[index];
  45893. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  45894. }
  45895. if (allowDuplicate) {
  45896. this._selectionContent.concat(this.dynamicContent);
  45897. }
  45898. else {
  45899. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45900. }
  45901. return this._selectionContent;
  45902. };
  45903. Octree.prototype.intersectsRay = function (ray) {
  45904. this._selectionContent.reset();
  45905. for (var index = 0; index < this.blocks.length; index++) {
  45906. var block = this.blocks[index];
  45907. block.intersectsRay(ray, this._selectionContent);
  45908. }
  45909. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45910. return this._selectionContent;
  45911. };
  45912. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  45913. target.blocks = new Array();
  45914. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  45915. // Segmenting space
  45916. for (var x = 0; x < 2; x++) {
  45917. for (var y = 0; y < 2; y++) {
  45918. for (var z = 0; z < 2; z++) {
  45919. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  45920. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  45921. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  45922. block.addEntries(entries);
  45923. target.blocks.push(block);
  45924. }
  45925. }
  45926. }
  45927. };
  45928. return Octree;
  45929. }());
  45930. Octree.CreationFuncForMeshes = function (entry, block) {
  45931. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  45932. block.entries.push(entry);
  45933. }
  45934. };
  45935. Octree.CreationFuncForSubMeshes = function (entry, block) {
  45936. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  45937. block.entries.push(entry);
  45938. }
  45939. };
  45940. BABYLON.Octree = Octree;
  45941. })(BABYLON || (BABYLON = {}));
  45942. //# sourceMappingURL=babylon.octree.js.map
  45943. var BABYLON;
  45944. (function (BABYLON) {
  45945. var OctreeBlock = (function () {
  45946. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  45947. this.entries = new Array();
  45948. this._boundingVectors = new Array();
  45949. this._capacity = capacity;
  45950. this._depth = depth;
  45951. this._maxDepth = maxDepth;
  45952. this._creationFunc = creationFunc;
  45953. this._minPoint = minPoint;
  45954. this._maxPoint = maxPoint;
  45955. this._boundingVectors.push(minPoint.clone());
  45956. this._boundingVectors.push(maxPoint.clone());
  45957. this._boundingVectors.push(minPoint.clone());
  45958. this._boundingVectors[2].x = maxPoint.x;
  45959. this._boundingVectors.push(minPoint.clone());
  45960. this._boundingVectors[3].y = maxPoint.y;
  45961. this._boundingVectors.push(minPoint.clone());
  45962. this._boundingVectors[4].z = maxPoint.z;
  45963. this._boundingVectors.push(maxPoint.clone());
  45964. this._boundingVectors[5].z = minPoint.z;
  45965. this._boundingVectors.push(maxPoint.clone());
  45966. this._boundingVectors[6].x = minPoint.x;
  45967. this._boundingVectors.push(maxPoint.clone());
  45968. this._boundingVectors[7].y = minPoint.y;
  45969. }
  45970. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  45971. // Property
  45972. get: function () {
  45973. return this._capacity;
  45974. },
  45975. enumerable: true,
  45976. configurable: true
  45977. });
  45978. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  45979. get: function () {
  45980. return this._minPoint;
  45981. },
  45982. enumerable: true,
  45983. configurable: true
  45984. });
  45985. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  45986. get: function () {
  45987. return this._maxPoint;
  45988. },
  45989. enumerable: true,
  45990. configurable: true
  45991. });
  45992. // Methods
  45993. OctreeBlock.prototype.addEntry = function (entry) {
  45994. if (this.blocks) {
  45995. for (var index = 0; index < this.blocks.length; index++) {
  45996. var block = this.blocks[index];
  45997. block.addEntry(entry);
  45998. }
  45999. return;
  46000. }
  46001. this._creationFunc(entry, this);
  46002. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  46003. this.createInnerBlocks();
  46004. }
  46005. };
  46006. OctreeBlock.prototype.addEntries = function (entries) {
  46007. for (var index = 0; index < entries.length; index++) {
  46008. var mesh = entries[index];
  46009. this.addEntry(mesh);
  46010. }
  46011. };
  46012. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  46013. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  46014. if (this.blocks) {
  46015. for (var index = 0; index < this.blocks.length; index++) {
  46016. var block = this.blocks[index];
  46017. block.select(frustumPlanes, selection, allowDuplicate);
  46018. }
  46019. return;
  46020. }
  46021. if (allowDuplicate) {
  46022. selection.concat(this.entries);
  46023. }
  46024. else {
  46025. selection.concatWithNoDuplicate(this.entries);
  46026. }
  46027. }
  46028. };
  46029. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  46030. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  46031. if (this.blocks) {
  46032. for (var index = 0; index < this.blocks.length; index++) {
  46033. var block = this.blocks[index];
  46034. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  46035. }
  46036. return;
  46037. }
  46038. if (allowDuplicate) {
  46039. selection.concat(this.entries);
  46040. }
  46041. else {
  46042. selection.concatWithNoDuplicate(this.entries);
  46043. }
  46044. }
  46045. };
  46046. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  46047. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  46048. if (this.blocks) {
  46049. for (var index = 0; index < this.blocks.length; index++) {
  46050. var block = this.blocks[index];
  46051. block.intersectsRay(ray, selection);
  46052. }
  46053. return;
  46054. }
  46055. selection.concatWithNoDuplicate(this.entries);
  46056. }
  46057. };
  46058. OctreeBlock.prototype.createInnerBlocks = function () {
  46059. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  46060. };
  46061. return OctreeBlock;
  46062. }());
  46063. BABYLON.OctreeBlock = OctreeBlock;
  46064. })(BABYLON || (BABYLON = {}));
  46065. //# sourceMappingURL=babylon.octreeBlock.js.map
  46066. var BABYLON;
  46067. (function (BABYLON) {
  46068. var BlurPostProcess = (function (_super) {
  46069. __extends(BlurPostProcess, _super);
  46070. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  46071. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  46072. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  46073. _this.direction = direction;
  46074. _this.blurWidth = blurWidth;
  46075. _this.onApplyObservable.add(function (effect) {
  46076. effect.setFloat2("screenSize", _this.width, _this.height);
  46077. effect.setVector2("direction", _this.direction);
  46078. effect.setFloat("blurWidth", _this.blurWidth);
  46079. });
  46080. return _this;
  46081. }
  46082. return BlurPostProcess;
  46083. }(BABYLON.PostProcess));
  46084. BABYLON.BlurPostProcess = BlurPostProcess;
  46085. })(BABYLON || (BABYLON = {}));
  46086. //# sourceMappingURL=babylon.blurPostProcess.js.map
  46087. var BABYLON;
  46088. (function (BABYLON) {
  46089. var RefractionPostProcess = (function (_super) {
  46090. __extends(RefractionPostProcess, _super);
  46091. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  46092. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  46093. _this.color = color;
  46094. _this.depth = depth;
  46095. _this.colorLevel = colorLevel;
  46096. _this.onActivateObservable.add(function (cam) {
  46097. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  46098. });
  46099. _this.onApplyObservable.add(function (effect) {
  46100. effect.setColor3("baseColor", _this.color);
  46101. effect.setFloat("depth", _this.depth);
  46102. effect.setFloat("colorLevel", _this.colorLevel);
  46103. effect.setTexture("refractionSampler", _this._refRexture);
  46104. });
  46105. return _this;
  46106. }
  46107. // Methods
  46108. RefractionPostProcess.prototype.dispose = function (camera) {
  46109. if (this._refRexture) {
  46110. this._refRexture.dispose();
  46111. }
  46112. _super.prototype.dispose.call(this, camera);
  46113. };
  46114. return RefractionPostProcess;
  46115. }(BABYLON.PostProcess));
  46116. BABYLON.RefractionPostProcess = RefractionPostProcess;
  46117. })(BABYLON || (BABYLON = {}));
  46118. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  46119. var BABYLON;
  46120. (function (BABYLON) {
  46121. var BlackAndWhitePostProcess = (function (_super) {
  46122. __extends(BlackAndWhitePostProcess, _super);
  46123. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  46124. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  46125. }
  46126. return BlackAndWhitePostProcess;
  46127. }(BABYLON.PostProcess));
  46128. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  46129. })(BABYLON || (BABYLON = {}));
  46130. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  46131. var BABYLON;
  46132. (function (BABYLON) {
  46133. var ConvolutionPostProcess = (function (_super) {
  46134. __extends(ConvolutionPostProcess, _super);
  46135. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  46136. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  46137. _this.kernel = kernel;
  46138. _this.onApply = function (effect) {
  46139. effect.setFloat2("screenSize", _this.width, _this.height);
  46140. effect.setArray("kernel", _this.kernel);
  46141. };
  46142. return _this;
  46143. }
  46144. return ConvolutionPostProcess;
  46145. }(BABYLON.PostProcess));
  46146. // Statics
  46147. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  46148. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  46149. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  46150. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  46151. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  46152. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  46153. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  46154. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  46155. })(BABYLON || (BABYLON = {}));
  46156. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  46157. var BABYLON;
  46158. (function (BABYLON) {
  46159. var FilterPostProcess = (function (_super) {
  46160. __extends(FilterPostProcess, _super);
  46161. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  46162. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  46163. _this.kernelMatrix = kernelMatrix;
  46164. _this.onApply = function (effect) {
  46165. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  46166. };
  46167. return _this;
  46168. }
  46169. return FilterPostProcess;
  46170. }(BABYLON.PostProcess));
  46171. BABYLON.FilterPostProcess = FilterPostProcess;
  46172. })(BABYLON || (BABYLON = {}));
  46173. //# sourceMappingURL=babylon.filterPostProcess.js.map
  46174. var BABYLON;
  46175. (function (BABYLON) {
  46176. var FxaaPostProcess = (function (_super) {
  46177. __extends(FxaaPostProcess, _super);
  46178. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  46179. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable) || this;
  46180. _this.onSizeChangedObservable.add(function () {
  46181. _this.texelWidth = 1.0 / _this.width;
  46182. _this.texelHeight = 1.0 / _this.height;
  46183. });
  46184. _this.onApplyObservable.add(function (effect) {
  46185. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  46186. });
  46187. return _this;
  46188. }
  46189. return FxaaPostProcess;
  46190. }(BABYLON.PostProcess));
  46191. BABYLON.FxaaPostProcess = FxaaPostProcess;
  46192. })(BABYLON || (BABYLON = {}));
  46193. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  46194. var BABYLON;
  46195. (function (BABYLON) {
  46196. var StereoscopicInterlacePostProcess = (function (_super) {
  46197. __extends(StereoscopicInterlacePostProcess, _super);
  46198. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  46199. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  46200. _this._passedProcess = rigCameras[0]._rigPostProcess;
  46201. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  46202. _this.onSizeChangedObservable.add(function () {
  46203. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  46204. });
  46205. _this.onApplyObservable.add(function (effect) {
  46206. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  46207. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  46208. });
  46209. return _this;
  46210. }
  46211. return StereoscopicInterlacePostProcess;
  46212. }(BABYLON.PostProcess));
  46213. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  46214. })(BABYLON || (BABYLON = {}));
  46215. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  46216. var BABYLON;
  46217. (function (BABYLON) {
  46218. var LensFlare = (function () {
  46219. function LensFlare(size, position, color, imgUrl, system) {
  46220. this.size = size;
  46221. this.position = position;
  46222. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  46223. this.dispose = function () {
  46224. if (this.texture) {
  46225. this.texture.dispose();
  46226. }
  46227. // Remove from scene
  46228. var index = this._system.lensFlares.indexOf(this);
  46229. this._system.lensFlares.splice(index, 1);
  46230. };
  46231. this.color = color || new BABYLON.Color3(1, 1, 1);
  46232. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  46233. this._system = system;
  46234. system.lensFlares.push(this);
  46235. }
  46236. return LensFlare;
  46237. }());
  46238. BABYLON.LensFlare = LensFlare;
  46239. })(BABYLON || (BABYLON = {}));
  46240. //# sourceMappingURL=babylon.lensFlare.js.map
  46241. var BABYLON;
  46242. (function (BABYLON) {
  46243. var LensFlareSystem = (function () {
  46244. function LensFlareSystem(name, emitter, scene) {
  46245. this.name = name;
  46246. this.lensFlares = new Array();
  46247. this.borderLimit = 300;
  46248. this.viewportBorder = 0;
  46249. this.layerMask = 0x0FFFFFFF;
  46250. this._vertexBuffers = {};
  46251. this._isEnabled = true;
  46252. this._scene = scene;
  46253. this._emitter = emitter;
  46254. this.id = name;
  46255. scene.lensFlareSystems.push(this);
  46256. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  46257. var engine = scene.getEngine();
  46258. // VBO
  46259. var vertices = [];
  46260. vertices.push(1, 1);
  46261. vertices.push(-1, 1);
  46262. vertices.push(-1, -1);
  46263. vertices.push(1, -1);
  46264. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  46265. // Indices
  46266. var indices = [];
  46267. indices.push(0);
  46268. indices.push(1);
  46269. indices.push(2);
  46270. indices.push(0);
  46271. indices.push(2);
  46272. indices.push(3);
  46273. this._indexBuffer = engine.createIndexBuffer(indices);
  46274. // Effects
  46275. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  46276. }
  46277. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  46278. get: function () {
  46279. return this._isEnabled;
  46280. },
  46281. set: function (value) {
  46282. this._isEnabled = value;
  46283. },
  46284. enumerable: true,
  46285. configurable: true
  46286. });
  46287. LensFlareSystem.prototype.getScene = function () {
  46288. return this._scene;
  46289. };
  46290. LensFlareSystem.prototype.getEmitter = function () {
  46291. return this._emitter;
  46292. };
  46293. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  46294. this._emitter = newEmitter;
  46295. };
  46296. LensFlareSystem.prototype.getEmitterPosition = function () {
  46297. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  46298. };
  46299. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  46300. var position = this.getEmitterPosition();
  46301. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  46302. this._positionX = position.x;
  46303. this._positionY = position.y;
  46304. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  46305. if (this.viewportBorder > 0) {
  46306. globalViewport.x -= this.viewportBorder;
  46307. globalViewport.y -= this.viewportBorder;
  46308. globalViewport.width += this.viewportBorder * 2;
  46309. globalViewport.height += this.viewportBorder * 2;
  46310. position.x += this.viewportBorder;
  46311. position.y += this.viewportBorder;
  46312. this._positionX += this.viewportBorder;
  46313. this._positionY += this.viewportBorder;
  46314. }
  46315. if (position.z > 0) {
  46316. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  46317. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  46318. return true;
  46319. }
  46320. return true;
  46321. }
  46322. return false;
  46323. };
  46324. LensFlareSystem.prototype._isVisible = function () {
  46325. if (!this._isEnabled) {
  46326. return false;
  46327. }
  46328. var emitterPosition = this.getEmitterPosition();
  46329. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  46330. var distance = direction.length();
  46331. direction.normalize();
  46332. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  46333. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  46334. return !pickInfo.hit || pickInfo.distance > distance;
  46335. };
  46336. LensFlareSystem.prototype.render = function () {
  46337. if (!this._effect.isReady())
  46338. return false;
  46339. var engine = this._scene.getEngine();
  46340. var viewport = this._scene.activeCamera.viewport;
  46341. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  46342. // Position
  46343. if (!this.computeEffectivePosition(globalViewport)) {
  46344. return false;
  46345. }
  46346. // Visibility
  46347. if (!this._isVisible()) {
  46348. return false;
  46349. }
  46350. // Intensity
  46351. var awayX;
  46352. var awayY;
  46353. if (this._positionX < this.borderLimit + globalViewport.x) {
  46354. awayX = this.borderLimit + globalViewport.x - this._positionX;
  46355. }
  46356. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  46357. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  46358. }
  46359. else {
  46360. awayX = 0;
  46361. }
  46362. if (this._positionY < this.borderLimit + globalViewport.y) {
  46363. awayY = this.borderLimit + globalViewport.y - this._positionY;
  46364. }
  46365. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  46366. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  46367. }
  46368. else {
  46369. awayY = 0;
  46370. }
  46371. var away = (awayX > awayY) ? awayX : awayY;
  46372. away -= this.viewportBorder;
  46373. if (away > this.borderLimit) {
  46374. away = this.borderLimit;
  46375. }
  46376. var intensity = 1.0 - (away / this.borderLimit);
  46377. if (intensity < 0) {
  46378. return false;
  46379. }
  46380. if (intensity > 1.0) {
  46381. intensity = 1.0;
  46382. }
  46383. if (this.viewportBorder > 0) {
  46384. globalViewport.x += this.viewportBorder;
  46385. globalViewport.y += this.viewportBorder;
  46386. globalViewport.width -= this.viewportBorder * 2;
  46387. globalViewport.height -= this.viewportBorder * 2;
  46388. this._positionX -= this.viewportBorder;
  46389. this._positionY -= this.viewportBorder;
  46390. }
  46391. // Position
  46392. var centerX = globalViewport.x + globalViewport.width / 2;
  46393. var centerY = globalViewport.y + globalViewport.height / 2;
  46394. var distX = centerX - this._positionX;
  46395. var distY = centerY - this._positionY;
  46396. // Effects
  46397. engine.enableEffect(this._effect);
  46398. engine.setState(false);
  46399. engine.setDepthBuffer(false);
  46400. // VBOs
  46401. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  46402. // Flares
  46403. for (var index = 0; index < this.lensFlares.length; index++) {
  46404. var flare = this.lensFlares[index];
  46405. engine.setAlphaMode(flare.alphaMode);
  46406. var x = centerX - (distX * flare.position);
  46407. var y = centerY - (distY * flare.position);
  46408. var cw = flare.size;
  46409. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  46410. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  46411. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  46412. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  46413. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  46414. // Texture
  46415. this._effect.setTexture("textureSampler", flare.texture);
  46416. // Color
  46417. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  46418. // Draw order
  46419. engine.draw(true, 0, 6);
  46420. }
  46421. engine.setDepthBuffer(true);
  46422. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46423. return true;
  46424. };
  46425. LensFlareSystem.prototype.dispose = function () {
  46426. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  46427. if (vertexBuffer) {
  46428. vertexBuffer.dispose();
  46429. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  46430. }
  46431. if (this._indexBuffer) {
  46432. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46433. this._indexBuffer = null;
  46434. }
  46435. while (this.lensFlares.length) {
  46436. this.lensFlares[0].dispose();
  46437. }
  46438. // Remove from scene
  46439. var index = this._scene.lensFlareSystems.indexOf(this);
  46440. this._scene.lensFlareSystems.splice(index, 1);
  46441. };
  46442. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  46443. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  46444. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  46445. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  46446. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  46447. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  46448. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  46449. var parsedFlare = parsedLensFlareSystem.flares[index];
  46450. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  46451. }
  46452. return lensFlareSystem;
  46453. };
  46454. LensFlareSystem.prototype.serialize = function () {
  46455. var serializationObject = {};
  46456. serializationObject.id = this.id;
  46457. serializationObject.name = this.name;
  46458. serializationObject.emitterId = this.getEmitter().id;
  46459. serializationObject.borderLimit = this.borderLimit;
  46460. serializationObject.flares = [];
  46461. for (var index = 0; index < this.lensFlares.length; index++) {
  46462. var flare = this.lensFlares[index];
  46463. serializationObject.flares.push({
  46464. size: flare.size,
  46465. position: flare.position,
  46466. color: flare.color.asArray(),
  46467. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  46468. });
  46469. }
  46470. return serializationObject;
  46471. };
  46472. return LensFlareSystem;
  46473. }());
  46474. BABYLON.LensFlareSystem = LensFlareSystem;
  46475. })(BABYLON || (BABYLON = {}));
  46476. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  46477. var BABYLON;
  46478. (function (BABYLON) {
  46479. // We're mainly based on the logic defined into the FreeCamera code
  46480. var DeviceOrientationCamera = (function (_super) {
  46481. __extends(DeviceOrientationCamera, _super);
  46482. function DeviceOrientationCamera(name, position, scene) {
  46483. var _this = _super.call(this, name, position, scene) || this;
  46484. _this._quaternionCache = new BABYLON.Quaternion();
  46485. _this.inputs.addDeviceOrientation();
  46486. return _this;
  46487. }
  46488. DeviceOrientationCamera.prototype.getClassName = function () {
  46489. return "DeviceOrientationCamera";
  46490. };
  46491. DeviceOrientationCamera.prototype._checkInputs = function () {
  46492. _super.prototype._checkInputs.call(this);
  46493. this._quaternionCache.copyFrom(this.rotationQuaternion);
  46494. if (this._initialQuaternion) {
  46495. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  46496. }
  46497. };
  46498. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  46499. var _this = this;
  46500. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  46501. //can only work if this camera has a rotation quaternion already.
  46502. if (!this.rotationQuaternion)
  46503. return;
  46504. if (!this._initialQuaternion) {
  46505. this._initialQuaternion = new BABYLON.Quaternion();
  46506. }
  46507. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  46508. ['x', 'y', 'z'].forEach(function (axisName) {
  46509. if (!axis[axisName]) {
  46510. _this._initialQuaternion[axisName] = 0;
  46511. }
  46512. else {
  46513. _this._initialQuaternion[axisName] *= -1;
  46514. }
  46515. });
  46516. this._initialQuaternion.normalize();
  46517. //force rotation update
  46518. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  46519. };
  46520. return DeviceOrientationCamera;
  46521. }(BABYLON.FreeCamera));
  46522. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  46523. })(BABYLON || (BABYLON = {}));
  46524. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  46525. var BABYLON;
  46526. (function (BABYLON) {
  46527. var VRDeviceOrientationFreeCamera = (function (_super) {
  46528. __extends(VRDeviceOrientationFreeCamera, _super);
  46529. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  46530. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46531. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46532. var _this = _super.call(this, name, position, scene) || this;
  46533. vrCameraMetrics.compensateDistortion = compensateDistortion;
  46534. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  46535. return _this;
  46536. }
  46537. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  46538. return "VRDeviceOrientationFreeCamera";
  46539. };
  46540. return VRDeviceOrientationFreeCamera;
  46541. }(BABYLON.DeviceOrientationCamera));
  46542. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  46543. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  46544. __extends(VRDeviceOrientationArcRotateCamera, _super);
  46545. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  46546. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46547. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46548. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  46549. vrCameraMetrics.compensateDistortion = compensateDistortion;
  46550. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  46551. _this.inputs.addVRDeviceOrientation();
  46552. return _this;
  46553. }
  46554. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  46555. return "VRDeviceOrientationArcRotateCamera";
  46556. };
  46557. return VRDeviceOrientationArcRotateCamera;
  46558. }(BABYLON.ArcRotateCamera));
  46559. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  46560. })(BABYLON || (BABYLON = {}));
  46561. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  46562. var BABYLON;
  46563. (function (BABYLON) {
  46564. // We're mainly based on the logic defined into the FreeCamera code
  46565. var UniversalCamera = (function (_super) {
  46566. __extends(UniversalCamera, _super);
  46567. //-- end properties for backward compatibility for inputs
  46568. function UniversalCamera(name, position, scene) {
  46569. var _this = _super.call(this, name, position, scene) || this;
  46570. _this.inputs.addGamepad();
  46571. return _this;
  46572. }
  46573. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  46574. //-- Begin properties for backward compatibility for inputs
  46575. get: function () {
  46576. var gamepad = this.inputs.attached["gamepad"];
  46577. if (gamepad)
  46578. return gamepad.gamepadAngularSensibility;
  46579. },
  46580. set: function (value) {
  46581. var gamepad = this.inputs.attached["gamepad"];
  46582. if (gamepad)
  46583. gamepad.gamepadAngularSensibility = value;
  46584. },
  46585. enumerable: true,
  46586. configurable: true
  46587. });
  46588. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  46589. get: function () {
  46590. var gamepad = this.inputs.attached["gamepad"];
  46591. if (gamepad)
  46592. return gamepad.gamepadMoveSensibility;
  46593. },
  46594. set: function (value) {
  46595. var gamepad = this.inputs.attached["gamepad"];
  46596. if (gamepad)
  46597. gamepad.gamepadMoveSensibility = value;
  46598. },
  46599. enumerable: true,
  46600. configurable: true
  46601. });
  46602. UniversalCamera.prototype.getClassName = function () {
  46603. return "UniversalCamera";
  46604. };
  46605. return UniversalCamera;
  46606. }(BABYLON.TouchCamera));
  46607. BABYLON.UniversalCamera = UniversalCamera;
  46608. })(BABYLON || (BABYLON = {}));
  46609. //# sourceMappingURL=babylon.universalCamera.js.map
  46610. var BABYLON;
  46611. (function (BABYLON) {
  46612. var Gamepads = (function () {
  46613. function Gamepads(ongamedpadconnected) {
  46614. var _this = this;
  46615. this.babylonGamepads = [];
  46616. this.oneGamepadConnected = false;
  46617. this.isMonitoring = false;
  46618. this.gamepadEventSupported = 'GamepadEvent' in window;
  46619. this.gamepadSupportAvailable = (navigator.getGamepads ||
  46620. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  46621. this._callbackGamepadConnected = ongamedpadconnected;
  46622. if (this.gamepadSupportAvailable) {
  46623. // Checking if the gamepad connected event is supported (like in Firefox)
  46624. if (this.gamepadEventSupported) {
  46625. this._onGamepadConnectedEvent = function (evt) {
  46626. _this._onGamepadConnected(evt);
  46627. };
  46628. this._onGamepadDisonnectedEvent = function (evt) {
  46629. _this._onGamepadDisconnected(evt);
  46630. };
  46631. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  46632. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  46633. }
  46634. else {
  46635. this._startMonitoringGamepads();
  46636. }
  46637. }
  46638. }
  46639. Gamepads.prototype.dispose = function () {
  46640. if (Gamepads.gamepadDOMInfo) {
  46641. document.body.removeChild(Gamepads.gamepadDOMInfo);
  46642. }
  46643. if (this._onGamepadConnectedEvent) {
  46644. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  46645. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  46646. this._onGamepadConnectedEvent = null;
  46647. this._onGamepadDisonnectedEvent = null;
  46648. }
  46649. };
  46650. Gamepads.prototype._onGamepadConnected = function (evt) {
  46651. var newGamepad = this._addNewGamepad(evt.gamepad);
  46652. if (this._callbackGamepadConnected)
  46653. this._callbackGamepadConnected(newGamepad);
  46654. this._startMonitoringGamepads();
  46655. };
  46656. Gamepads.prototype._addNewGamepad = function (gamepad) {
  46657. if (!this.oneGamepadConnected) {
  46658. this.oneGamepadConnected = true;
  46659. if (Gamepads.gamepadDOMInfo) {
  46660. document.body.removeChild(Gamepads.gamepadDOMInfo);
  46661. Gamepads.gamepadDOMInfo = null;
  46662. }
  46663. }
  46664. var newGamepad;
  46665. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  46666. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  46667. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  46668. }
  46669. else {
  46670. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  46671. }
  46672. this.babylonGamepads.push(newGamepad);
  46673. return newGamepad;
  46674. };
  46675. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  46676. // Remove the gamepad from the list of gamepads to monitor.
  46677. for (var i in this.babylonGamepads) {
  46678. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  46679. this.babylonGamepads.splice(+i, 1);
  46680. break;
  46681. }
  46682. }
  46683. // If no gamepads are left, stop the polling loop.
  46684. if (this.babylonGamepads.length == 0) {
  46685. this._stopMonitoringGamepads();
  46686. }
  46687. };
  46688. Gamepads.prototype._startMonitoringGamepads = function () {
  46689. if (!this.isMonitoring) {
  46690. this.isMonitoring = true;
  46691. this._checkGamepadsStatus();
  46692. }
  46693. };
  46694. Gamepads.prototype._stopMonitoringGamepads = function () {
  46695. this.isMonitoring = false;
  46696. };
  46697. Gamepads.prototype._checkGamepadsStatus = function () {
  46698. var _this = this;
  46699. // updating gamepad objects
  46700. this._updateGamepadObjects();
  46701. for (var i in this.babylonGamepads) {
  46702. this.babylonGamepads[i].update();
  46703. }
  46704. if (this.isMonitoring) {
  46705. if (window.requestAnimationFrame) {
  46706. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46707. }
  46708. else if (window.mozRequestAnimationFrame) {
  46709. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46710. }
  46711. else if (window.webkitRequestAnimationFrame) {
  46712. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46713. }
  46714. }
  46715. };
  46716. // This function is called only on Chrome, which does not yet support
  46717. // connection/disconnection events, but requires you to monitor
  46718. // an array for changes.
  46719. Gamepads.prototype._updateGamepadObjects = function () {
  46720. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  46721. for (var i = 0; i < gamepads.length; i++) {
  46722. if (gamepads[i]) {
  46723. if (!(gamepads[i].index in this.babylonGamepads)) {
  46724. var newGamepad = this._addNewGamepad(gamepads[i]);
  46725. if (this._callbackGamepadConnected) {
  46726. this._callbackGamepadConnected(newGamepad);
  46727. }
  46728. }
  46729. else {
  46730. this.babylonGamepads[i].browserGamepad = gamepads[i];
  46731. }
  46732. }
  46733. }
  46734. };
  46735. return Gamepads;
  46736. }());
  46737. BABYLON.Gamepads = Gamepads;
  46738. var StickValues = (function () {
  46739. function StickValues(x, y) {
  46740. this.x = x;
  46741. this.y = y;
  46742. }
  46743. return StickValues;
  46744. }());
  46745. BABYLON.StickValues = StickValues;
  46746. var Gamepad = (function () {
  46747. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  46748. if (leftStickX === void 0) { leftStickX = 0; }
  46749. if (leftStickY === void 0) { leftStickY = 1; }
  46750. if (rightStickX === void 0) { rightStickX = 2; }
  46751. if (rightStickY === void 0) { rightStickY = 3; }
  46752. this.id = id;
  46753. this.index = index;
  46754. this.browserGamepad = browserGamepad;
  46755. this._leftStickAxisX = leftStickX;
  46756. this._leftStickAxisY = leftStickY;
  46757. this._rightStickAxisX = rightStickX;
  46758. this._rightStickAxisY = rightStickY;
  46759. if (this.browserGamepad.axes.length >= 2) {
  46760. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  46761. }
  46762. if (this.browserGamepad.axes.length >= 4) {
  46763. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  46764. }
  46765. }
  46766. Gamepad.prototype.onleftstickchanged = function (callback) {
  46767. this._onleftstickchanged = callback;
  46768. };
  46769. Gamepad.prototype.onrightstickchanged = function (callback) {
  46770. this._onrightstickchanged = callback;
  46771. };
  46772. Object.defineProperty(Gamepad.prototype, "leftStick", {
  46773. get: function () {
  46774. return this._leftStick;
  46775. },
  46776. set: function (newValues) {
  46777. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  46778. this._onleftstickchanged(newValues);
  46779. }
  46780. this._leftStick = newValues;
  46781. },
  46782. enumerable: true,
  46783. configurable: true
  46784. });
  46785. Object.defineProperty(Gamepad.prototype, "rightStick", {
  46786. get: function () {
  46787. return this._rightStick;
  46788. },
  46789. set: function (newValues) {
  46790. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  46791. this._onrightstickchanged(newValues);
  46792. }
  46793. this._rightStick = newValues;
  46794. },
  46795. enumerable: true,
  46796. configurable: true
  46797. });
  46798. Gamepad.prototype.update = function () {
  46799. if (this._leftStick) {
  46800. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  46801. }
  46802. if (this._rightStick) {
  46803. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  46804. }
  46805. };
  46806. return Gamepad;
  46807. }());
  46808. BABYLON.Gamepad = Gamepad;
  46809. var GenericPad = (function (_super) {
  46810. __extends(GenericPad, _super);
  46811. function GenericPad(id, index, gamepad) {
  46812. var _this = _super.call(this, id, index, gamepad) || this;
  46813. _this.id = id;
  46814. _this.index = index;
  46815. _this.gamepad = gamepad;
  46816. _this._buttons = new Array(gamepad.buttons.length);
  46817. return _this;
  46818. }
  46819. GenericPad.prototype.onbuttondown = function (callback) {
  46820. this._onbuttondown = callback;
  46821. };
  46822. GenericPad.prototype.onbuttonup = function (callback) {
  46823. this._onbuttonup = callback;
  46824. };
  46825. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  46826. if (newValue !== currentValue) {
  46827. if (this._onbuttondown && newValue === 1) {
  46828. this._onbuttondown(buttonIndex);
  46829. }
  46830. if (this._onbuttonup && newValue === 0) {
  46831. this._onbuttonup(buttonIndex);
  46832. }
  46833. }
  46834. return newValue;
  46835. };
  46836. GenericPad.prototype.update = function () {
  46837. _super.prototype.update.call(this);
  46838. for (var index = 0; index < this._buttons.length; index++) {
  46839. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  46840. }
  46841. };
  46842. return GenericPad;
  46843. }(Gamepad));
  46844. BABYLON.GenericPad = GenericPad;
  46845. var Xbox360Button;
  46846. (function (Xbox360Button) {
  46847. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  46848. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  46849. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  46850. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  46851. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  46852. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  46853. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  46854. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  46855. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  46856. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  46857. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  46858. var Xbox360Dpad;
  46859. (function (Xbox360Dpad) {
  46860. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  46861. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  46862. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  46863. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  46864. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  46865. var Xbox360Pad = (function (_super) {
  46866. __extends(Xbox360Pad, _super);
  46867. function Xbox360Pad(id, index, gamepad, xboxOne) {
  46868. if (xboxOne === void 0) { xboxOne = false; }
  46869. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  46870. _this._leftTrigger = 0;
  46871. _this._rightTrigger = 0;
  46872. _this._buttonA = 0;
  46873. _this._buttonB = 0;
  46874. _this._buttonX = 0;
  46875. _this._buttonY = 0;
  46876. _this._buttonBack = 0;
  46877. _this._buttonStart = 0;
  46878. _this._buttonLB = 0;
  46879. _this._buttonRB = 0;
  46880. _this._buttonLeftStick = 0;
  46881. _this._buttonRightStick = 0;
  46882. _this._dPadUp = 0;
  46883. _this._dPadDown = 0;
  46884. _this._dPadLeft = 0;
  46885. _this._dPadRight = 0;
  46886. _this._isXboxOnePad = false;
  46887. _this._isXboxOnePad = xboxOne;
  46888. return _this;
  46889. }
  46890. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  46891. this._onlefttriggerchanged = callback;
  46892. };
  46893. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  46894. this._onrighttriggerchanged = callback;
  46895. };
  46896. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  46897. get: function () {
  46898. return this._leftTrigger;
  46899. },
  46900. set: function (newValue) {
  46901. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  46902. this._onlefttriggerchanged(newValue);
  46903. }
  46904. this._leftTrigger = newValue;
  46905. },
  46906. enumerable: true,
  46907. configurable: true
  46908. });
  46909. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  46910. get: function () {
  46911. return this._rightTrigger;
  46912. },
  46913. set: function (newValue) {
  46914. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  46915. this._onrighttriggerchanged(newValue);
  46916. }
  46917. this._rightTrigger = newValue;
  46918. },
  46919. enumerable: true,
  46920. configurable: true
  46921. });
  46922. Xbox360Pad.prototype.onbuttondown = function (callback) {
  46923. this._onbuttondown = callback;
  46924. };
  46925. Xbox360Pad.prototype.onbuttonup = function (callback) {
  46926. this._onbuttonup = callback;
  46927. };
  46928. Xbox360Pad.prototype.ondpaddown = function (callback) {
  46929. this._ondpaddown = callback;
  46930. };
  46931. Xbox360Pad.prototype.ondpadup = function (callback) {
  46932. this._ondpadup = callback;
  46933. };
  46934. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  46935. if (newValue !== currentValue) {
  46936. if (this._onbuttondown && newValue === 1) {
  46937. this._onbuttondown(buttonType);
  46938. }
  46939. if (this._onbuttonup && newValue === 0) {
  46940. this._onbuttonup(buttonType);
  46941. }
  46942. }
  46943. return newValue;
  46944. };
  46945. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  46946. if (newValue !== currentValue) {
  46947. if (this._ondpaddown && newValue === 1) {
  46948. this._ondpaddown(buttonType);
  46949. }
  46950. if (this._ondpadup && newValue === 0) {
  46951. this._ondpadup(buttonType);
  46952. }
  46953. }
  46954. return newValue;
  46955. };
  46956. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  46957. get: function () {
  46958. return this._buttonA;
  46959. },
  46960. set: function (value) {
  46961. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  46962. },
  46963. enumerable: true,
  46964. configurable: true
  46965. });
  46966. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  46967. get: function () {
  46968. return this._buttonB;
  46969. },
  46970. set: function (value) {
  46971. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  46972. },
  46973. enumerable: true,
  46974. configurable: true
  46975. });
  46976. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  46977. get: function () {
  46978. return this._buttonX;
  46979. },
  46980. set: function (value) {
  46981. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  46982. },
  46983. enumerable: true,
  46984. configurable: true
  46985. });
  46986. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  46987. get: function () {
  46988. return this._buttonY;
  46989. },
  46990. set: function (value) {
  46991. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  46992. },
  46993. enumerable: true,
  46994. configurable: true
  46995. });
  46996. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  46997. get: function () {
  46998. return this._buttonStart;
  46999. },
  47000. set: function (value) {
  47001. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  47002. },
  47003. enumerable: true,
  47004. configurable: true
  47005. });
  47006. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  47007. get: function () {
  47008. return this._buttonBack;
  47009. },
  47010. set: function (value) {
  47011. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  47012. },
  47013. enumerable: true,
  47014. configurable: true
  47015. });
  47016. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  47017. get: function () {
  47018. return this._buttonLB;
  47019. },
  47020. set: function (value) {
  47021. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  47022. },
  47023. enumerable: true,
  47024. configurable: true
  47025. });
  47026. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  47027. get: function () {
  47028. return this._buttonRB;
  47029. },
  47030. set: function (value) {
  47031. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  47032. },
  47033. enumerable: true,
  47034. configurable: true
  47035. });
  47036. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  47037. get: function () {
  47038. return this._buttonLeftStick;
  47039. },
  47040. set: function (value) {
  47041. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  47042. },
  47043. enumerable: true,
  47044. configurable: true
  47045. });
  47046. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  47047. get: function () {
  47048. return this._buttonRightStick;
  47049. },
  47050. set: function (value) {
  47051. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  47052. },
  47053. enumerable: true,
  47054. configurable: true
  47055. });
  47056. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  47057. get: function () {
  47058. return this._dPadUp;
  47059. },
  47060. set: function (value) {
  47061. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  47062. },
  47063. enumerable: true,
  47064. configurable: true
  47065. });
  47066. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  47067. get: function () {
  47068. return this._dPadDown;
  47069. },
  47070. set: function (value) {
  47071. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  47072. },
  47073. enumerable: true,
  47074. configurable: true
  47075. });
  47076. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  47077. get: function () {
  47078. return this._dPadLeft;
  47079. },
  47080. set: function (value) {
  47081. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  47082. },
  47083. enumerable: true,
  47084. configurable: true
  47085. });
  47086. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  47087. get: function () {
  47088. return this._dPadRight;
  47089. },
  47090. set: function (value) {
  47091. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  47092. },
  47093. enumerable: true,
  47094. configurable: true
  47095. });
  47096. Xbox360Pad.prototype.update = function () {
  47097. _super.prototype.update.call(this);
  47098. if (this._isXboxOnePad) {
  47099. this.buttonA = this.browserGamepad.buttons[0].value;
  47100. this.buttonB = this.browserGamepad.buttons[1].value;
  47101. this.buttonX = this.browserGamepad.buttons[2].value;
  47102. this.buttonY = this.browserGamepad.buttons[3].value;
  47103. this.buttonLB = this.browserGamepad.buttons[4].value;
  47104. this.buttonRB = this.browserGamepad.buttons[5].value;
  47105. this.leftTrigger = this.browserGamepad.axes[2];
  47106. this.rightTrigger = this.browserGamepad.axes[5];
  47107. this.buttonBack = this.browserGamepad.buttons[9].value;
  47108. this.buttonStart = this.browserGamepad.buttons[8].value;
  47109. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  47110. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  47111. this.dPadUp = this.browserGamepad.buttons[11].value;
  47112. this.dPadDown = this.browserGamepad.buttons[12].value;
  47113. this.dPadLeft = this.browserGamepad.buttons[13].value;
  47114. this.dPadRight = this.browserGamepad.buttons[14].value;
  47115. }
  47116. else {
  47117. this.buttonA = this.browserGamepad.buttons[0].value;
  47118. this.buttonB = this.browserGamepad.buttons[1].value;
  47119. this.buttonX = this.browserGamepad.buttons[2].value;
  47120. this.buttonY = this.browserGamepad.buttons[3].value;
  47121. this.buttonLB = this.browserGamepad.buttons[4].value;
  47122. this.buttonRB = this.browserGamepad.buttons[5].value;
  47123. this.leftTrigger = this.browserGamepad.buttons[6].value;
  47124. this.rightTrigger = this.browserGamepad.buttons[7].value;
  47125. this.buttonBack = this.browserGamepad.buttons[8].value;
  47126. this.buttonStart = this.browserGamepad.buttons[9].value;
  47127. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  47128. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  47129. this.dPadUp = this.browserGamepad.buttons[12].value;
  47130. this.dPadDown = this.browserGamepad.buttons[13].value;
  47131. this.dPadLeft = this.browserGamepad.buttons[14].value;
  47132. this.dPadRight = this.browserGamepad.buttons[15].value;
  47133. }
  47134. };
  47135. return Xbox360Pad;
  47136. }(Gamepad));
  47137. BABYLON.Xbox360Pad = Xbox360Pad;
  47138. })(BABYLON || (BABYLON = {}));
  47139. //# sourceMappingURL=babylon.gamepads.js.map
  47140. var BABYLON;
  47141. (function (BABYLON) {
  47142. // We're mainly based on the logic defined into the FreeCamera code
  47143. var GamepadCamera = (function (_super) {
  47144. __extends(GamepadCamera, _super);
  47145. //-- end properties for backward compatibility for inputs
  47146. function GamepadCamera(name, position, scene) {
  47147. var _this;
  47148. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  47149. _this = _super.call(this, name, position, scene) || this;
  47150. return _this;
  47151. }
  47152. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  47153. //-- Begin properties for backward compatibility for inputs
  47154. get: function () {
  47155. var gamepad = this.inputs.attached["gamepad"];
  47156. if (gamepad)
  47157. return gamepad.gamepadAngularSensibility;
  47158. },
  47159. set: function (value) {
  47160. var gamepad = this.inputs.attached["gamepad"];
  47161. if (gamepad)
  47162. gamepad.gamepadAngularSensibility = value;
  47163. },
  47164. enumerable: true,
  47165. configurable: true
  47166. });
  47167. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  47168. get: function () {
  47169. var gamepad = this.inputs.attached["gamepad"];
  47170. if (gamepad)
  47171. return gamepad.gamepadMoveSensibility;
  47172. },
  47173. set: function (value) {
  47174. var gamepad = this.inputs.attached["gamepad"];
  47175. if (gamepad)
  47176. gamepad.gamepadMoveSensibility = value;
  47177. },
  47178. enumerable: true,
  47179. configurable: true
  47180. });
  47181. GamepadCamera.prototype.getClassName = function () {
  47182. return "GamepadCamera";
  47183. };
  47184. return GamepadCamera;
  47185. }(BABYLON.UniversalCamera));
  47186. BABYLON.GamepadCamera = GamepadCamera;
  47187. })(BABYLON || (BABYLON = {}));
  47188. //# sourceMappingURL=babylon.gamepadCamera.js.map
  47189. var BABYLON;
  47190. (function (BABYLON) {
  47191. var Analyser = (function () {
  47192. function Analyser(scene) {
  47193. this.SMOOTHING = 0.75;
  47194. this.FFT_SIZE = 512;
  47195. this.BARGRAPHAMPLITUDE = 256;
  47196. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  47197. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  47198. this._scene = scene;
  47199. this._audioEngine = BABYLON.Engine.audioEngine;
  47200. if (this._audioEngine.canUseWebAudio) {
  47201. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  47202. this._webAudioAnalyser.minDecibels = -140;
  47203. this._webAudioAnalyser.maxDecibels = 0;
  47204. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  47205. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  47206. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  47207. }
  47208. }
  47209. Analyser.prototype.getFrequencyBinCount = function () {
  47210. if (this._audioEngine.canUseWebAudio) {
  47211. return this._webAudioAnalyser.frequencyBinCount;
  47212. }
  47213. else {
  47214. return 0;
  47215. }
  47216. };
  47217. Analyser.prototype.getByteFrequencyData = function () {
  47218. if (this._audioEngine.canUseWebAudio) {
  47219. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47220. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47221. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  47222. }
  47223. return this._byteFreqs;
  47224. };
  47225. Analyser.prototype.getByteTimeDomainData = function () {
  47226. if (this._audioEngine.canUseWebAudio) {
  47227. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47228. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47229. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  47230. }
  47231. return this._byteTime;
  47232. };
  47233. Analyser.prototype.getFloatFrequencyData = function () {
  47234. if (this._audioEngine.canUseWebAudio) {
  47235. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47236. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47237. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  47238. }
  47239. return this._floatFreqs;
  47240. };
  47241. Analyser.prototype.drawDebugCanvas = function () {
  47242. var _this = this;
  47243. if (this._audioEngine.canUseWebAudio) {
  47244. if (!this._debugCanvas) {
  47245. this._debugCanvas = document.createElement("canvas");
  47246. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  47247. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  47248. this._debugCanvas.style.position = "absolute";
  47249. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  47250. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  47251. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  47252. document.body.appendChild(this._debugCanvas);
  47253. this._registerFunc = function () {
  47254. _this.drawDebugCanvas();
  47255. };
  47256. this._scene.registerBeforeRender(this._registerFunc);
  47257. }
  47258. if (this._registerFunc) {
  47259. var workingArray = this.getByteFrequencyData();
  47260. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  47261. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  47262. // Draw the frequency domain chart.
  47263. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  47264. var value = workingArray[i];
  47265. var percent = value / this.BARGRAPHAMPLITUDE;
  47266. var height = this.DEBUGCANVASSIZE.height * percent;
  47267. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  47268. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  47269. var hue = i / this.getFrequencyBinCount() * 360;
  47270. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  47271. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  47272. }
  47273. }
  47274. }
  47275. };
  47276. Analyser.prototype.stopDebugCanvas = function () {
  47277. if (this._debugCanvas) {
  47278. this._scene.unregisterBeforeRender(this._registerFunc);
  47279. this._registerFunc = null;
  47280. document.body.removeChild(this._debugCanvas);
  47281. this._debugCanvas = null;
  47282. this._debugCanvasContext = null;
  47283. }
  47284. };
  47285. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  47286. if (this._audioEngine.canUseWebAudio) {
  47287. inputAudioNode.connect(this._webAudioAnalyser);
  47288. this._webAudioAnalyser.connect(outputAudioNode);
  47289. }
  47290. };
  47291. Analyser.prototype.dispose = function () {
  47292. if (this._audioEngine.canUseWebAudio) {
  47293. this._webAudioAnalyser.disconnect();
  47294. }
  47295. };
  47296. return Analyser;
  47297. }());
  47298. BABYLON.Analyser = Analyser;
  47299. })(BABYLON || (BABYLON = {}));
  47300. //# sourceMappingURL=babylon.analyser.js.map
  47301. var BABYLON;
  47302. (function (BABYLON) {
  47303. var DepthRenderer = (function () {
  47304. function DepthRenderer(scene, type) {
  47305. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  47306. var _this = this;
  47307. this._viewMatrix = BABYLON.Matrix.Zero();
  47308. this._projectionMatrix = BABYLON.Matrix.Zero();
  47309. this._transformMatrix = BABYLON.Matrix.Zero();
  47310. this._worldViewProjection = BABYLON.Matrix.Zero();
  47311. this._scene = scene;
  47312. var engine = scene.getEngine();
  47313. // Render target
  47314. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  47315. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47316. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47317. this._depthMap.refreshRate = 1;
  47318. this._depthMap.renderParticles = false;
  47319. this._depthMap.renderList = null;
  47320. // set default depth value to 1.0 (far away)
  47321. this._depthMap.onClearObservable.add(function (engine) {
  47322. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  47323. });
  47324. // Custom render function
  47325. var renderSubMesh = function (subMesh) {
  47326. var mesh = subMesh.getRenderingMesh();
  47327. var scene = _this._scene;
  47328. var engine = scene.getEngine();
  47329. // Culling
  47330. engine.setState(subMesh.getMaterial().backFaceCulling);
  47331. // Managing instances
  47332. var batch = mesh._getInstancesRenderList(subMesh._id);
  47333. if (batch.mustReturn) {
  47334. return;
  47335. }
  47336. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  47337. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  47338. engine.enableEffect(_this._effect);
  47339. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  47340. var material = subMesh.getMaterial();
  47341. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  47342. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  47343. // Alpha test
  47344. if (material && material.needAlphaTesting()) {
  47345. var alphaTexture = material.getAlphaTestTexture();
  47346. _this._effect.setTexture("diffuseSampler", alphaTexture);
  47347. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47348. }
  47349. // Bones
  47350. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47351. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47352. }
  47353. // Draw
  47354. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  47355. }
  47356. };
  47357. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  47358. var index;
  47359. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47360. renderSubMesh(opaqueSubMeshes.data[index]);
  47361. }
  47362. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47363. renderSubMesh(alphaTestSubMeshes.data[index]);
  47364. }
  47365. };
  47366. }
  47367. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  47368. var material = subMesh.getMaterial();
  47369. if (material.disableDepthWrite) {
  47370. return false;
  47371. }
  47372. var defines = [];
  47373. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47374. var mesh = subMesh.getMesh();
  47375. var scene = mesh.getScene();
  47376. // Alpha test
  47377. if (material && material.needAlphaTesting()) {
  47378. defines.push("#define ALPHATEST");
  47379. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47380. attribs.push(BABYLON.VertexBuffer.UVKind);
  47381. defines.push("#define UV1");
  47382. }
  47383. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47384. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47385. defines.push("#define UV2");
  47386. }
  47387. }
  47388. // Bones
  47389. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47390. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47391. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47392. if (mesh.numBoneInfluencers > 4) {
  47393. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47394. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47395. }
  47396. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47397. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47398. }
  47399. else {
  47400. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47401. }
  47402. // Instances
  47403. if (useInstances) {
  47404. defines.push("#define INSTANCES");
  47405. attribs.push("world0");
  47406. attribs.push("world1");
  47407. attribs.push("world2");
  47408. attribs.push("world3");
  47409. }
  47410. // Get correct effect
  47411. var join = defines.join("\n");
  47412. if (this._cachedDefines !== join) {
  47413. this._cachedDefines = join;
  47414. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  47415. }
  47416. return this._effect.isReady();
  47417. };
  47418. DepthRenderer.prototype.getDepthMap = function () {
  47419. return this._depthMap;
  47420. };
  47421. // Methods
  47422. DepthRenderer.prototype.dispose = function () {
  47423. this._depthMap.dispose();
  47424. };
  47425. return DepthRenderer;
  47426. }());
  47427. BABYLON.DepthRenderer = DepthRenderer;
  47428. })(BABYLON || (BABYLON = {}));
  47429. //# sourceMappingURL=babylon.depthRenderer.js.map
  47430. var BABYLON;
  47431. (function (BABYLON) {
  47432. var SSAORenderingPipeline = (function (_super) {
  47433. __extends(SSAORenderingPipeline, _super);
  47434. /**
  47435. * @constructor
  47436. * @param {string} name - The rendering pipeline name
  47437. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47438. * @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 }
  47439. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47440. */
  47441. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  47442. var _this = _super.call(this, scene.getEngine(), name) || this;
  47443. // Members
  47444. /**
  47445. * The PassPostProcess id in the pipeline that contains the original scene color
  47446. * @type {string}
  47447. */
  47448. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  47449. /**
  47450. * The SSAO PostProcess id in the pipeline
  47451. * @type {string}
  47452. */
  47453. _this.SSAORenderEffect = "SSAORenderEffect";
  47454. /**
  47455. * The horizontal blur PostProcess id in the pipeline
  47456. * @type {string}
  47457. */
  47458. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  47459. /**
  47460. * The vertical blur PostProcess id in the pipeline
  47461. * @type {string}
  47462. */
  47463. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  47464. /**
  47465. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  47466. * @type {string}
  47467. */
  47468. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  47469. /**
  47470. * The output strength of the SSAO post-process. Default value is 1.0.
  47471. * @type {number}
  47472. */
  47473. _this.totalStrength = 1.0;
  47474. /**
  47475. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  47476. * @type {number}
  47477. */
  47478. _this.radius = 0.0001;
  47479. /**
  47480. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  47481. * Must not be equal to fallOff and superior to fallOff.
  47482. * Default value is 0.975
  47483. * @type {number}
  47484. */
  47485. _this.area = 0.0075;
  47486. /**
  47487. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  47488. * Must not be equal to area and inferior to area.
  47489. * Default value is 0.0
  47490. * @type {number}
  47491. */
  47492. _this.fallOff = 0.000001;
  47493. /**
  47494. * The base color of the SSAO post-process
  47495. * The final result is "base + ssao" between [0, 1]
  47496. * @type {number}
  47497. */
  47498. _this.base = 0.5;
  47499. _this._firstUpdate = true;
  47500. _this._scene = scene;
  47501. // Set up assets
  47502. _this._createRandomTexture();
  47503. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47504. var ssaoRatio = ratio.ssaoRatio || ratio;
  47505. var combineRatio = ratio.combineRatio || ratio;
  47506. _this._ratio = {
  47507. ssaoRatio: ssaoRatio,
  47508. combineRatio: combineRatio
  47509. };
  47510. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  47511. _this._createSSAOPostProcess(ssaoRatio);
  47512. _this._createBlurPostProcess(ssaoRatio);
  47513. _this._createSSAOCombinePostProcess(combineRatio);
  47514. // Set up pipeline
  47515. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  47516. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  47517. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  47518. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  47519. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  47520. // Finish
  47521. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47522. if (cameras)
  47523. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47524. return _this;
  47525. }
  47526. // Public Methods
  47527. /**
  47528. * Returns the horizontal blur PostProcess
  47529. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  47530. */
  47531. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  47532. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  47533. return null;
  47534. };
  47535. /**
  47536. * Returns the vertical blur PostProcess
  47537. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  47538. */
  47539. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  47540. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  47541. return null;
  47542. };
  47543. /**
  47544. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  47545. */
  47546. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47547. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47548. for (var i = 0; i < this._scene.cameras.length; i++) {
  47549. var camera = this._scene.cameras[i];
  47550. this._originalColorPostProcess.dispose(camera);
  47551. this._ssaoPostProcess.dispose(camera);
  47552. this._blurHPostProcess.dispose(camera);
  47553. this._blurVPostProcess.dispose(camera);
  47554. this._ssaoCombinePostProcess.dispose(camera);
  47555. }
  47556. this._randomTexture.dispose();
  47557. if (disableDepthRender)
  47558. this._scene.disableDepthRenderer();
  47559. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47560. };
  47561. // Private Methods
  47562. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  47563. var _this = this;
  47564. /*
  47565. var samplerOffsets = [
  47566. -8.0, -6.0, -4.0, -2.0,
  47567. 0.0,
  47568. 2.0, 4.0, 6.0, 8.0
  47569. ];
  47570. */
  47571. var samples = 16;
  47572. var samplerOffsets = [];
  47573. for (var i = -8; i < 8; i++) {
  47574. samplerOffsets.push(i * 2);
  47575. }
  47576. 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");
  47577. this._blurHPostProcess.onApply = function (effect) {
  47578. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  47579. effect.setTexture("depthSampler", _this._depthTexture);
  47580. if (_this._firstUpdate) {
  47581. effect.setArray("samplerOffsets", samplerOffsets);
  47582. }
  47583. };
  47584. 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");
  47585. this._blurVPostProcess.onApply = function (effect) {
  47586. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  47587. effect.setTexture("depthSampler", _this._depthTexture);
  47588. if (_this._firstUpdate) {
  47589. effect.setArray("samplerOffsets", samplerOffsets);
  47590. _this._firstUpdate = false;
  47591. }
  47592. };
  47593. };
  47594. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  47595. var _this = this;
  47596. var numSamples = 16;
  47597. var sampleSphere = [
  47598. 0.5381, 0.1856, -0.4319,
  47599. 0.1379, 0.2486, 0.4430,
  47600. 0.3371, 0.5679, -0.0057,
  47601. -0.6999, -0.0451, -0.0019,
  47602. 0.0689, -0.1598, -0.8547,
  47603. 0.0560, 0.0069, -0.1843,
  47604. -0.0146, 0.1402, 0.0762,
  47605. 0.0100, -0.1924, -0.0344,
  47606. -0.3577, -0.5301, -0.4358,
  47607. -0.3169, 0.1063, 0.0158,
  47608. 0.0103, -0.5869, 0.0046,
  47609. -0.0897, -0.4940, 0.3287,
  47610. 0.7119, -0.0154, -0.0918,
  47611. -0.0533, 0.0596, -0.5411,
  47612. 0.0352, -0.0631, 0.5460,
  47613. -0.4776, 0.2847, -0.0271
  47614. ];
  47615. var samplesFactor = 1.0 / numSamples;
  47616. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  47617. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  47618. "area", "fallOff", "base", "range", "viewport"
  47619. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  47620. var viewport = new BABYLON.Vector2(0, 0);
  47621. this._ssaoPostProcess.onApply = function (effect) {
  47622. if (_this._firstUpdate) {
  47623. effect.setArray3("sampleSphere", sampleSphere);
  47624. effect.setFloat("samplesFactor", samplesFactor);
  47625. effect.setFloat("randTextureTiles", 4.0);
  47626. }
  47627. effect.setFloat("totalStrength", _this.totalStrength);
  47628. effect.setFloat("radius", _this.radius);
  47629. effect.setFloat("area", _this.area);
  47630. effect.setFloat("fallOff", _this.fallOff);
  47631. effect.setFloat("base", _this.base);
  47632. effect.setTexture("textureSampler", _this._depthTexture);
  47633. effect.setTexture("randomSampler", _this._randomTexture);
  47634. };
  47635. };
  47636. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  47637. var _this = this;
  47638. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47639. this._ssaoCombinePostProcess.onApply = function (effect) {
  47640. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  47641. };
  47642. };
  47643. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  47644. var size = 512;
  47645. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  47646. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47647. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47648. var context = this._randomTexture.getContext();
  47649. var rand = function (min, max) {
  47650. return Math.random() * (max - min) + min;
  47651. };
  47652. var randVector = BABYLON.Vector3.Zero();
  47653. for (var x = 0; x < size; x++) {
  47654. for (var y = 0; y < size; y++) {
  47655. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  47656. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  47657. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  47658. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  47659. context.fillRect(x, y, 1, 1);
  47660. }
  47661. }
  47662. this._randomTexture.update(false);
  47663. };
  47664. return SSAORenderingPipeline;
  47665. }(BABYLON.PostProcessRenderPipeline));
  47666. __decorate([
  47667. BABYLON.serialize()
  47668. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  47669. __decorate([
  47670. BABYLON.serialize()
  47671. ], SSAORenderingPipeline.prototype, "radius", void 0);
  47672. __decorate([
  47673. BABYLON.serialize()
  47674. ], SSAORenderingPipeline.prototype, "area", void 0);
  47675. __decorate([
  47676. BABYLON.serialize()
  47677. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  47678. __decorate([
  47679. BABYLON.serialize()
  47680. ], SSAORenderingPipeline.prototype, "base", void 0);
  47681. __decorate([
  47682. BABYLON.serialize()
  47683. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  47684. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  47685. })(BABYLON || (BABYLON = {}));
  47686. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  47687. var BABYLON;
  47688. (function (BABYLON) {
  47689. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  47690. var VolumetricLightScatteringPostProcess = (function (_super) {
  47691. __extends(VolumetricLightScatteringPostProcess, _super);
  47692. /**
  47693. * @constructor
  47694. * @param {string} name - The post-process name
  47695. * @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)
  47696. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  47697. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  47698. * @param {number} samples - The post-process quality, default 100
  47699. * @param {number} samplingMode - The post-process filtering mode
  47700. * @param {BABYLON.Engine} engine - The babylon engine
  47701. * @param {boolean} reusable - If the post-process is reusable
  47702. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  47703. */
  47704. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  47705. if (samples === void 0) { samples = 100; }
  47706. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  47707. 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;
  47708. _this._screenCoordinates = BABYLON.Vector2.Zero();
  47709. /**
  47710. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  47711. * @type {Vector3}
  47712. */
  47713. _this.customMeshPosition = BABYLON.Vector3.Zero();
  47714. /**
  47715. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  47716. * @type {boolean}
  47717. */
  47718. _this.useCustomMeshPosition = false;
  47719. /**
  47720. * If the post-process should inverse the light scattering direction
  47721. * @type {boolean}
  47722. */
  47723. _this.invert = true;
  47724. /**
  47725. * Array containing the excluded meshes not rendered in the internal pass
  47726. */
  47727. _this.excludedMeshes = new Array();
  47728. /**
  47729. * Controls the overall intensity of the post-process
  47730. * @type {number}
  47731. */
  47732. _this.exposure = 0.3;
  47733. /**
  47734. * Dissipates each sample's contribution in range [0, 1]
  47735. * @type {number}
  47736. */
  47737. _this.decay = 0.96815;
  47738. /**
  47739. * Controls the overall intensity of each sample
  47740. * @type {number}
  47741. */
  47742. _this.weight = 0.58767;
  47743. /**
  47744. * Controls the density of each sample
  47745. * @type {number}
  47746. */
  47747. _this.density = 0.926;
  47748. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  47749. var engine = scene.getEngine();
  47750. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  47751. // Configure mesh
  47752. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  47753. // Configure
  47754. _this._createPass(scene, ratio.passRatio || ratio);
  47755. _this.onActivate = function (camera) {
  47756. if (!_this.isSupported) {
  47757. _this.dispose(camera);
  47758. }
  47759. _this.onActivate = null;
  47760. };
  47761. _this.onApplyObservable.add(function (effect) {
  47762. _this._updateMeshScreenCoordinates(scene);
  47763. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  47764. effect.setFloat("exposure", _this.exposure);
  47765. effect.setFloat("decay", _this.decay);
  47766. effect.setFloat("weight", _this.weight);
  47767. effect.setFloat("density", _this.density);
  47768. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  47769. });
  47770. return _this;
  47771. }
  47772. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  47773. get: function () {
  47774. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  47775. return false;
  47776. },
  47777. set: function (useDiffuseColor) {
  47778. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  47779. },
  47780. enumerable: true,
  47781. configurable: true
  47782. });
  47783. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  47784. var mesh = subMesh.getMesh();
  47785. // Render this.mesh as default
  47786. if (mesh === this.mesh) {
  47787. return mesh.material.isReady(mesh);
  47788. }
  47789. var defines = [];
  47790. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47791. var material = subMesh.getMaterial();
  47792. var needUV = false;
  47793. // Alpha test
  47794. if (material) {
  47795. if (material.needAlphaTesting()) {
  47796. defines.push("#define ALPHATEST");
  47797. }
  47798. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47799. attribs.push(BABYLON.VertexBuffer.UVKind);
  47800. defines.push("#define UV1");
  47801. }
  47802. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47803. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47804. defines.push("#define UV2");
  47805. }
  47806. }
  47807. // Bones
  47808. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47809. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47810. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47811. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47812. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47813. }
  47814. else {
  47815. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47816. }
  47817. // Instances
  47818. if (useInstances) {
  47819. defines.push("#define INSTANCES");
  47820. attribs.push("world0");
  47821. attribs.push("world1");
  47822. attribs.push("world2");
  47823. attribs.push("world3");
  47824. }
  47825. // Get correct effect
  47826. var join = defines.join("\n");
  47827. if (this._cachedDefines !== join) {
  47828. this._cachedDefines = join;
  47829. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  47830. }
  47831. return this._volumetricLightScatteringPass.isReady();
  47832. };
  47833. /**
  47834. * Sets the new light position for light scattering effect
  47835. * @param {BABYLON.Vector3} The new custom light position
  47836. */
  47837. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  47838. this.customMeshPosition = position;
  47839. };
  47840. /**
  47841. * Returns the light position for light scattering effect
  47842. * @return {BABYLON.Vector3} The custom light position
  47843. */
  47844. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  47845. return this.customMeshPosition;
  47846. };
  47847. /**
  47848. * Disposes the internal assets and detaches the post-process from the camera
  47849. */
  47850. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  47851. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  47852. if (rttIndex !== -1) {
  47853. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  47854. }
  47855. this._volumetricLightScatteringRTT.dispose();
  47856. _super.prototype.dispose.call(this, camera);
  47857. };
  47858. /**
  47859. * Returns the render target texture used by the post-process
  47860. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  47861. */
  47862. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  47863. return this._volumetricLightScatteringRTT;
  47864. };
  47865. // Private methods
  47866. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  47867. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  47868. return true;
  47869. }
  47870. return false;
  47871. };
  47872. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  47873. var _this = this;
  47874. var engine = scene.getEngine();
  47875. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  47876. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47877. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47878. this._volumetricLightScatteringRTT.renderList = null;
  47879. this._volumetricLightScatteringRTT.renderParticles = false;
  47880. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  47881. // Custom render function for submeshes
  47882. var renderSubMesh = function (subMesh) {
  47883. var mesh = subMesh.getRenderingMesh();
  47884. if (_this._meshExcluded(mesh)) {
  47885. return;
  47886. }
  47887. var scene = mesh.getScene();
  47888. var engine = scene.getEngine();
  47889. // Culling
  47890. engine.setState(subMesh.getMaterial().backFaceCulling);
  47891. // Managing instances
  47892. var batch = mesh._getInstancesRenderList(subMesh._id);
  47893. if (batch.mustReturn) {
  47894. return;
  47895. }
  47896. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  47897. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  47898. var effect = _this._volumetricLightScatteringPass;
  47899. if (mesh === _this.mesh) {
  47900. effect = subMesh.getMaterial().getEffect();
  47901. }
  47902. engine.enableEffect(effect);
  47903. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  47904. if (mesh === _this.mesh) {
  47905. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  47906. }
  47907. else {
  47908. var material = subMesh.getMaterial();
  47909. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  47910. // Alpha test
  47911. if (material && material.needAlphaTesting()) {
  47912. var alphaTexture = material.getAlphaTestTexture();
  47913. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  47914. if (alphaTexture) {
  47915. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47916. }
  47917. }
  47918. // Bones
  47919. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47920. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47921. }
  47922. }
  47923. // Draw
  47924. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  47925. }
  47926. };
  47927. // Render target texture callbacks
  47928. var savedSceneClearColor;
  47929. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  47930. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  47931. savedSceneClearColor = scene.clearColor;
  47932. scene.clearColor = sceneClearColor;
  47933. });
  47934. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  47935. scene.clearColor = savedSceneClearColor;
  47936. });
  47937. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  47938. var engine = scene.getEngine();
  47939. var index;
  47940. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47941. renderSubMesh(opaqueSubMeshes.data[index]);
  47942. }
  47943. engine.setAlphaTesting(true);
  47944. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47945. renderSubMesh(alphaTestSubMeshes.data[index]);
  47946. }
  47947. engine.setAlphaTesting(false);
  47948. if (transparentSubMeshes.length) {
  47949. // Sort sub meshes
  47950. for (index = 0; index < transparentSubMeshes.length; index++) {
  47951. var submesh = transparentSubMeshes.data[index];
  47952. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  47953. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  47954. }
  47955. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  47956. sortedArray.sort(function (a, b) {
  47957. // Alpha index first
  47958. if (a._alphaIndex > b._alphaIndex) {
  47959. return 1;
  47960. }
  47961. if (a._alphaIndex < b._alphaIndex) {
  47962. return -1;
  47963. }
  47964. // Then distance to camera
  47965. if (a._distanceToCamera < b._distanceToCamera) {
  47966. return 1;
  47967. }
  47968. if (a._distanceToCamera > b._distanceToCamera) {
  47969. return -1;
  47970. }
  47971. return 0;
  47972. });
  47973. // Render sub meshes
  47974. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  47975. for (index = 0; index < sortedArray.length; index++) {
  47976. renderSubMesh(sortedArray[index]);
  47977. }
  47978. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  47979. }
  47980. };
  47981. };
  47982. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  47983. var transform = scene.getTransformMatrix();
  47984. var meshPosition;
  47985. if (this.useCustomMeshPosition) {
  47986. meshPosition = this.customMeshPosition;
  47987. }
  47988. else if (this.attachedNode) {
  47989. meshPosition = this.attachedNode.position;
  47990. }
  47991. else {
  47992. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  47993. }
  47994. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  47995. this._screenCoordinates.x = pos.x / this._viewPort.width;
  47996. this._screenCoordinates.y = pos.y / this._viewPort.height;
  47997. if (this.invert)
  47998. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  47999. };
  48000. // Static methods
  48001. /**
  48002. * Creates a default mesh for the Volumeric Light Scattering post-process
  48003. * @param {string} The mesh name
  48004. * @param {BABYLON.Scene} The scene where to create the mesh
  48005. * @return {BABYLON.Mesh} the default mesh
  48006. */
  48007. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  48008. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  48009. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  48010. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  48011. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  48012. mesh.material = material;
  48013. return mesh;
  48014. };
  48015. return VolumetricLightScatteringPostProcess;
  48016. }(BABYLON.PostProcess));
  48017. __decorate([
  48018. BABYLON.serializeAsVector3()
  48019. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  48020. __decorate([
  48021. BABYLON.serialize()
  48022. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  48023. __decorate([
  48024. BABYLON.serialize()
  48025. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  48026. __decorate([
  48027. BABYLON.serializeAsMeshReference()
  48028. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  48029. __decorate([
  48030. BABYLON.serialize()
  48031. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  48032. __decorate([
  48033. BABYLON.serialize()
  48034. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  48035. __decorate([
  48036. BABYLON.serialize()
  48037. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  48038. __decorate([
  48039. BABYLON.serialize()
  48040. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  48041. __decorate([
  48042. BABYLON.serialize()
  48043. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  48044. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  48045. })(BABYLON || (BABYLON = {}));
  48046. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  48047. // BABYLON.JS Chromatic Aberration GLSL Shader
  48048. // Author: Olivier Guyot
  48049. // Separates very slightly R, G and B colors on the edges of the screen
  48050. // Inspired by Francois Tarlier & Martins Upitis
  48051. var BABYLON;
  48052. (function (BABYLON) {
  48053. var LensRenderingPipeline = (function (_super) {
  48054. __extends(LensRenderingPipeline, _super);
  48055. /**
  48056. * @constructor
  48057. *
  48058. * Effect parameters are as follow:
  48059. * {
  48060. * chromatic_aberration: number; // from 0 to x (1 for realism)
  48061. * edge_blur: number; // from 0 to x (1 for realism)
  48062. * distortion: number; // from 0 to x (1 for realism)
  48063. * grain_amount: number; // from 0 to 1
  48064. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  48065. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  48066. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  48067. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  48068. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  48069. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  48070. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  48071. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  48072. * }
  48073. * Note: if an effect parameter is unset, effect is disabled
  48074. *
  48075. * @param {string} name - The rendering pipeline name
  48076. * @param {object} parameters - An object containing all parameters (see above)
  48077. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  48078. * @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)
  48079. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  48080. */
  48081. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  48082. if (ratio === void 0) { ratio = 1.0; }
  48083. var _this = _super.call(this, scene.getEngine(), name) || this;
  48084. // Lens effects can be of the following:
  48085. // - chromatic aberration (slight shift of RGB colors)
  48086. // - blur on the edge of the lens
  48087. // - lens distortion
  48088. // - depth-of-field blur & highlights enhancing
  48089. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  48090. // - grain effect (noise or custom texture)
  48091. // Two additional texture samplers are needed:
  48092. // - depth map (for depth-of-field)
  48093. // - grain texture
  48094. /**
  48095. * The chromatic aberration PostProcess id in the pipeline
  48096. * @type {string}
  48097. */
  48098. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  48099. /**
  48100. * The highlights enhancing PostProcess id in the pipeline
  48101. * @type {string}
  48102. */
  48103. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  48104. /**
  48105. * The depth-of-field PostProcess id in the pipeline
  48106. * @type {string}
  48107. */
  48108. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  48109. _this._scene = scene;
  48110. // Fetch texture samplers
  48111. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  48112. if (parameters.grain_texture) {
  48113. _this._grainTexture = parameters.grain_texture;
  48114. }
  48115. else {
  48116. _this._createGrainTexture();
  48117. }
  48118. // save parameters
  48119. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  48120. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  48121. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  48122. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  48123. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  48124. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  48125. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  48126. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  48127. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  48128. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  48129. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  48130. // Create effects
  48131. _this._createChromaticAberrationPostProcess(ratio);
  48132. _this._createHighlightsPostProcess(ratio);
  48133. _this._createDepthOfFieldPostProcess(ratio / 4);
  48134. // Set up pipeline
  48135. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  48136. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  48137. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  48138. if (_this._highlightsGain === -1) {
  48139. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  48140. }
  48141. // Finish
  48142. scene.postProcessRenderPipelineManager.addPipeline(_this);
  48143. if (cameras) {
  48144. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  48145. }
  48146. return _this;
  48147. }
  48148. // public methods (self explanatory)
  48149. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  48150. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  48151. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  48152. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  48153. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  48154. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  48155. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  48156. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  48157. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  48158. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  48159. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  48160. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  48161. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  48162. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  48163. };
  48164. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  48165. this._highlightsPostProcess.updateEffect();
  48166. };
  48167. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  48168. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  48169. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  48170. this._highlightsGain = amount;
  48171. };
  48172. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  48173. if (this._highlightsGain === -1) {
  48174. this._highlightsGain = 1.0;
  48175. }
  48176. this._highlightsThreshold = amount;
  48177. };
  48178. LensRenderingPipeline.prototype.disableHighlights = function () {
  48179. this._highlightsGain = -1;
  48180. };
  48181. /**
  48182. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  48183. */
  48184. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  48185. if (disableDepthRender === void 0) { disableDepthRender = false; }
  48186. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  48187. this._chromaticAberrationPostProcess = undefined;
  48188. this._highlightsPostProcess = undefined;
  48189. this._depthOfFieldPostProcess = undefined;
  48190. this._grainTexture.dispose();
  48191. if (disableDepthRender)
  48192. this._scene.disableDepthRenderer();
  48193. };
  48194. // colors shifting and distortion
  48195. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  48196. var _this = this;
  48197. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  48198. [], // samplers
  48199. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  48200. this._chromaticAberrationPostProcess.onApply = function (effect) {
  48201. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  48202. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  48203. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48204. };
  48205. };
  48206. // highlights enhancing
  48207. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  48208. var _this = this;
  48209. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  48210. [], // samplers
  48211. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  48212. this._highlightsPostProcess.onApply = function (effect) {
  48213. effect.setFloat('gain', _this._highlightsGain);
  48214. effect.setFloat('threshold', _this._highlightsThreshold);
  48215. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  48216. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  48217. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48218. };
  48219. };
  48220. // colors shifting and distortion
  48221. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  48222. var _this = this;
  48223. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  48224. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  48225. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  48226. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  48227. this._depthOfFieldPostProcess.onApply = function (effect) {
  48228. effect.setTexture("depthSampler", _this._depthTexture);
  48229. effect.setTexture("grainSampler", _this._grainTexture);
  48230. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  48231. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  48232. effect.setFloat('grain_amount', _this._grainAmount);
  48233. effect.setBool('blur_noise', _this._blurNoise);
  48234. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  48235. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48236. effect.setFloat('distortion', _this._distortion);
  48237. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  48238. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  48239. effect.setFloat('aperture', _this._dofAperture);
  48240. effect.setFloat('darken', _this._dofDarken);
  48241. effect.setFloat('edge_blur', _this._edgeBlur);
  48242. effect.setBool('highlights', (_this._highlightsGain !== -1));
  48243. effect.setFloat('near', _this._scene.activeCamera.minZ);
  48244. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  48245. };
  48246. };
  48247. // creates a black and white random noise texture, 512x512
  48248. LensRenderingPipeline.prototype._createGrainTexture = function () {
  48249. var size = 512;
  48250. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  48251. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  48252. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  48253. var context = this._grainTexture.getContext();
  48254. var rand = function (min, max) {
  48255. return Math.random() * (max - min) + min;
  48256. };
  48257. var value;
  48258. for (var x = 0; x < size; x++) {
  48259. for (var y = 0; y < size; y++) {
  48260. value = Math.floor(rand(0.42, 0.58) * 255);
  48261. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  48262. context.fillRect(x, y, 1, 1);
  48263. }
  48264. }
  48265. this._grainTexture.update(false);
  48266. };
  48267. return LensRenderingPipeline;
  48268. }(BABYLON.PostProcessRenderPipeline));
  48269. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  48270. })(BABYLON || (BABYLON = {}));
  48271. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  48272. //
  48273. // This post-process allows the modification of rendered colors by using
  48274. // a 'look-up table' (LUT). This effect is also called Color Grading.
  48275. //
  48276. // The object needs to be provided an url to a texture containing the color
  48277. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  48278. // Use an image editing software to tweak the LUT to match your needs.
  48279. //
  48280. // For an example of a color LUT, see here:
  48281. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  48282. // For explanations on color grading, see here:
  48283. // http://udn.epicgames.com/Three/ColorGrading.html
  48284. //
  48285. var BABYLON;
  48286. (function (BABYLON) {
  48287. var ColorCorrectionPostProcess = (function (_super) {
  48288. __extends(ColorCorrectionPostProcess, _super);
  48289. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  48290. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  48291. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  48292. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  48293. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48294. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48295. _this.onApply = function (effect) {
  48296. effect.setTexture("colorTable", _this._colorTableTexture);
  48297. };
  48298. return _this;
  48299. }
  48300. return ColorCorrectionPostProcess;
  48301. }(BABYLON.PostProcess));
  48302. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  48303. })(BABYLON || (BABYLON = {}));
  48304. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  48305. var BABYLON;
  48306. (function (BABYLON) {
  48307. var AnaglyphFreeCamera = (function (_super) {
  48308. __extends(AnaglyphFreeCamera, _super);
  48309. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  48310. var _this = _super.call(this, name, position, scene) || this;
  48311. _this.interaxialDistance = interaxialDistance;
  48312. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48313. return _this;
  48314. }
  48315. AnaglyphFreeCamera.prototype.getClassName = function () {
  48316. return "AnaglyphFreeCamera";
  48317. };
  48318. return AnaglyphFreeCamera;
  48319. }(BABYLON.FreeCamera));
  48320. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  48321. var AnaglyphArcRotateCamera = (function (_super) {
  48322. __extends(AnaglyphArcRotateCamera, _super);
  48323. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  48324. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  48325. _this.interaxialDistance = interaxialDistance;
  48326. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48327. return _this;
  48328. }
  48329. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  48330. return "AnaglyphArcRotateCamera";
  48331. };
  48332. return AnaglyphArcRotateCamera;
  48333. }(BABYLON.ArcRotateCamera));
  48334. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  48335. var AnaglyphGamepadCamera = (function (_super) {
  48336. __extends(AnaglyphGamepadCamera, _super);
  48337. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  48338. var _this = _super.call(this, name, position, scene) || this;
  48339. _this.interaxialDistance = interaxialDistance;
  48340. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48341. return _this;
  48342. }
  48343. AnaglyphGamepadCamera.prototype.getClassName = function () {
  48344. return "AnaglyphGamepadCamera";
  48345. };
  48346. return AnaglyphGamepadCamera;
  48347. }(BABYLON.GamepadCamera));
  48348. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  48349. var AnaglyphUniversalCamera = (function (_super) {
  48350. __extends(AnaglyphUniversalCamera, _super);
  48351. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  48352. var _this = _super.call(this, name, position, scene) || this;
  48353. _this.interaxialDistance = interaxialDistance;
  48354. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48355. return _this;
  48356. }
  48357. AnaglyphUniversalCamera.prototype.getClassName = function () {
  48358. return "AnaglyphUniversalCamera";
  48359. };
  48360. return AnaglyphUniversalCamera;
  48361. }(BABYLON.UniversalCamera));
  48362. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  48363. var StereoscopicFreeCamera = (function (_super) {
  48364. __extends(StereoscopicFreeCamera, _super);
  48365. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48366. var _this = _super.call(this, name, position, scene) || this;
  48367. _this.interaxialDistance = interaxialDistance;
  48368. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48369. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48370. return _this;
  48371. }
  48372. StereoscopicFreeCamera.prototype.getClassName = function () {
  48373. return "StereoscopicFreeCamera";
  48374. };
  48375. return StereoscopicFreeCamera;
  48376. }(BABYLON.FreeCamera));
  48377. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  48378. var StereoscopicArcRotateCamera = (function (_super) {
  48379. __extends(StereoscopicArcRotateCamera, _super);
  48380. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  48381. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  48382. _this.interaxialDistance = interaxialDistance;
  48383. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48384. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48385. return _this;
  48386. }
  48387. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  48388. return "StereoscopicArcRotateCamera";
  48389. };
  48390. return StereoscopicArcRotateCamera;
  48391. }(BABYLON.ArcRotateCamera));
  48392. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  48393. var StereoscopicGamepadCamera = (function (_super) {
  48394. __extends(StereoscopicGamepadCamera, _super);
  48395. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48396. var _this = _super.call(this, name, position, scene) || this;
  48397. _this.interaxialDistance = interaxialDistance;
  48398. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48399. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48400. return _this;
  48401. }
  48402. StereoscopicGamepadCamera.prototype.getClassName = function () {
  48403. return "StereoscopicGamepadCamera";
  48404. };
  48405. return StereoscopicGamepadCamera;
  48406. }(BABYLON.GamepadCamera));
  48407. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  48408. var StereoscopicUniversalCamera = (function (_super) {
  48409. __extends(StereoscopicUniversalCamera, _super);
  48410. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48411. var _this = _super.call(this, name, position, scene) || this;
  48412. _this.interaxialDistance = interaxialDistance;
  48413. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48414. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48415. return _this;
  48416. }
  48417. StereoscopicUniversalCamera.prototype.getClassName = function () {
  48418. return "StereoscopicUniversalCamera";
  48419. };
  48420. return StereoscopicUniversalCamera;
  48421. }(BABYLON.UniversalCamera));
  48422. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  48423. })(BABYLON || (BABYLON = {}));
  48424. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  48425. var BABYLON;
  48426. (function (BABYLON) {
  48427. var HolographicCamera = (function (_super) {
  48428. __extends(HolographicCamera, _super);
  48429. function HolographicCamera(name, scene) {
  48430. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  48431. scene.clearColor = new BABYLON.Color4(0, 0, 0, 0);
  48432. _this._holographicViewMatrix = new BABYLON.Matrix();
  48433. _this._identityProjection = BABYLON.Matrix.Identity();
  48434. _this._scriptProjection = BABYLON.Matrix.Transpose(BABYLON.Matrix.PerspectiveFovLH(30, window.innerWidth / window.innerHeight, 1, 20));
  48435. _this._scriptViewProjection = BABYLON.Matrix.Identity();
  48436. _this.fov = 30;
  48437. _this.minZ = 1.0;
  48438. _this.maxZ = 20;
  48439. _this.mode = BABYLON.Camera.PERSPECTIVE_CAMERA;
  48440. _this.isIntermediate = false;
  48441. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  48442. _this.layerMask = 0x0FFFFFFF;
  48443. _this.fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED;
  48444. _this.cameraRigMode = BABYLON.Camera.RIG_MODE_NONE;
  48445. var self = _this;
  48446. _this._onBeforeRenderObserver = scene.onBeforeRenderObservable.add(function (scene) {
  48447. self._holographicViewMatrix.m = window.getViewMatrix();
  48448. self.setViewMatrix(self._holographicViewMatrix);
  48449. var position = window.getCameraPositionVector();
  48450. self.position.copyFromFloats(-position[0], position[1], -position[2]);
  48451. });
  48452. _this._onBeforeCameraRenderObserver = scene.onBeforeCameraRenderObservable.add(function () {
  48453. if (scene.frustumPlanes) {
  48454. self.getFrustumPlanesToRef(scene.frustumPlanes);
  48455. }
  48456. });
  48457. scene.addCamera(_this);
  48458. if (!scene.activeCamera) {
  48459. scene.activeCamera = _this;
  48460. }
  48461. return _this;
  48462. }
  48463. HolographicCamera.prototype.getTypeName = function () {
  48464. return "HolographicCamera";
  48465. };
  48466. ;
  48467. HolographicCamera.prototype.getProjectionMatrix = function () {
  48468. return this._identityProjection;
  48469. };
  48470. ;
  48471. HolographicCamera.prototype.getViewMatrix = function () {
  48472. return this._holographicViewMatrix;
  48473. };
  48474. ;
  48475. HolographicCamera.prototype.setViewMatrix = function (view) {
  48476. this._holographicViewMatrix = view;
  48477. view.m[0] = -view.m[0];
  48478. view.m[1] = -view.m[1];
  48479. view.m[2] = -view.m[2];
  48480. view.m[3] = -view.m[3];
  48481. view.m[8] = -view.m[8];
  48482. view.m[9] = -view.m[9];
  48483. view.m[10] = -view.m[10];
  48484. view.m[11] = -view.m[11];
  48485. };
  48486. ;
  48487. HolographicCamera.prototype._initCache = function () { };
  48488. ;
  48489. HolographicCamera.prototype._updateCache = function () { };
  48490. ;
  48491. HolographicCamera.prototype._updateFromScene = function () { };
  48492. ;
  48493. // Synchronized
  48494. HolographicCamera.prototype._isSynchronizedViewMatrix = function () {
  48495. return true;
  48496. };
  48497. ;
  48498. HolographicCamera.prototype._isSynchronizedProjectionMatrix = function () {
  48499. return true;
  48500. };
  48501. ;
  48502. HolographicCamera.prototype.getFrustumPlanesToRef = function (result) {
  48503. this._holographicViewMatrix.multiplyToRef(this._scriptProjection, this._scriptViewProjection);
  48504. BABYLON.Frustum.GetPlanesToRef(this._scriptViewProjection, result);
  48505. return result;
  48506. };
  48507. ;
  48508. HolographicCamera.prototype.dispose = function () {
  48509. this.getScene().onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  48510. this.getScene().onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  48511. _super.prototype.dispose.call(this);
  48512. };
  48513. return HolographicCamera;
  48514. }(BABYLON.Camera));
  48515. BABYLON.HolographicCamera = HolographicCamera;
  48516. })(BABYLON || (BABYLON = {}));
  48517. //# sourceMappingURL=babylon.holographicCamera.js.map
  48518. var BABYLON;
  48519. (function (BABYLON) {
  48520. var HDRRenderingPipeline = (function (_super) {
  48521. __extends(HDRRenderingPipeline, _super);
  48522. /**
  48523. * @constructor
  48524. * @param {string} name - The rendering pipeline name
  48525. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  48526. * @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)
  48527. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  48528. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  48529. */
  48530. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  48531. if (originalPostProcess === void 0) { originalPostProcess = null; }
  48532. var _this = _super.call(this, scene.getEngine(), name) || this;
  48533. /**
  48534. * Public members
  48535. */
  48536. // Gaussian Blur
  48537. /**
  48538. * Gaussian blur coefficient
  48539. * @type {number}
  48540. */
  48541. _this.gaussCoeff = 0.3;
  48542. /**
  48543. * Gaussian blur mean
  48544. * @type {number}
  48545. */
  48546. _this.gaussMean = 1.0;
  48547. /**
  48548. * Gaussian blur standard deviation
  48549. * @type {number}
  48550. */
  48551. _this.gaussStandDev = 0.8;
  48552. /**
  48553. * Gaussian blur multiplier. Multiplies the blur effect
  48554. * @type {number}
  48555. */
  48556. _this.gaussMultiplier = 4.0;
  48557. // HDR
  48558. /**
  48559. * Exposure, controls the overall intensity of the pipeline
  48560. * @type {number}
  48561. */
  48562. _this.exposure = 1.0;
  48563. /**
  48564. * Minimum luminance that the post-process can output. Luminance is >= 0
  48565. * @type {number}
  48566. */
  48567. _this.minimumLuminance = 1.0;
  48568. /**
  48569. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  48570. * @type {number}
  48571. */
  48572. _this.maximumLuminance = 1e20;
  48573. /**
  48574. * Increase rate for luminance: eye adaptation speed to dark
  48575. * @type {number}
  48576. */
  48577. _this.luminanceIncreaserate = 0.5;
  48578. /**
  48579. * Decrease rate for luminance: eye adaptation speed to bright
  48580. * @type {number}
  48581. */
  48582. _this.luminanceDecreaseRate = 0.5;
  48583. // Bright pass
  48584. /**
  48585. * Minimum luminance needed to compute HDR
  48586. * @type {number}
  48587. */
  48588. _this.brightThreshold = 0.8;
  48589. _this._needUpdate = true;
  48590. _this._scene = scene;
  48591. // Bright pass
  48592. _this._createBrightPassPostProcess(scene, ratio);
  48593. // Down sample X4
  48594. _this._createDownSampleX4PostProcess(scene, ratio);
  48595. // Create gaussian blur post-processes
  48596. _this._createGaussianBlurPostProcess(scene, ratio);
  48597. // Texture adder
  48598. _this._createTextureAdderPostProcess(scene, ratio);
  48599. // Luminance generator
  48600. _this._createLuminanceGeneratorPostProcess(scene);
  48601. // HDR
  48602. _this._createHDRPostProcess(scene, ratio);
  48603. // Pass postprocess
  48604. if (originalPostProcess === null) {
  48605. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  48606. }
  48607. else {
  48608. _this._originalPostProcess = originalPostProcess;
  48609. }
  48610. // Configure pipeline
  48611. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  48612. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  48613. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  48614. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  48615. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  48616. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  48617. var addDownSamplerPostProcess = function (id) {
  48618. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  48619. };
  48620. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  48621. addDownSamplerPostProcess(i);
  48622. }
  48623. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  48624. // Finish
  48625. scene.postProcessRenderPipelineManager.addPipeline(_this);
  48626. if (cameras !== null) {
  48627. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  48628. }
  48629. _this.update();
  48630. return _this;
  48631. }
  48632. /**
  48633. * Tells the pipeline to update its post-processes
  48634. */
  48635. HDRRenderingPipeline.prototype.update = function () {
  48636. this._needUpdate = true;
  48637. };
  48638. /**
  48639. * Returns the current calculated luminance
  48640. */
  48641. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  48642. return this._hdrCurrentLuminance;
  48643. };
  48644. /**
  48645. * Returns the currently drawn luminance
  48646. */
  48647. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  48648. return this._hdrOutputLuminance;
  48649. };
  48650. /**
  48651. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  48652. */
  48653. HDRRenderingPipeline.prototype.dispose = function () {
  48654. this._originalPostProcess = undefined;
  48655. this._brightPassPostProcess = undefined;
  48656. this._downSampleX4PostProcess = undefined;
  48657. this._guassianBlurHPostProcess = undefined;
  48658. this._guassianBlurVPostProcess = undefined;
  48659. this._textureAdderPostProcess = undefined;
  48660. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  48661. this._downSamplePostProcesses[i] = undefined;
  48662. }
  48663. this._hdrPostProcess = undefined;
  48664. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  48665. };
  48666. /**
  48667. * Creates the HDR post-process and computes the luminance adaptation
  48668. */
  48669. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  48670. var _this = this;
  48671. var hdrLastLuminance = 0.0;
  48672. this._hdrOutputLuminance = -1.0;
  48673. this._hdrCurrentLuminance = 1.0;
  48674. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  48675. this._hdrPostProcess.onApply = function (effect) {
  48676. if (_this._hdrOutputLuminance < 0.0) {
  48677. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  48678. }
  48679. else {
  48680. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  48681. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  48682. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  48683. }
  48684. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  48685. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  48686. }
  48687. else {
  48688. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  48689. }
  48690. }
  48691. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  48692. hdrLastLuminance += scene.getEngine().getDeltaTime();
  48693. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  48694. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  48695. effect.setFloat("exposure", _this.exposure);
  48696. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  48697. _this._needUpdate = false;
  48698. };
  48699. };
  48700. /**
  48701. * Texture Adder post-process
  48702. */
  48703. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  48704. var _this = this;
  48705. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  48706. this._textureAdderPostProcess.onApply = function (effect) {
  48707. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  48708. };
  48709. };
  48710. /**
  48711. * Down sample X4 post-process
  48712. */
  48713. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  48714. var _this = this;
  48715. var downSampleX4Offsets = new Array(32);
  48716. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  48717. this._downSampleX4PostProcess.onApply = function (effect) {
  48718. if (_this._needUpdate) {
  48719. var id = 0;
  48720. for (var i = -2; i < 2; i++) {
  48721. for (var j = -2; j < 2; j++) {
  48722. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  48723. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  48724. id += 2;
  48725. }
  48726. }
  48727. }
  48728. effect.setArray2("dsOffsets", downSampleX4Offsets);
  48729. };
  48730. };
  48731. /**
  48732. * Bright pass post-process
  48733. */
  48734. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  48735. var _this = this;
  48736. var brightOffsets = new Array(8);
  48737. var brightPassCallback = function (effect) {
  48738. if (_this._needUpdate) {
  48739. var sU = (1.0 / _this._brightPassPostProcess.width);
  48740. var sV = (1.0 / _this._brightPassPostProcess.height);
  48741. brightOffsets[0] = -0.5 * sU;
  48742. brightOffsets[1] = 0.5 * sV;
  48743. brightOffsets[2] = 0.5 * sU;
  48744. brightOffsets[3] = 0.5 * sV;
  48745. brightOffsets[4] = -0.5 * sU;
  48746. brightOffsets[5] = -0.5 * sV;
  48747. brightOffsets[6] = 0.5 * sU;
  48748. brightOffsets[7] = -0.5 * sV;
  48749. }
  48750. effect.setArray2("dsOffsets", brightOffsets);
  48751. effect.setFloat("brightThreshold", _this.brightThreshold);
  48752. };
  48753. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  48754. this._brightPassPostProcess.onApply = brightPassCallback;
  48755. };
  48756. /**
  48757. * Luminance generator. Creates the luminance post-process and down sample post-processes
  48758. */
  48759. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  48760. var _this = this;
  48761. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  48762. var luminanceOffsets = new Array(8);
  48763. var downSampleOffsets = new Array(18);
  48764. var halfDestPixelSize;
  48765. this._downSamplePostProcesses = new Array(lumSteps);
  48766. // Utils for luminance
  48767. var luminanceUpdateSourceOffsets = function (width, height) {
  48768. var sU = (1.0 / width);
  48769. var sV = (1.0 / height);
  48770. luminanceOffsets[0] = -0.5 * sU;
  48771. luminanceOffsets[1] = 0.5 * sV;
  48772. luminanceOffsets[2] = 0.5 * sU;
  48773. luminanceOffsets[3] = 0.5 * sV;
  48774. luminanceOffsets[4] = -0.5 * sU;
  48775. luminanceOffsets[5] = -0.5 * sV;
  48776. luminanceOffsets[6] = 0.5 * sU;
  48777. luminanceOffsets[7] = -0.5 * sV;
  48778. };
  48779. var luminanceUpdateDestOffsets = function (width, height) {
  48780. var id = 0;
  48781. for (var x = -1; x < 2; x++) {
  48782. for (var y = -1; y < 2; y++) {
  48783. downSampleOffsets[id] = (x) / width;
  48784. downSampleOffsets[id + 1] = (y) / height;
  48785. id += 2;
  48786. }
  48787. }
  48788. };
  48789. // Luminance callback
  48790. var luminanceCallback = function (effect) {
  48791. if (_this._needUpdate) {
  48792. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  48793. }
  48794. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  48795. effect.setArray2("lumOffsets", luminanceOffsets);
  48796. };
  48797. // Down sample callbacks
  48798. var downSampleCallback = function (indice) {
  48799. var i = indice;
  48800. return function (effect) {
  48801. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  48802. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  48803. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  48804. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  48805. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  48806. effect.setArray2("dsOffsets", downSampleOffsets);
  48807. };
  48808. };
  48809. var downSampleAfterRenderCallback = function (effect) {
  48810. // Unpack result
  48811. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  48812. 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);
  48813. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  48814. };
  48815. // Create luminance post-process
  48816. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  48817. this._downSamplePostProcesses[lumSteps - 1] = new BABYLON.PostProcess("hdr", "hdr", ["lumOffsets"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE_GENERATOR", BABYLON.Engine.TEXTURETYPE_FLOAT);
  48818. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  48819. // Create down sample post-processes
  48820. for (var i = lumSteps - 2; i >= 0; i--) {
  48821. var length = Math.pow(3, i);
  48822. ratio = { width: length, height: length };
  48823. var defines = "#define DOWN_SAMPLE\n";
  48824. if (i === 0) {
  48825. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  48826. }
  48827. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  48828. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  48829. if (i === 0) {
  48830. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  48831. }
  48832. }
  48833. };
  48834. /**
  48835. * Gaussian blur post-processes. Horizontal and Vertical
  48836. */
  48837. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  48838. var _this = this;
  48839. var blurOffsetsW = new Array(9);
  48840. var blurOffsetsH = new Array(9);
  48841. var blurWeights = new Array(9);
  48842. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  48843. // Utils for gaussian blur
  48844. var calculateBlurOffsets = function (height) {
  48845. var lastOutputDimensions = {
  48846. width: scene.getEngine().getRenderWidth(),
  48847. height: scene.getEngine().getRenderHeight()
  48848. };
  48849. for (var i = 0; i < 9; i++) {
  48850. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  48851. if (height) {
  48852. blurOffsetsH[i] = value;
  48853. }
  48854. else {
  48855. blurOffsetsW[i] = value;
  48856. }
  48857. }
  48858. };
  48859. var calculateWeights = function () {
  48860. var x = 0.0;
  48861. for (var i = 0; i < 9; i++) {
  48862. x = (i - 4.0) / 4.0;
  48863. blurWeights[i] = _this.gaussCoeff * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussStandDev)) * Math.exp((-((x - _this.gaussMean) * (x - _this.gaussMean))) / (2.0 * _this.gaussStandDev * _this.gaussStandDev));
  48864. }
  48865. };
  48866. // Callback
  48867. var gaussianBlurCallback = function (height) {
  48868. return function (effect) {
  48869. if (_this._needUpdate) {
  48870. calculateWeights();
  48871. calculateBlurOffsets(height);
  48872. }
  48873. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  48874. effect.setArray("blurWeights", blurWeights);
  48875. effect.setFloat("multiplier", _this.gaussMultiplier);
  48876. };
  48877. };
  48878. // Create horizontal gaussian blur post-processes
  48879. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  48880. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  48881. // Create vertical gaussian blur post-process
  48882. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  48883. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  48884. };
  48885. return HDRRenderingPipeline;
  48886. }(BABYLON.PostProcessRenderPipeline));
  48887. // Luminance generator
  48888. HDRRenderingPipeline.LUM_STEPS = 6;
  48889. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  48890. })(BABYLON || (BABYLON = {}));
  48891. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  48892. var BABYLON;
  48893. (function (BABYLON) {
  48894. var FaceAdjacencies = (function () {
  48895. function FaceAdjacencies() {
  48896. this.edges = new Array();
  48897. this.edgesConnectedCount = 0;
  48898. }
  48899. return FaceAdjacencies;
  48900. }());
  48901. var EdgesRenderer = (function () {
  48902. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  48903. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  48904. if (epsilon === void 0) { epsilon = 0.95; }
  48905. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  48906. this.edgesWidthScalerForOrthographic = 1000.0;
  48907. this.edgesWidthScalerForPerspective = 50.0;
  48908. this._linesPositions = new Array();
  48909. this._linesNormals = new Array();
  48910. this._linesIndices = new Array();
  48911. this._buffers = {};
  48912. this._checkVerticesInsteadOfIndices = false;
  48913. this._source = source;
  48914. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  48915. this._epsilon = epsilon;
  48916. this._prepareRessources();
  48917. this._generateEdgesLines();
  48918. }
  48919. EdgesRenderer.prototype._prepareRessources = function () {
  48920. if (this._lineShader) {
  48921. return;
  48922. }
  48923. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  48924. attributes: ["position", "normal"],
  48925. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  48926. });
  48927. this._lineShader.disableDepthWrite = true;
  48928. this._lineShader.backFaceCulling = false;
  48929. };
  48930. EdgesRenderer.prototype.dispose = function () {
  48931. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  48932. if (buffer) {
  48933. buffer.dispose();
  48934. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  48935. }
  48936. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  48937. if (buffer) {
  48938. buffer.dispose();
  48939. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  48940. }
  48941. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  48942. this._lineShader.dispose();
  48943. };
  48944. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  48945. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  48946. return 0;
  48947. }
  48948. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  48949. return 1;
  48950. }
  48951. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  48952. return 2;
  48953. }
  48954. return -1;
  48955. };
  48956. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  48957. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  48958. return 0;
  48959. }
  48960. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  48961. return 1;
  48962. }
  48963. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  48964. return 2;
  48965. }
  48966. return -1;
  48967. };
  48968. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  48969. var needToCreateLine;
  48970. if (edge === undefined) {
  48971. needToCreateLine = true;
  48972. }
  48973. else {
  48974. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  48975. needToCreateLine = dotProduct < this._epsilon;
  48976. }
  48977. if (needToCreateLine) {
  48978. var offset = this._linesPositions.length / 3;
  48979. var normal = p0.subtract(p1);
  48980. normal.normalize();
  48981. // Positions
  48982. this._linesPositions.push(p0.x);
  48983. this._linesPositions.push(p0.y);
  48984. this._linesPositions.push(p0.z);
  48985. this._linesPositions.push(p0.x);
  48986. this._linesPositions.push(p0.y);
  48987. this._linesPositions.push(p0.z);
  48988. this._linesPositions.push(p1.x);
  48989. this._linesPositions.push(p1.y);
  48990. this._linesPositions.push(p1.z);
  48991. this._linesPositions.push(p1.x);
  48992. this._linesPositions.push(p1.y);
  48993. this._linesPositions.push(p1.z);
  48994. // Normals
  48995. this._linesNormals.push(p1.x);
  48996. this._linesNormals.push(p1.y);
  48997. this._linesNormals.push(p1.z);
  48998. this._linesNormals.push(-1);
  48999. this._linesNormals.push(p1.x);
  49000. this._linesNormals.push(p1.y);
  49001. this._linesNormals.push(p1.z);
  49002. this._linesNormals.push(1);
  49003. this._linesNormals.push(p0.x);
  49004. this._linesNormals.push(p0.y);
  49005. this._linesNormals.push(p0.z);
  49006. this._linesNormals.push(-1);
  49007. this._linesNormals.push(p0.x);
  49008. this._linesNormals.push(p0.y);
  49009. this._linesNormals.push(p0.z);
  49010. this._linesNormals.push(1);
  49011. // Indices
  49012. this._linesIndices.push(offset);
  49013. this._linesIndices.push(offset + 1);
  49014. this._linesIndices.push(offset + 2);
  49015. this._linesIndices.push(offset);
  49016. this._linesIndices.push(offset + 2);
  49017. this._linesIndices.push(offset + 3);
  49018. }
  49019. };
  49020. EdgesRenderer.prototype._generateEdgesLines = function () {
  49021. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49022. var indices = this._source.getIndices();
  49023. // First let's find adjacencies
  49024. var adjacencies = new Array();
  49025. var faceNormals = new Array();
  49026. var index;
  49027. var faceAdjacencies;
  49028. // Prepare faces
  49029. for (index = 0; index < indices.length; index += 3) {
  49030. faceAdjacencies = new FaceAdjacencies();
  49031. var p0Index = indices[index];
  49032. var p1Index = indices[index + 1];
  49033. var p2Index = indices[index + 2];
  49034. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  49035. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  49036. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  49037. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  49038. faceNormal.normalize();
  49039. faceNormals.push(faceNormal);
  49040. adjacencies.push(faceAdjacencies);
  49041. }
  49042. // Scan
  49043. for (index = 0; index < adjacencies.length; index++) {
  49044. faceAdjacencies = adjacencies[index];
  49045. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  49046. var otherFaceAdjacencies = adjacencies[otherIndex];
  49047. if (faceAdjacencies.edgesConnectedCount === 3) {
  49048. break;
  49049. }
  49050. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  49051. continue;
  49052. }
  49053. var otherP0 = indices[otherIndex * 3];
  49054. var otherP1 = indices[otherIndex * 3 + 1];
  49055. var otherP2 = indices[otherIndex * 3 + 2];
  49056. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  49057. var otherEdgeIndex;
  49058. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  49059. continue;
  49060. }
  49061. switch (edgeIndex) {
  49062. case 0:
  49063. if (this._checkVerticesInsteadOfIndices) {
  49064. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  49065. }
  49066. else {
  49067. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  49068. }
  49069. break;
  49070. case 1:
  49071. if (this._checkVerticesInsteadOfIndices) {
  49072. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  49073. }
  49074. else {
  49075. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  49076. }
  49077. break;
  49078. case 2:
  49079. if (this._checkVerticesInsteadOfIndices) {
  49080. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  49081. }
  49082. else {
  49083. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  49084. }
  49085. break;
  49086. }
  49087. if (otherEdgeIndex === -1) {
  49088. continue;
  49089. }
  49090. faceAdjacencies.edges[edgeIndex] = otherIndex;
  49091. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  49092. faceAdjacencies.edgesConnectedCount++;
  49093. otherFaceAdjacencies.edgesConnectedCount++;
  49094. if (faceAdjacencies.edgesConnectedCount === 3) {
  49095. break;
  49096. }
  49097. }
  49098. }
  49099. }
  49100. // Create lines
  49101. for (index = 0; index < adjacencies.length; index++) {
  49102. // 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
  49103. var current = adjacencies[index];
  49104. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  49105. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  49106. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  49107. }
  49108. // Merge into a single mesh
  49109. var engine = this._source.getScene().getEngine();
  49110. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  49111. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  49112. this._ib = engine.createIndexBuffer(this._linesIndices);
  49113. this._indicesCount = this._linesIndices.length;
  49114. };
  49115. EdgesRenderer.prototype.render = function () {
  49116. if (!this._lineShader.isReady()) {
  49117. return;
  49118. }
  49119. var scene = this._source.getScene();
  49120. var engine = scene.getEngine();
  49121. this._lineShader._preBind();
  49122. // VBOs
  49123. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  49124. scene.resetCachedMaterial();
  49125. this._lineShader.setColor4("color", this._source.edgesColor);
  49126. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  49127. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  49128. }
  49129. else {
  49130. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  49131. }
  49132. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  49133. this._lineShader.bind(this._source.getWorldMatrix());
  49134. // Draw order
  49135. engine.draw(true, 0, this._indicesCount);
  49136. this._lineShader.unbind();
  49137. engine.setDepthWrite(true);
  49138. };
  49139. return EdgesRenderer;
  49140. }());
  49141. BABYLON.EdgesRenderer = EdgesRenderer;
  49142. })(BABYLON || (BABYLON = {}));
  49143. //# sourceMappingURL=babylon.edgesRenderer.js.map
  49144. var BABYLON;
  49145. (function (BABYLON) {
  49146. var TonemappingOperator;
  49147. (function (TonemappingOperator) {
  49148. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  49149. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  49150. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  49151. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  49152. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  49153. ;
  49154. var TonemapPostProcess = (function (_super) {
  49155. __extends(TonemapPostProcess, _super);
  49156. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  49157. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  49158. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49159. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  49160. _this._operator = _operator;
  49161. _this.exposureAdjustment = exposureAdjustment;
  49162. var defines = "#define ";
  49163. if (_this._operator === TonemappingOperator.Hable)
  49164. defines += "HABLE_TONEMAPPING";
  49165. else if (_this._operator === TonemappingOperator.Reinhard)
  49166. defines += "REINHARD_TONEMAPPING";
  49167. else if (_this._operator === TonemappingOperator.HejiDawson)
  49168. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  49169. else if (_this._operator === TonemappingOperator.Photographic)
  49170. defines += "PHOTOGRAPHIC_TONEMAPPING";
  49171. //sadly a second call to create the effect.
  49172. _this.updateEffect(defines);
  49173. _this.onApply = function (effect) {
  49174. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  49175. };
  49176. return _this;
  49177. }
  49178. return TonemapPostProcess;
  49179. }(BABYLON.PostProcess));
  49180. BABYLON.TonemapPostProcess = TonemapPostProcess;
  49181. })(BABYLON || (BABYLON = {}));
  49182. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  49183. var BABYLON;
  49184. (function (BABYLON) {
  49185. var ReflectionProbe = (function () {
  49186. function ReflectionProbe(name, size, scene, generateMipMaps) {
  49187. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49188. var _this = this;
  49189. this.name = name;
  49190. this._viewMatrix = BABYLON.Matrix.Identity();
  49191. this._target = BABYLON.Vector3.Zero();
  49192. this._add = BABYLON.Vector3.Zero();
  49193. this.invertYAxis = false;
  49194. this.position = BABYLON.Vector3.Zero();
  49195. this._scene = scene;
  49196. this._scene.reflectionProbes.push(this);
  49197. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  49198. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  49199. switch (faceIndex) {
  49200. case 0:
  49201. _this._add.copyFromFloats(1, 0, 0);
  49202. break;
  49203. case 1:
  49204. _this._add.copyFromFloats(-1, 0, 0);
  49205. break;
  49206. case 2:
  49207. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  49208. break;
  49209. case 3:
  49210. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  49211. break;
  49212. case 4:
  49213. _this._add.copyFromFloats(0, 0, 1);
  49214. break;
  49215. case 5:
  49216. _this._add.copyFromFloats(0, 0, -1);
  49217. break;
  49218. }
  49219. if (_this._attachedMesh) {
  49220. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  49221. }
  49222. _this.position.addToRef(_this._add, _this._target);
  49223. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  49224. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  49225. });
  49226. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  49227. scene.updateTransformMatrix(true);
  49228. });
  49229. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  49230. }
  49231. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  49232. get: function () {
  49233. return this._renderTargetTexture.refreshRate;
  49234. },
  49235. set: function (value) {
  49236. this._renderTargetTexture.refreshRate = value;
  49237. },
  49238. enumerable: true,
  49239. configurable: true
  49240. });
  49241. ReflectionProbe.prototype.getScene = function () {
  49242. return this._scene;
  49243. };
  49244. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  49245. get: function () {
  49246. return this._renderTargetTexture;
  49247. },
  49248. enumerable: true,
  49249. configurable: true
  49250. });
  49251. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  49252. get: function () {
  49253. return this._renderTargetTexture.renderList;
  49254. },
  49255. enumerable: true,
  49256. configurable: true
  49257. });
  49258. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  49259. this._attachedMesh = mesh;
  49260. };
  49261. ReflectionProbe.prototype.dispose = function () {
  49262. var index = this._scene.reflectionProbes.indexOf(this);
  49263. if (index !== -1) {
  49264. // Remove from the scene if found
  49265. this._scene.reflectionProbes.splice(index, 1);
  49266. }
  49267. if (this._renderTargetTexture) {
  49268. this._renderTargetTexture.dispose();
  49269. this._renderTargetTexture = null;
  49270. }
  49271. };
  49272. return ReflectionProbe;
  49273. }());
  49274. BABYLON.ReflectionProbe = ReflectionProbe;
  49275. })(BABYLON || (BABYLON = {}));
  49276. //# sourceMappingURL=babylon.reflectionProbe.js.map
  49277. var BABYLON;
  49278. (function (BABYLON) {
  49279. var SolidParticle = (function () {
  49280. /**
  49281. * Creates a Solid Particle object.
  49282. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  49283. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  49284. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  49285. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  49286. * `shapeId` (integer) is the model shape identifier in the SPS.
  49287. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  49288. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  49289. */
  49290. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  49291. this.idx = 0; // particle global index
  49292. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  49293. this.position = BABYLON.Vector3.Zero(); // position
  49294. this.rotation = BABYLON.Vector3.Zero(); // rotation
  49295. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  49296. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  49297. this.velocity = BABYLON.Vector3.Zero(); // velocity
  49298. this.alive = true; // alive
  49299. this.isVisible = true; // visibility
  49300. this._pos = 0; // index of this particle in the global "positions" array
  49301. this.shapeId = 0; // model shape id
  49302. this.idxInShape = 0; // index of the particle in its shape id
  49303. this.idx = particleIndex;
  49304. this._pos = positionIndex;
  49305. this._model = model;
  49306. this.shapeId = shapeId;
  49307. this.idxInShape = idxInShape;
  49308. this._sps = sps;
  49309. if (modelBoundingInfo) {
  49310. this._modelBoundingInfo = modelBoundingInfo;
  49311. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  49312. }
  49313. }
  49314. Object.defineProperty(SolidParticle.prototype, "scale", {
  49315. /**
  49316. * legacy support, changed scale to scaling
  49317. */
  49318. get: function () {
  49319. return this.scaling;
  49320. },
  49321. set: function (scale) {
  49322. this.scaling = scale;
  49323. },
  49324. enumerable: true,
  49325. configurable: true
  49326. });
  49327. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  49328. /**
  49329. * legacy support, changed quaternion to rotationQuaternion
  49330. */
  49331. get: function () {
  49332. return this.rotationQuaternion;
  49333. },
  49334. set: function (q) {
  49335. this.rotationQuaternion = q;
  49336. },
  49337. enumerable: true,
  49338. configurable: true
  49339. });
  49340. /**
  49341. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  49342. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  49343. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  49344. */
  49345. SolidParticle.prototype.intersectsMesh = function (target) {
  49346. if (!this._boundingInfo || !target._boundingInfo) {
  49347. return false;
  49348. }
  49349. if (this._sps._bSphereOnly) {
  49350. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  49351. }
  49352. return this._boundingInfo.intersects(target._boundingInfo, false);
  49353. };
  49354. return SolidParticle;
  49355. }());
  49356. BABYLON.SolidParticle = SolidParticle;
  49357. var ModelShape = (function () {
  49358. /**
  49359. * 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.
  49360. * SPS internal tool, don't use it manually.
  49361. */
  49362. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  49363. this.shapeID = id;
  49364. this._shape = shape;
  49365. this._shapeUV = shapeUV;
  49366. this._positionFunction = posFunction;
  49367. this._vertexFunction = vtxFunction;
  49368. }
  49369. return ModelShape;
  49370. }());
  49371. BABYLON.ModelShape = ModelShape;
  49372. })(BABYLON || (BABYLON = {}));
  49373. //# sourceMappingURL=babylon.solidParticle.js.map
  49374. var BABYLON;
  49375. (function (BABYLON) {
  49376. /**
  49377. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  49378. */
  49379. var SolidParticleSystem = (function () {
  49380. /**
  49381. * Creates a SPS (Solid Particle System) object.
  49382. * `name` (String) is the SPS name, this will be the underlying mesh name.
  49383. * `scene` (Scene) is the scene in which the SPS is added.
  49384. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  49385. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  49386. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  49387. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  49388. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  49389. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  49390. */
  49391. function SolidParticleSystem(name, scene, options) {
  49392. // public members
  49393. /**
  49394. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  49395. * Example : var p = SPS.particles[i];
  49396. */
  49397. this.particles = new Array();
  49398. /**
  49399. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  49400. */
  49401. this.nbParticles = 0;
  49402. /**
  49403. * If the particles must ever face the camera (default false). Useful for planar particles.
  49404. */
  49405. this.billboard = false;
  49406. /**
  49407. * Recompute normals when adding a shape
  49408. */
  49409. this.recomputeNormals = true;
  49410. /**
  49411. * This a counter ofr your own usage. It's not set by any SPS functions.
  49412. */
  49413. this.counter = 0;
  49414. /**
  49415. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  49416. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  49417. */
  49418. this.vars = {};
  49419. this._positions = new Array();
  49420. this._indices = new Array();
  49421. this._normals = new Array();
  49422. this._colors = new Array();
  49423. this._uvs = new Array();
  49424. this._index = 0; // indices index
  49425. this._updatable = true;
  49426. this._pickable = false;
  49427. this._isVisibilityBoxLocked = false;
  49428. this._alwaysVisible = false;
  49429. this._shapeCounter = 0;
  49430. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  49431. this._color = new BABYLON.Color4(0, 0, 0, 0);
  49432. this._computeParticleColor = true;
  49433. this._computeParticleTexture = true;
  49434. this._computeParticleRotation = true;
  49435. this._computeParticleVertex = false;
  49436. this._computeBoundingBox = false;
  49437. this._cam_axisZ = BABYLON.Vector3.Zero();
  49438. this._cam_axisY = BABYLON.Vector3.Zero();
  49439. this._cam_axisX = BABYLON.Vector3.Zero();
  49440. this._axisX = BABYLON.Axis.X;
  49441. this._axisY = BABYLON.Axis.Y;
  49442. this._axisZ = BABYLON.Axis.Z;
  49443. this._camDir = BABYLON.Vector3.Zero();
  49444. this._rotMatrix = new BABYLON.Matrix();
  49445. this._invertMatrix = new BABYLON.Matrix();
  49446. this._rotated = BABYLON.Vector3.Zero();
  49447. this._quaternion = new BABYLON.Quaternion();
  49448. this._vertex = BABYLON.Vector3.Zero();
  49449. this._normal = BABYLON.Vector3.Zero();
  49450. this._yaw = 0.0;
  49451. this._pitch = 0.0;
  49452. this._roll = 0.0;
  49453. this._halfroll = 0.0;
  49454. this._halfpitch = 0.0;
  49455. this._halfyaw = 0.0;
  49456. this._sinRoll = 0.0;
  49457. this._cosRoll = 0.0;
  49458. this._sinPitch = 0.0;
  49459. this._cosPitch = 0.0;
  49460. this._sinYaw = 0.0;
  49461. this._cosYaw = 0.0;
  49462. this._w = 0.0;
  49463. this._minimum = BABYLON.Tmp.Vector3[0];
  49464. this._maximum = BABYLON.Tmp.Vector3[1];
  49465. this._scale = BABYLON.Tmp.Vector3[2];
  49466. this._translation = BABYLON.Tmp.Vector3[3];
  49467. this._minBbox = BABYLON.Tmp.Vector3[4];
  49468. this._maxBbox = BABYLON.Tmp.Vector3[5];
  49469. this._particlesIntersect = false;
  49470. this._bSphereOnly = false;
  49471. this._bSphereRadiusFactor = 1.0;
  49472. this.name = name;
  49473. this._scene = scene;
  49474. this._camera = scene.activeCamera;
  49475. this._pickable = options ? options.isPickable : false;
  49476. this._particlesIntersect = options ? options.particleIntersection : false;
  49477. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  49478. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  49479. if (options && options.updatable) {
  49480. this._updatable = options.updatable;
  49481. }
  49482. else {
  49483. this._updatable = true;
  49484. }
  49485. if (this._pickable) {
  49486. this.pickedParticles = [];
  49487. }
  49488. }
  49489. /**
  49490. * Builds the SPS underlying mesh. Returns a standard Mesh.
  49491. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  49492. */
  49493. SolidParticleSystem.prototype.buildMesh = function () {
  49494. if (this.nbParticles === 0) {
  49495. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  49496. this.addShape(triangle, 1);
  49497. triangle.dispose();
  49498. }
  49499. this._positions32 = new Float32Array(this._positions);
  49500. this._uvs32 = new Float32Array(this._uvs);
  49501. this._colors32 = new Float32Array(this._colors);
  49502. if (this.recomputeNormals) {
  49503. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  49504. }
  49505. this._normals32 = new Float32Array(this._normals);
  49506. this._fixedNormal32 = new Float32Array(this._normals);
  49507. var vertexData = new BABYLON.VertexData();
  49508. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  49509. vertexData.indices = this._indices;
  49510. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  49511. if (this._uvs32) {
  49512. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  49513. ;
  49514. }
  49515. if (this._colors32) {
  49516. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  49517. }
  49518. var mesh = new BABYLON.Mesh(this.name, this._scene);
  49519. vertexData.applyToMesh(mesh, this._updatable);
  49520. this.mesh = mesh;
  49521. this.mesh.isPickable = this._pickable;
  49522. // free memory
  49523. this._positions = null;
  49524. this._normals = null;
  49525. this._uvs = null;
  49526. this._colors = null;
  49527. if (!this._updatable) {
  49528. this.particles.length = 0;
  49529. }
  49530. return mesh;
  49531. };
  49532. /**
  49533. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  49534. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  49535. * Thus the particles generated from `digest()` have their property `position` set yet.
  49536. * `mesh` ( Mesh ) is the mesh to be digested
  49537. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  49538. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  49539. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  49540. */
  49541. SolidParticleSystem.prototype.digest = function (mesh, options) {
  49542. var size = (options && options.facetNb) || 1;
  49543. var number = (options && options.number);
  49544. var delta = (options && options.delta) || 0;
  49545. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49546. var meshInd = mesh.getIndices();
  49547. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49548. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49549. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49550. var f = 0; // facet counter
  49551. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  49552. // compute size from number
  49553. if (number) {
  49554. number = (number > totalFacets) ? totalFacets : number;
  49555. size = Math.round(totalFacets / number);
  49556. delta = 0;
  49557. }
  49558. else {
  49559. size = (size > totalFacets) ? totalFacets : size;
  49560. }
  49561. var facetPos = []; // submesh positions
  49562. var facetInd = []; // submesh indices
  49563. var facetUV = []; // submesh UV
  49564. var facetCol = []; // submesh colors
  49565. var barycenter = BABYLON.Tmp.Vector3[0];
  49566. var rand;
  49567. var sizeO = size;
  49568. while (f < totalFacets) {
  49569. size = sizeO + Math.floor((1 + delta) * Math.random());
  49570. if (f > totalFacets - size) {
  49571. size = totalFacets - f;
  49572. }
  49573. // reset temp arrays
  49574. facetPos.length = 0;
  49575. facetInd.length = 0;
  49576. facetUV.length = 0;
  49577. facetCol.length = 0;
  49578. // iterate over "size" facets
  49579. var fi = 0;
  49580. for (var j = f * 3; j < (f + size) * 3; j++) {
  49581. facetInd.push(fi);
  49582. var i = meshInd[j];
  49583. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  49584. if (meshUV) {
  49585. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  49586. }
  49587. if (meshCol) {
  49588. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  49589. }
  49590. fi++;
  49591. }
  49592. // create a model shape for each single particle
  49593. var idx = this.nbParticles;
  49594. var shape = this._posToShape(facetPos);
  49595. var shapeUV = this._uvsToShapeUV(facetUV);
  49596. // compute the barycenter of the shape
  49597. var v;
  49598. for (v = 0; v < shape.length; v++) {
  49599. barycenter.addInPlace(shape[v]);
  49600. }
  49601. barycenter.scaleInPlace(1 / shape.length);
  49602. // shift the shape from its barycenter to the origin
  49603. for (v = 0; v < shape.length; v++) {
  49604. shape[v].subtractInPlace(barycenter);
  49605. }
  49606. var bInfo;
  49607. if (this._particlesIntersect) {
  49608. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  49609. }
  49610. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  49611. // add the particle in the SPS
  49612. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  49613. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0, bInfo);
  49614. // initialize the particle position
  49615. this.particles[this.nbParticles].position.addInPlace(barycenter);
  49616. this._index += shape.length;
  49617. idx++;
  49618. this.nbParticles++;
  49619. this._shapeCounter++;
  49620. f += size;
  49621. }
  49622. return this;
  49623. };
  49624. //reset copy
  49625. SolidParticleSystem.prototype._resetCopy = function () {
  49626. this._copy.position.x = 0;
  49627. this._copy.position.y = 0;
  49628. this._copy.position.z = 0;
  49629. this._copy.rotation.x = 0;
  49630. this._copy.rotation.y = 0;
  49631. this._copy.rotation.z = 0;
  49632. this._copy.rotationQuaternion = null;
  49633. this._copy.scaling.x = 1;
  49634. this._copy.scaling.y = 1;
  49635. this._copy.scaling.z = 1;
  49636. this._copy.uvs.x = 0;
  49637. this._copy.uvs.y = 0;
  49638. this._copy.uvs.z = 1;
  49639. this._copy.uvs.w = 1;
  49640. this._copy.color = null;
  49641. };
  49642. // _meshBuilder : inserts the shape model in the global SPS mesh
  49643. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  49644. var i;
  49645. var u = 0;
  49646. var c = 0;
  49647. var n = 0;
  49648. this._resetCopy();
  49649. if (options && options.positionFunction) {
  49650. options.positionFunction(this._copy, idx, idxInShape);
  49651. }
  49652. if (this._copy.rotationQuaternion) {
  49653. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49654. }
  49655. else {
  49656. this._yaw = this._copy.rotation.y;
  49657. this._pitch = this._copy.rotation.x;
  49658. this._roll = this._copy.rotation.z;
  49659. this._quaternionRotationYPR();
  49660. }
  49661. this._quaternionToRotationMatrix();
  49662. for (i = 0; i < shape.length; i++) {
  49663. this._vertex.x = shape[i].x;
  49664. this._vertex.y = shape[i].y;
  49665. this._vertex.z = shape[i].z;
  49666. if (options && options.vertexFunction) {
  49667. options.vertexFunction(this._copy, this._vertex, i);
  49668. }
  49669. this._vertex.x *= this._copy.scaling.x;
  49670. this._vertex.y *= this._copy.scaling.y;
  49671. this._vertex.z *= this._copy.scaling.z;
  49672. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49673. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  49674. if (meshUV) {
  49675. 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);
  49676. u += 2;
  49677. }
  49678. if (this._copy.color) {
  49679. this._color = this._copy.color;
  49680. }
  49681. else if (meshCol && meshCol[c] !== undefined) {
  49682. this._color.r = meshCol[c];
  49683. this._color.g = meshCol[c + 1];
  49684. this._color.b = meshCol[c + 2];
  49685. this._color.a = meshCol[c + 3];
  49686. }
  49687. else {
  49688. this._color.r = 1;
  49689. this._color.g = 1;
  49690. this._color.b = 1;
  49691. this._color.a = 1;
  49692. }
  49693. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  49694. c += 4;
  49695. if (!this.recomputeNormals && meshNor) {
  49696. this._normal.x = meshNor[n];
  49697. this._normal.y = meshNor[n + 1];
  49698. this._normal.z = meshNor[n + 2];
  49699. BABYLON.Vector3.TransformCoordinatesToRef(this._normal, this._rotMatrix, this._normal);
  49700. normals.push(this._normal.x, this._normal.y, this._normal.z);
  49701. n += 3;
  49702. }
  49703. }
  49704. for (i = 0; i < meshInd.length; i++) {
  49705. indices.push(p + meshInd[i]);
  49706. }
  49707. if (this._pickable) {
  49708. var nbfaces = meshInd.length / 3;
  49709. for (i = 0; i < nbfaces; i++) {
  49710. this.pickedParticles.push({ idx: idx, faceId: i });
  49711. }
  49712. }
  49713. };
  49714. // returns a shape array from positions array
  49715. SolidParticleSystem.prototype._posToShape = function (positions) {
  49716. var shape = [];
  49717. for (var i = 0; i < positions.length; i += 3) {
  49718. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  49719. }
  49720. return shape;
  49721. };
  49722. // returns a shapeUV array from a Vector4 uvs
  49723. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  49724. var shapeUV = [];
  49725. if (uvs) {
  49726. for (var i = 0; i < uvs.length; i++)
  49727. shapeUV.push(uvs[i]);
  49728. }
  49729. return shapeUV;
  49730. };
  49731. // adds a new particle object in the particles array
  49732. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  49733. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo));
  49734. };
  49735. /**
  49736. * Adds some particles to the SPS from the model shape. Returns the shape id.
  49737. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  49738. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  49739. * `nb` (positive integer) the number of particles to be created from this model
  49740. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  49741. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  49742. */
  49743. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  49744. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49745. var meshInd = mesh.getIndices();
  49746. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49747. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49748. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49749. var bbInfo;
  49750. if (this._particlesIntersect) {
  49751. bbInfo = mesh.getBoundingInfo();
  49752. }
  49753. var shape = this._posToShape(meshPos);
  49754. var shapeUV = this._uvsToShapeUV(meshUV);
  49755. var posfunc = options ? options.positionFunction : null;
  49756. var vtxfunc = options ? options.vertexFunction : null;
  49757. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  49758. // particles
  49759. var idx = this.nbParticles;
  49760. for (var i = 0; i < nb; i++) {
  49761. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  49762. if (this._updatable) {
  49763. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i, bbInfo);
  49764. }
  49765. this._index += shape.length;
  49766. idx++;
  49767. }
  49768. this.nbParticles += nb;
  49769. this._shapeCounter++;
  49770. return this._shapeCounter - 1;
  49771. };
  49772. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  49773. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  49774. this._resetCopy();
  49775. if (particle._model._positionFunction) {
  49776. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  49777. }
  49778. if (this._copy.rotationQuaternion) {
  49779. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49780. }
  49781. else {
  49782. this._yaw = this._copy.rotation.y;
  49783. this._pitch = this._copy.rotation.x;
  49784. this._roll = this._copy.rotation.z;
  49785. this._quaternionRotationYPR();
  49786. }
  49787. this._quaternionToRotationMatrix();
  49788. this._shape = particle._model._shape;
  49789. for (var pt = 0; pt < this._shape.length; pt++) {
  49790. this._vertex.x = this._shape[pt].x;
  49791. this._vertex.y = this._shape[pt].y;
  49792. this._vertex.z = this._shape[pt].z;
  49793. if (particle._model._vertexFunction) {
  49794. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  49795. }
  49796. this._vertex.x *= this._copy.scaling.x;
  49797. this._vertex.y *= this._copy.scaling.y;
  49798. this._vertex.z *= this._copy.scaling.z;
  49799. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49800. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  49801. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  49802. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  49803. }
  49804. particle.position.x = 0.0;
  49805. particle.position.y = 0.0;
  49806. particle.position.z = 0.0;
  49807. particle.rotation.x = 0.0;
  49808. particle.rotation.y = 0.0;
  49809. particle.rotation.z = 0.0;
  49810. particle.rotationQuaternion = null;
  49811. particle.scaling.x = 1.0;
  49812. particle.scaling.y = 1.0;
  49813. particle.scaling.z = 1.0;
  49814. };
  49815. /**
  49816. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  49817. */
  49818. SolidParticleSystem.prototype.rebuildMesh = function () {
  49819. for (var p = 0; p < this.particles.length; p++) {
  49820. this._rebuildParticle(this.particles[p]);
  49821. }
  49822. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49823. };
  49824. /**
  49825. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  49826. * This method calls `updateParticle()` for each particle of the SPS.
  49827. * For an animated SPS, it is usually called within the render loop.
  49828. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  49829. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  49830. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  49831. */
  49832. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  49833. if (start === void 0) { start = 0; }
  49834. if (end === void 0) { end = this.nbParticles - 1; }
  49835. if (update === void 0) { update = true; }
  49836. if (!this._updatable) {
  49837. return;
  49838. }
  49839. // custom beforeUpdate
  49840. this.beforeUpdateParticles(start, end, update);
  49841. this._cam_axisX.x = 1.0;
  49842. this._cam_axisX.y = 0.0;
  49843. this._cam_axisX.z = 0.0;
  49844. this._cam_axisY.x = 0.0;
  49845. this._cam_axisY.y = 1.0;
  49846. this._cam_axisY.z = 0.0;
  49847. this._cam_axisZ.x = 0.0;
  49848. this._cam_axisZ.y = 0.0;
  49849. this._cam_axisZ.z = 1.0;
  49850. // if the particles will always face the camera
  49851. if (this.billboard) {
  49852. // compute the camera position and un-rotate it by the current mesh rotation
  49853. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  49854. this._quaternionToRotationMatrix();
  49855. this._rotMatrix.invertToRef(this._invertMatrix);
  49856. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  49857. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  49858. this._cam_axisZ.normalize();
  49859. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  49860. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  49861. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  49862. this._cam_axisY.normalize();
  49863. this._cam_axisX.normalize();
  49864. }
  49865. }
  49866. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  49867. var idx = 0;
  49868. var index = 0;
  49869. var colidx = 0;
  49870. var colorIndex = 0;
  49871. var uvidx = 0;
  49872. var uvIndex = 0;
  49873. var pt = 0;
  49874. if (this._computeBoundingBox) {
  49875. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  49876. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  49877. }
  49878. // particle loop
  49879. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  49880. for (var p = start; p <= end; p++) {
  49881. this._particle = this.particles[p];
  49882. this._shape = this._particle._model._shape;
  49883. this._shapeUV = this._particle._model._shapeUV;
  49884. // call to custom user function to update the particle properties
  49885. this.updateParticle(this._particle);
  49886. if (this._particle.isVisible) {
  49887. // particle rotation matrix
  49888. if (this.billboard) {
  49889. this._particle.rotation.x = 0.0;
  49890. this._particle.rotation.y = 0.0;
  49891. }
  49892. if (this._computeParticleRotation || this.billboard) {
  49893. if (this._particle.rotationQuaternion) {
  49894. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49895. }
  49896. else {
  49897. this._yaw = this._particle.rotation.y;
  49898. this._pitch = this._particle.rotation.x;
  49899. this._roll = this._particle.rotation.z;
  49900. this._quaternionRotationYPR();
  49901. }
  49902. this._quaternionToRotationMatrix();
  49903. }
  49904. // particle vertex loop
  49905. for (pt = 0; pt < this._shape.length; pt++) {
  49906. idx = index + pt * 3;
  49907. colidx = colorIndex + pt * 4;
  49908. uvidx = uvIndex + pt * 2;
  49909. this._vertex.x = this._shape[pt].x;
  49910. this._vertex.y = this._shape[pt].y;
  49911. this._vertex.z = this._shape[pt].z;
  49912. if (this._computeParticleVertex) {
  49913. this.updateParticleVertex(this._particle, this._vertex, pt);
  49914. }
  49915. // positions
  49916. this._vertex.x *= this._particle.scaling.x;
  49917. this._vertex.y *= this._particle.scaling.y;
  49918. this._vertex.z *= this._particle.scaling.z;
  49919. 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];
  49920. 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;
  49921. 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;
  49922. 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;
  49923. 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;
  49924. 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;
  49925. 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;
  49926. if (this._computeBoundingBox) {
  49927. if (this._positions32[idx] < this._minimum.x) {
  49928. this._minimum.x = this._positions32[idx];
  49929. }
  49930. if (this._positions32[idx] > this._maximum.x) {
  49931. this._maximum.x = this._positions32[idx];
  49932. }
  49933. if (this._positions32[idx + 1] < this._minimum.y) {
  49934. this._minimum.y = this._positions32[idx + 1];
  49935. }
  49936. if (this._positions32[idx + 1] > this._maximum.y) {
  49937. this._maximum.y = this._positions32[idx + 1];
  49938. }
  49939. if (this._positions32[idx + 2] < this._minimum.z) {
  49940. this._minimum.z = this._positions32[idx + 2];
  49941. }
  49942. if (this._positions32[idx + 2] > this._maximum.z) {
  49943. this._maximum.z = this._positions32[idx + 2];
  49944. }
  49945. }
  49946. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  49947. if (!this._computeParticleVertex) {
  49948. this._normal.x = this._fixedNormal32[idx];
  49949. this._normal.y = this._fixedNormal32[idx + 1];
  49950. this._normal.z = this._fixedNormal32[idx + 2];
  49951. this._w = (this._normal.x * this._rotMatrix.m[3]) + (this._normal.y * this._rotMatrix.m[7]) + (this._normal.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  49952. 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]) / this._w;
  49953. 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]) / this._w;
  49954. 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]) / this._w;
  49955. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  49956. 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;
  49957. 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;
  49958. }
  49959. if (this._computeParticleColor) {
  49960. this._colors32[colidx] = this._particle.color.r;
  49961. this._colors32[colidx + 1] = this._particle.color.g;
  49962. this._colors32[colidx + 2] = this._particle.color.b;
  49963. this._colors32[colidx + 3] = this._particle.color.a;
  49964. }
  49965. if (this._computeParticleTexture) {
  49966. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49967. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49968. }
  49969. }
  49970. }
  49971. else {
  49972. for (pt = 0; pt < this._shape.length; pt++) {
  49973. idx = index + pt * 3;
  49974. colidx = colorIndex + pt * 4;
  49975. uvidx = uvIndex + pt * 2;
  49976. this._positions32[idx] = this._camera.position.x;
  49977. this._positions32[idx + 1] = this._camera.position.y;
  49978. this._positions32[idx + 2] = this._camera.position.z;
  49979. this._normals32[idx] = 0.0;
  49980. this._normals32[idx + 1] = 0.0;
  49981. this._normals32[idx + 2] = 0.0;
  49982. if (this._computeParticleColor) {
  49983. this._colors32[colidx] = this._particle.color.r;
  49984. this._colors32[colidx + 1] = this._particle.color.g;
  49985. this._colors32[colidx + 2] = this._particle.color.b;
  49986. this._colors32[colidx + 3] = this._particle.color.a;
  49987. }
  49988. if (this._computeParticleTexture) {
  49989. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49990. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49991. }
  49992. }
  49993. }
  49994. // if the particle intersections must be computed : update the bbInfo
  49995. if (this._particlesIntersect) {
  49996. var bInfo = this._particle._boundingInfo;
  49997. var bBox = bInfo.boundingBox;
  49998. var bSphere = bInfo.boundingSphere;
  49999. if (!this._bSphereOnly) {
  50000. // place, scale and rotate the particle bbox within the SPS local system, then update it
  50001. for (var b = 0; b < bBox.vectors.length; b++) {
  50002. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  50003. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  50004. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  50005. 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];
  50006. 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;
  50007. 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;
  50008. 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;
  50009. 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;
  50010. 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;
  50011. 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;
  50012. }
  50013. bBox._update(this.mesh._worldMatrix);
  50014. }
  50015. // place and scale the particle bouding sphere in the SPS local system, then update it
  50016. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  50017. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  50018. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  50019. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  50020. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  50021. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  50022. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  50023. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  50024. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  50025. 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));
  50026. bSphere._update(this.mesh._worldMatrix);
  50027. }
  50028. // increment indexes for the next particle
  50029. index = idx + 3;
  50030. colorIndex = colidx + 4;
  50031. uvIndex = uvidx + 2;
  50032. }
  50033. // if the VBO must be updated
  50034. if (update) {
  50035. if (this._computeParticleColor) {
  50036. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  50037. }
  50038. if (this._computeParticleTexture) {
  50039. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  50040. }
  50041. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50042. if (!this.mesh.areNormalsFrozen) {
  50043. if (this._computeParticleVertex) {
  50044. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  50045. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  50046. for (var i = 0; i < this._normals32.length; i++) {
  50047. this._fixedNormal32[i] = this._normals32[i];
  50048. }
  50049. }
  50050. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  50051. }
  50052. }
  50053. if (this._computeBoundingBox) {
  50054. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  50055. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  50056. }
  50057. this.afterUpdateParticles(start, end, update);
  50058. };
  50059. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  50060. this._halfroll = this._roll * 0.5;
  50061. this._halfpitch = this._pitch * 0.5;
  50062. this._halfyaw = this._yaw * 0.5;
  50063. this._sinRoll = Math.sin(this._halfroll);
  50064. this._cosRoll = Math.cos(this._halfroll);
  50065. this._sinPitch = Math.sin(this._halfpitch);
  50066. this._cosPitch = Math.cos(this._halfpitch);
  50067. this._sinYaw = Math.sin(this._halfyaw);
  50068. this._cosYaw = Math.cos(this._halfyaw);
  50069. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  50070. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  50071. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  50072. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  50073. };
  50074. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  50075. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  50076. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  50077. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  50078. this._rotMatrix.m[3] = 0;
  50079. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  50080. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  50081. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  50082. this._rotMatrix.m[7] = 0;
  50083. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  50084. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  50085. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  50086. this._rotMatrix.m[11] = 0;
  50087. this._rotMatrix.m[12] = 0;
  50088. this._rotMatrix.m[13] = 0;
  50089. this._rotMatrix.m[14] = 0;
  50090. this._rotMatrix.m[15] = 1.0;
  50091. };
  50092. /**
  50093. * Disposes the SPS
  50094. */
  50095. SolidParticleSystem.prototype.dispose = function () {
  50096. this.mesh.dispose();
  50097. this.vars = null;
  50098. // drop references to internal big arrays for the GC
  50099. this._positions = null;
  50100. this._indices = null;
  50101. this._normals = null;
  50102. this._uvs = null;
  50103. this._colors = null;
  50104. this._positions32 = null;
  50105. this._normals32 = null;
  50106. this._fixedNormal32 = null;
  50107. this._uvs32 = null;
  50108. this._colors32 = null;
  50109. this.pickedParticles = null;
  50110. };
  50111. /**
  50112. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  50113. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50114. */
  50115. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  50116. if (!this._isVisibilityBoxLocked) {
  50117. this.mesh.refreshBoundingInfo();
  50118. }
  50119. };
  50120. /**
  50121. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  50122. * @param size the size (float) of the visibility box
  50123. * note : this doesn't lock the SPS mesh bounding box.
  50124. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50125. */
  50126. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  50127. var vis = size / 2;
  50128. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  50129. };
  50130. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  50131. // getter and setter
  50132. get: function () {
  50133. return this._alwaysVisible;
  50134. },
  50135. /**
  50136. * Sets the SPS as always visible or not
  50137. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50138. */
  50139. set: function (val) {
  50140. this._alwaysVisible = val;
  50141. this.mesh.alwaysSelectAsActiveMesh = val;
  50142. },
  50143. enumerable: true,
  50144. configurable: true
  50145. });
  50146. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  50147. get: function () {
  50148. return this._isVisibilityBoxLocked;
  50149. },
  50150. /**
  50151. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  50152. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50153. */
  50154. set: function (val) {
  50155. this._isVisibilityBoxLocked = val;
  50156. this.mesh.getBoundingInfo().isLocked = val;
  50157. },
  50158. enumerable: true,
  50159. configurable: true
  50160. });
  50161. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  50162. // getters
  50163. get: function () {
  50164. return this._computeParticleRotation;
  50165. },
  50166. // Optimizer setters
  50167. /**
  50168. * Tells to `setParticles()` to compute the particle rotations or not.
  50169. * Default value : true. The SPS is faster when it's set to false.
  50170. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  50171. */
  50172. set: function (val) {
  50173. this._computeParticleRotation = val;
  50174. },
  50175. enumerable: true,
  50176. configurable: true
  50177. });
  50178. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  50179. get: function () {
  50180. return this._computeParticleColor;
  50181. },
  50182. /**
  50183. * Tells to `setParticles()` to compute the particle colors or not.
  50184. * Default value : true. The SPS is faster when it's set to false.
  50185. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  50186. */
  50187. set: function (val) {
  50188. this._computeParticleColor = val;
  50189. },
  50190. enumerable: true,
  50191. configurable: true
  50192. });
  50193. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  50194. get: function () {
  50195. return this._computeParticleTexture;
  50196. },
  50197. /**
  50198. * Tells to `setParticles()` to compute the particle textures or not.
  50199. * Default value : true. The SPS is faster when it's set to false.
  50200. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  50201. */
  50202. set: function (val) {
  50203. this._computeParticleTexture = val;
  50204. },
  50205. enumerable: true,
  50206. configurable: true
  50207. });
  50208. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  50209. get: function () {
  50210. return this._computeParticleVertex;
  50211. },
  50212. /**
  50213. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  50214. * Default value : false. The SPS is faster when it's set to false.
  50215. * Note : the particle custom vertex positions aren't stored values.
  50216. */
  50217. set: function (val) {
  50218. this._computeParticleVertex = val;
  50219. },
  50220. enumerable: true,
  50221. configurable: true
  50222. });
  50223. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  50224. get: function () {
  50225. return this._computeBoundingBox;
  50226. },
  50227. /**
  50228. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  50229. */
  50230. set: function (val) {
  50231. this._computeBoundingBox = val;
  50232. },
  50233. enumerable: true,
  50234. configurable: true
  50235. });
  50236. // =======================================================================
  50237. // Particle behavior logic
  50238. // these following methods may be overwritten by the user to fit his needs
  50239. /**
  50240. * This function does nothing. It may be overwritten to set all the particle first values.
  50241. * The SPS doesn't call this function, you may have to call it by your own.
  50242. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50243. */
  50244. SolidParticleSystem.prototype.initParticles = function () {
  50245. };
  50246. /**
  50247. * This function does nothing. It may be overwritten to recycle a particle.
  50248. * The SPS doesn't call this function, you may have to call it by your own.
  50249. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50250. */
  50251. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  50252. return particle;
  50253. };
  50254. /**
  50255. * Updates a particle : this function should be overwritten by the user.
  50256. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  50257. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50258. * ex : just set a particle position or velocity and recycle conditions
  50259. */
  50260. SolidParticleSystem.prototype.updateParticle = function (particle) {
  50261. return particle;
  50262. };
  50263. /**
  50264. * Updates a vertex of a particle : it can be overwritten by the user.
  50265. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  50266. * @param particle the current particle
  50267. * @param vertex the current index of the current particle
  50268. * @param pt the index of the current vertex in the particle shape
  50269. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  50270. * ex : just set a vertex particle position
  50271. */
  50272. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  50273. return vertex;
  50274. };
  50275. /**
  50276. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  50277. * This does nothing and may be overwritten by the user.
  50278. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50279. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50280. * @param update the boolean update value actually passed to setParticles()
  50281. */
  50282. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  50283. };
  50284. /**
  50285. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  50286. * This will be passed three parameters.
  50287. * This does nothing and may be overwritten by the user.
  50288. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50289. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50290. * @param update the boolean update value actually passed to setParticles()
  50291. */
  50292. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  50293. };
  50294. return SolidParticleSystem;
  50295. }());
  50296. BABYLON.SolidParticleSystem = SolidParticleSystem;
  50297. })(BABYLON || (BABYLON = {}));
  50298. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  50299. var BABYLON;
  50300. (function (BABYLON) {
  50301. var Internals;
  50302. (function (Internals) {
  50303. var FileFaceOrientation = (function () {
  50304. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  50305. this.name = name;
  50306. this.worldAxisForNormal = worldAxisForNormal;
  50307. this.worldAxisForFileX = worldAxisForFileX;
  50308. this.worldAxisForFileY = worldAxisForFileY;
  50309. }
  50310. return FileFaceOrientation;
  50311. }());
  50312. ;
  50313. /**
  50314. * Helper class dealing with the extraction of spherical polynomial dataArray
  50315. * from a cube map.
  50316. */
  50317. var CubeMapToSphericalPolynomialTools = (function () {
  50318. function CubeMapToSphericalPolynomialTools() {
  50319. }
  50320. /**
  50321. * Converts a cubemap to the according Spherical Polynomial data.
  50322. * This extracts the first 3 orders only as they are the only one used in the lighting.
  50323. *
  50324. * @param cubeInfo The Cube map to extract the information from.
  50325. * @return The Spherical Polynomial data.
  50326. */
  50327. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  50328. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  50329. var totalSolidAngle = 0.0;
  50330. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  50331. var du = 2.0 / cubeInfo.size;
  50332. var dv = du;
  50333. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  50334. var minUV = du * 0.5 - 1.0;
  50335. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50336. var fileFace = this.FileFaces[faceIndex];
  50337. var dataArray = cubeInfo[fileFace.name];
  50338. var v = minUV;
  50339. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  50340. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  50341. // Because SP is still linear, so summation is fine in that basis.
  50342. for (var y = 0; y < cubeInfo.size; y++) {
  50343. var u = minUV;
  50344. for (var x = 0; x < cubeInfo.size; x++) {
  50345. // World direction (not normalised)
  50346. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  50347. worldDirection.normalize();
  50348. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  50349. if (1) {
  50350. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  50351. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  50352. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  50353. var color = new BABYLON.Color3(r, g, b);
  50354. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50355. }
  50356. else {
  50357. if (faceIndex == 0) {
  50358. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50359. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50360. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50361. }
  50362. else if (faceIndex == 1) {
  50363. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50364. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50365. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50366. }
  50367. else if (faceIndex == 2) {
  50368. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50369. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50370. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50371. }
  50372. else if (faceIndex == 3) {
  50373. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50374. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50375. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50376. }
  50377. else if (faceIndex == 4) {
  50378. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50379. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50380. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50381. }
  50382. else if (faceIndex == 5) {
  50383. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50384. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50385. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50386. }
  50387. 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]);
  50388. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50389. }
  50390. totalSolidAngle += deltaSolidAngle;
  50391. u += du;
  50392. }
  50393. v += dv;
  50394. }
  50395. }
  50396. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  50397. var correction = correctSolidAngle / totalSolidAngle;
  50398. sphericalHarmonics.scale(correction);
  50399. // Additionally scale by pi -- audit needed
  50400. sphericalHarmonics.scale(1.0 / Math.PI);
  50401. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  50402. };
  50403. return CubeMapToSphericalPolynomialTools;
  50404. }());
  50405. CubeMapToSphericalPolynomialTools.FileFaces = [
  50406. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  50407. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  50408. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  50409. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  50410. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  50411. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  50412. ];
  50413. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  50414. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50415. })(BABYLON || (BABYLON = {}));
  50416. //# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
  50417. var BABYLON;
  50418. (function (BABYLON) {
  50419. var Internals;
  50420. (function (Internals) {
  50421. /**
  50422. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  50423. */
  50424. var PanoramaToCubeMapTools = (function () {
  50425. function PanoramaToCubeMapTools() {
  50426. }
  50427. /**
  50428. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  50429. *
  50430. * @param float32Array The source data.
  50431. * @param inputWidth The width of the input panorama.
  50432. * @param inputhHeight The height of the input panorama.
  50433. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  50434. * @return The cubemap data
  50435. */
  50436. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  50437. if (!float32Array) {
  50438. throw "ConvertPanoramaToCubemap: input cannot be null";
  50439. }
  50440. if (float32Array.length != inputWidth * inputHeight * 3) {
  50441. throw "ConvertPanoramaToCubemap: input size is wrong";
  50442. }
  50443. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  50444. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  50445. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  50446. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  50447. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  50448. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  50449. return {
  50450. front: textureFront,
  50451. back: textureBack,
  50452. left: textureLeft,
  50453. right: textureRight,
  50454. up: textureUp,
  50455. down: textureDown,
  50456. size: size
  50457. };
  50458. };
  50459. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  50460. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  50461. var textureArray = new Float32Array(buffer);
  50462. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  50463. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  50464. var dy = 1 / texSize;
  50465. var fy = 0;
  50466. for (var y = 0; y < texSize; y++) {
  50467. var xv1 = faceData[0];
  50468. var xv2 = faceData[2];
  50469. for (var x = 0; x < texSize; x++) {
  50470. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  50471. v.normalize();
  50472. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  50473. // 3 channels per pixels
  50474. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  50475. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  50476. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  50477. xv1 = xv1.add(rotDX1);
  50478. xv2 = xv2.add(rotDX2);
  50479. }
  50480. fy += dy;
  50481. }
  50482. return textureArray;
  50483. };
  50484. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  50485. var theta = Math.atan2(vDir.z, vDir.x);
  50486. var phi = Math.acos(vDir.y);
  50487. while (theta < -Math.PI)
  50488. theta += 2 * Math.PI;
  50489. while (theta > Math.PI)
  50490. theta -= 2 * Math.PI;
  50491. var dx = theta / Math.PI;
  50492. var dy = phi / Math.PI;
  50493. // recenter.
  50494. dx = dx * 0.5 + 0.5;
  50495. var px = Math.round(dx * inputWidth);
  50496. if (px < 0)
  50497. px = 0;
  50498. else if (px >= inputWidth)
  50499. px = inputWidth - 1;
  50500. var py = Math.round(dy * inputHeight);
  50501. if (py < 0)
  50502. py = 0;
  50503. else if (py >= inputHeight)
  50504. py = inputHeight - 1;
  50505. var inputY = (inputHeight - py - 1);
  50506. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  50507. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  50508. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  50509. return {
  50510. r: r,
  50511. g: g,
  50512. b: b
  50513. };
  50514. };
  50515. return PanoramaToCubeMapTools;
  50516. }());
  50517. PanoramaToCubeMapTools.FACE_FRONT = [
  50518. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50519. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50520. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50521. new BABYLON.Vector3(1.0, 1.0, -1.0)
  50522. ];
  50523. PanoramaToCubeMapTools.FACE_BACK = [
  50524. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50525. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50526. new BABYLON.Vector3(1.0, 1.0, 1.0),
  50527. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  50528. ];
  50529. PanoramaToCubeMapTools.FACE_RIGHT = [
  50530. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50531. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50532. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50533. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50534. ];
  50535. PanoramaToCubeMapTools.FACE_LEFT = [
  50536. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50537. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50538. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50539. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  50540. ];
  50541. PanoramaToCubeMapTools.FACE_DOWN = [
  50542. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50543. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50544. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50545. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50546. ];
  50547. PanoramaToCubeMapTools.FACE_UP = [
  50548. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50549. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50550. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50551. new BABYLON.Vector3(1.0, -1.0, -1.0)
  50552. ];
  50553. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  50554. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50555. })(BABYLON || (BABYLON = {}));
  50556. //# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
  50557. var BABYLON;
  50558. (function (BABYLON) {
  50559. var Internals;
  50560. (function (Internals) {
  50561. ;
  50562. /**
  50563. * This groups tools to convert HDR texture to native colors array.
  50564. */
  50565. var HDRTools = (function () {
  50566. function HDRTools() {
  50567. }
  50568. HDRTools.Ldexp = function (mantissa, exponent) {
  50569. if (exponent > 1023) {
  50570. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  50571. }
  50572. if (exponent < -1074) {
  50573. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  50574. }
  50575. return mantissa * Math.pow(2, exponent);
  50576. };
  50577. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  50578. if (exponent > 0) {
  50579. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  50580. float32array[index + 0] = red * exponent;
  50581. float32array[index + 1] = green * exponent;
  50582. float32array[index + 2] = blue * exponent;
  50583. }
  50584. else {
  50585. float32array[index + 0] = 0;
  50586. float32array[index + 1] = 0;
  50587. float32array[index + 2] = 0;
  50588. }
  50589. };
  50590. HDRTools.readStringLine = function (uint8array, startIndex) {
  50591. var line = "";
  50592. var character = "";
  50593. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  50594. character = String.fromCharCode(uint8array[i]);
  50595. if (character == "\n") {
  50596. break;
  50597. }
  50598. line += character;
  50599. }
  50600. return line;
  50601. };
  50602. /**
  50603. * Reads header information from an RGBE texture stored in a native array.
  50604. * More information on this format are available here:
  50605. * https://en.wikipedia.org/wiki/RGBE_image_format
  50606. *
  50607. * @param uint8array The binary file stored in native array.
  50608. * @return The header information.
  50609. */
  50610. HDRTools.RGBE_ReadHeader = function (uint8array) {
  50611. var height = 0;
  50612. var width = 0;
  50613. var line = this.readStringLine(uint8array, 0);
  50614. if (line[0] != '#' || line[1] != '?') {
  50615. throw "Bad HDR Format.";
  50616. }
  50617. var endOfHeader = false;
  50618. var findFormat = false;
  50619. var lineIndex = 0;
  50620. do {
  50621. lineIndex += (line.length + 1);
  50622. line = this.readStringLine(uint8array, lineIndex);
  50623. if (line == "FORMAT=32-bit_rle_rgbe") {
  50624. findFormat = true;
  50625. }
  50626. else if (line.length == 0) {
  50627. endOfHeader = true;
  50628. }
  50629. } while (!endOfHeader);
  50630. if (!findFormat) {
  50631. throw "HDR Bad header format, unsupported FORMAT";
  50632. }
  50633. lineIndex += (line.length + 1);
  50634. line = this.readStringLine(uint8array, lineIndex);
  50635. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  50636. var match = sizeRegexp.exec(line);
  50637. // TODO. Support +Y and -X if needed.
  50638. if (match.length < 3) {
  50639. throw "HDR Bad header format, no size";
  50640. }
  50641. width = parseInt(match[2]);
  50642. height = parseInt(match[1]);
  50643. if (width < 8 || width > 0x7fff) {
  50644. throw "HDR Bad header format, unsupported size";
  50645. }
  50646. lineIndex += (line.length + 1);
  50647. return {
  50648. height: height,
  50649. width: width,
  50650. dataPosition: lineIndex
  50651. };
  50652. };
  50653. /**
  50654. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  50655. * This RGBE texture needs to store the information as a panorama.
  50656. *
  50657. * More information on this format are available here:
  50658. * https://en.wikipedia.org/wiki/RGBE_image_format
  50659. *
  50660. * @param buffer The binary file stored in an array buffer.
  50661. * @param size The expected size of the extracted cubemap.
  50662. * @return The Cube Map information.
  50663. */
  50664. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  50665. var uint8array = new Uint8Array(buffer);
  50666. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  50667. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  50668. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  50669. return cubeMapData;
  50670. };
  50671. /**
  50672. * Returns the pixels data extracted from an RGBE texture.
  50673. * This pixels will be stored left to right up to down in the R G B order in one array.
  50674. *
  50675. * More information on this format are available here:
  50676. * https://en.wikipedia.org/wiki/RGBE_image_format
  50677. *
  50678. * @param uint8array The binary file stored in an array buffer.
  50679. * @param hdrInfo The header information of the file.
  50680. * @return The pixels data in RGB right to left up to down order.
  50681. */
  50682. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  50683. // Keep for multi format supports.
  50684. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  50685. };
  50686. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  50687. var num_scanlines = hdrInfo.height;
  50688. var scanline_width = hdrInfo.width;
  50689. var a, b, c, d, count;
  50690. var dataIndex = hdrInfo.dataPosition;
  50691. var index = 0, endIndex = 0, i = 0;
  50692. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  50693. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  50694. // 3 channels of 4 bytes per pixel in float.
  50695. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  50696. var resultArray = new Float32Array(resultBuffer);
  50697. // read in each successive scanline
  50698. while (num_scanlines > 0) {
  50699. a = uint8array[dataIndex++];
  50700. b = uint8array[dataIndex++];
  50701. c = uint8array[dataIndex++];
  50702. d = uint8array[dataIndex++];
  50703. if (a != 2 || b != 2 || (c & 0x80)) {
  50704. // this file is not run length encoded
  50705. throw "HDR Bad header format, not RLE";
  50706. }
  50707. if (((c << 8) | d) != scanline_width) {
  50708. throw "HDR Bad header format, wrong scan line width";
  50709. }
  50710. index = 0;
  50711. // read each of the four channels for the scanline into the buffer
  50712. for (i = 0; i < 4; i++) {
  50713. endIndex = (i + 1) * scanline_width;
  50714. while (index < endIndex) {
  50715. a = uint8array[dataIndex++];
  50716. b = uint8array[dataIndex++];
  50717. if (a > 128) {
  50718. // a run of the same value
  50719. count = a - 128;
  50720. if ((count == 0) || (count > endIndex - index)) {
  50721. throw "HDR Bad Format, bad scanline data (run)";
  50722. }
  50723. while (count-- > 0) {
  50724. scanLineArray[index++] = b;
  50725. }
  50726. }
  50727. else {
  50728. // a non-run
  50729. count = a;
  50730. if ((count == 0) || (count > endIndex - index)) {
  50731. throw "HDR Bad Format, bad scanline data (non-run)";
  50732. }
  50733. scanLineArray[index++] = b;
  50734. if (--count > 0) {
  50735. for (var j = 0; j < count; j++) {
  50736. scanLineArray[index++] = uint8array[dataIndex++];
  50737. }
  50738. }
  50739. }
  50740. }
  50741. }
  50742. // now convert data from buffer into floats
  50743. for (i = 0; i < scanline_width; i++) {
  50744. a = scanLineArray[i];
  50745. b = scanLineArray[i + scanline_width];
  50746. c = scanLineArray[i + 2 * scanline_width];
  50747. d = scanLineArray[i + 3 * scanline_width];
  50748. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  50749. }
  50750. num_scanlines--;
  50751. }
  50752. return resultArray;
  50753. };
  50754. return HDRTools;
  50755. }());
  50756. Internals.HDRTools = HDRTools;
  50757. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50758. })(BABYLON || (BABYLON = {}));
  50759. //# sourceMappingURL=babylon.tools.hdr.js.map
  50760. //_______________________________________________________________
  50761. // Extracted from CubeMapGen:
  50762. // https://code.google.com/archive/p/cubemapgen/
  50763. //
  50764. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50765. //_______________________________________________________________
  50766. var BABYLON;
  50767. (function (BABYLON) {
  50768. var Internals;
  50769. (function (Internals) {
  50770. /**
  50771. * The bounding box information used during the conversion process.
  50772. */
  50773. var CMGBoundinBox = (function () {
  50774. function CMGBoundinBox() {
  50775. this.min = new BABYLON.Vector3(0, 0, 0);
  50776. this.max = new BABYLON.Vector3(0, 0, 0);
  50777. this.clear();
  50778. }
  50779. CMGBoundinBox.prototype.clear = function () {
  50780. this.min.x = CMGBoundinBox.MAX;
  50781. this.min.y = CMGBoundinBox.MAX;
  50782. this.min.z = CMGBoundinBox.MAX;
  50783. this.max.x = CMGBoundinBox.MIN;
  50784. this.max.y = CMGBoundinBox.MIN;
  50785. this.max.z = CMGBoundinBox.MIN;
  50786. };
  50787. CMGBoundinBox.prototype.augment = function (x, y, z) {
  50788. this.min.x = Math.min(this.min.x, x);
  50789. this.min.y = Math.min(this.min.y, y);
  50790. this.min.z = Math.min(this.min.z, z);
  50791. this.max.x = Math.max(this.max.x, x);
  50792. this.max.y = Math.max(this.max.y, y);
  50793. this.max.z = Math.max(this.max.z, z);
  50794. };
  50795. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  50796. this.min.x = Math.max(this.min.x, x);
  50797. this.min.y = Math.max(this.min.y, y);
  50798. this.min.z = Math.max(this.min.z, z);
  50799. };
  50800. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  50801. this.max.x = Math.min(this.max.x, x);
  50802. this.max.y = Math.min(this.max.y, y);
  50803. this.max.z = Math.min(this.max.z, z);
  50804. };
  50805. CMGBoundinBox.prototype.empty = function () {
  50806. if ((this.min.x > this.max.y) ||
  50807. (this.min.y > this.max.y) ||
  50808. (this.min.z > this.max.y)) {
  50809. return true;
  50810. }
  50811. else {
  50812. return false;
  50813. }
  50814. };
  50815. return CMGBoundinBox;
  50816. }());
  50817. CMGBoundinBox.MAX = Number.MAX_VALUE;
  50818. CMGBoundinBox.MIN = Number.MIN_VALUE;
  50819. /**
  50820. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  50821. * required by the glossinees of a material.
  50822. *
  50823. * This only supports the cosine drop power as well as Warp fixup generation method.
  50824. *
  50825. * This is using the process from CubeMapGen described here:
  50826. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50827. */
  50828. var PMREMGenerator = (function () {
  50829. /**
  50830. * Constructor of the generator.
  50831. *
  50832. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  50833. * @param inputSize The size of the cubemap faces
  50834. * @param outputSize The size of the output cubemap faces
  50835. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  50836. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  50837. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  50838. * @param specularPower The max specular level of the desired cubemap
  50839. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  50840. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  50841. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  50842. */
  50843. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  50844. this.input = input;
  50845. this.inputSize = inputSize;
  50846. this.outputSize = outputSize;
  50847. this.maxNumMipLevels = maxNumMipLevels;
  50848. this.numChannels = numChannels;
  50849. this.isFloat = isFloat;
  50850. this.specularPower = specularPower;
  50851. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  50852. this.excludeBase = excludeBase;
  50853. this.fixup = fixup;
  50854. this._outputSurface = [];
  50855. this._numMipLevels = 0;
  50856. }
  50857. /**
  50858. * Launches the filter process and return the result.
  50859. *
  50860. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  50861. */
  50862. PMREMGenerator.prototype.filterCubeMap = function () {
  50863. // Init cubemap processor
  50864. this.init();
  50865. // Filters the cubemap
  50866. this.filterCubeMapMipChain();
  50867. // Returns the filtered mips.
  50868. return this._outputSurface;
  50869. };
  50870. PMREMGenerator.prototype.init = function () {
  50871. var i;
  50872. var j;
  50873. var mipLevelSize;
  50874. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  50875. if (this.maxNumMipLevels == 0) {
  50876. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  50877. }
  50878. //first miplevel size
  50879. mipLevelSize = this.outputSize;
  50880. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  50881. for (j = 0; j < this.maxNumMipLevels; j++) {
  50882. this._outputSurface.length++;
  50883. this._outputSurface[j] = [];
  50884. //Iterate over faces for output images
  50885. for (i = 0; i < 6; i++) {
  50886. this._outputSurface[j].length++;
  50887. // Initializes a new array for the output.
  50888. if (this.isFloat) {
  50889. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  50890. }
  50891. else {
  50892. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  50893. }
  50894. }
  50895. //next mip level is half size
  50896. mipLevelSize >>= 1;
  50897. this._numMipLevels++;
  50898. //terminate if mip chain becomes too small
  50899. if (mipLevelSize == 0) {
  50900. this.maxNumMipLevels = j;
  50901. return;
  50902. }
  50903. }
  50904. };
  50905. //--------------------------------------------------------------------------------------
  50906. //Cube map filtering and mip chain generation.
  50907. // the cube map filtereing is specified using a number of parameters:
  50908. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  50909. // indicates the region of the hemisphere to filter over for each tap.
  50910. //
  50911. // Note that the top mip level is also a filtered version of the original input images
  50912. // as well in order to create mip chains for diffuse environment illumination.
  50913. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  50914. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  50915. //
  50916. // Then the mip angle used to genreate the next level of the mip chain from the first level
  50917. // is a_InitialMipAngle
  50918. //
  50919. // The angle for the subsequent levels of the mip chain are specified by their parents
  50920. // filtering angle and a per-level scale and bias
  50921. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  50922. //
  50923. //--------------------------------------------------------------------------------------
  50924. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  50925. // First, take count of the lighting model to modify SpecularPower
  50926. // 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;
  50927. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  50928. //Cone angle start (for generating subsequent mip levels)
  50929. var currentSpecularPower = this.specularPower;
  50930. //Build filter lookup tables based on the source miplevel size
  50931. this.precomputeFilterLookupTables(this.inputSize);
  50932. // Note that we need to filter the first level before generating mipmap
  50933. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  50934. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  50935. // TODO : Write a function to copy and scale the base mipmap in output
  50936. // I am just lazy here and just put a high specular power value, and do some if.
  50937. if (this.excludeBase && (levelIndex == 0)) {
  50938. // 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).
  50939. currentSpecularPower = 100000.0;
  50940. }
  50941. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  50942. var srcCubeImage = this.input;
  50943. var dstCubeImage = this._outputSurface[levelIndex];
  50944. var dstSize = this.outputSize >> levelIndex;
  50945. // Compute required angle.
  50946. var angle = this.getBaseFilterAngle(currentSpecularPower);
  50947. // filter cube surfaces
  50948. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  50949. // fix seams
  50950. if (this.fixup) {
  50951. this.fixupCubeEdges(dstCubeImage, dstSize);
  50952. }
  50953. // Decrease the specular power to generate the mipmap chain
  50954. // TODO : Use another method for Exclude (see first comment at start of the function
  50955. if (this.excludeBase && (levelIndex == 0)) {
  50956. currentSpecularPower = this.specularPower;
  50957. }
  50958. currentSpecularPower *= this.cosinePowerDropPerMip;
  50959. }
  50960. };
  50961. //--------------------------------------------------------------------------------------
  50962. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  50963. // It allow to optimize the texel to access base on the specular power.
  50964. //--------------------------------------------------------------------------------------
  50965. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  50966. // We want to find the alpha such that:
  50967. // cos(alpha)^cosinePower = epsilon
  50968. // That's: acos(epsilon^(1/cosinePower))
  50969. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  50970. var angle = 180.0;
  50971. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  50972. angle *= 180.0 / Math.PI; // Convert to degree
  50973. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  50974. return angle;
  50975. };
  50976. //--------------------------------------------------------------------------------------
  50977. //Builds the following lookup tables prior to filtering:
  50978. // -normalizer cube map
  50979. // -tap weight lookup table
  50980. //
  50981. //--------------------------------------------------------------------------------------
  50982. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  50983. var srcTexelAngle;
  50984. var iCubeFace;
  50985. //clear pre-existing normalizer cube map
  50986. this._normCubeMap = [];
  50987. //Normalized vectors per cubeface and per-texel solid angle
  50988. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  50989. };
  50990. //--------------------------------------------------------------------------------------
  50991. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  50992. //
  50993. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  50994. //
  50995. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  50996. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  50997. // below
  50998. //--------------------------------------------------------------------------------------
  50999. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  51000. var iCubeFace;
  51001. var u;
  51002. var v;
  51003. //iterate over cube faces
  51004. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51005. //First three channels for norm cube, and last channel for solid angle
  51006. this._normCubeMap.push(new Float32Array(size * size * 4));
  51007. //fast texture walk, build normalizer cube map
  51008. var facesData = this.input[iCubeFace];
  51009. for (v = 0; v < size; v++) {
  51010. for (u = 0; u < size; u++) {
  51011. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  51012. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  51013. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  51014. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  51015. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  51016. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  51017. }
  51018. }
  51019. }
  51020. };
  51021. //--------------------------------------------------------------------------------------
  51022. // Convert cubemap face texel coordinates and face idx to 3D vector
  51023. // note the U and V coords are integer coords and range from 0 to size-1
  51024. // this routine can be used to generate a normalizer cube map
  51025. //--------------------------------------------------------------------------------------
  51026. // SL BEGIN
  51027. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  51028. var nvcU;
  51029. var nvcV;
  51030. var tempVec;
  51031. // Change from original AMD code
  51032. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  51033. // + 0.5f is for texel center addressing
  51034. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  51035. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  51036. // warp fixup
  51037. if (fixup && size > 1) {
  51038. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  51039. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  51040. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  51041. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  51042. }
  51043. // Get current vector
  51044. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  51045. // U contribution
  51046. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  51047. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  51048. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  51049. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  51050. // V contribution and Sum
  51051. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  51052. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  51053. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  51054. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  51055. //add face axis
  51056. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  51057. PMREMGenerator._vectorTemp.x += faceAxis[0];
  51058. PMREMGenerator._vectorTemp.y += faceAxis[1];
  51059. PMREMGenerator._vectorTemp.z += faceAxis[2];
  51060. //normalize vector
  51061. PMREMGenerator._vectorTemp.normalize();
  51062. return PMREMGenerator._vectorTemp;
  51063. };
  51064. //--------------------------------------------------------------------------------------
  51065. // Convert 3D vector to cubemap face texel coordinates and face idx
  51066. // note the U and V coords are integer coords and range from 0 to size-1
  51067. // this routine can be used to generate a normalizer cube map
  51068. //
  51069. // returns face IDX and texel coords
  51070. //--------------------------------------------------------------------------------------
  51071. // SL BEGIN
  51072. /*
  51073. Mapping Texture Coordinates to Cube Map Faces
  51074. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  51075. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  51076. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  51077. map arrangement in Pixar's RenderMan package.
  51078. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  51079. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  51080. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  51081. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  51082. the major axis direction). The target column in the table below explains how the major axis direction
  51083. maps to the 2D image of a particular cube map target.
  51084. major axis
  51085. direction target sc tc ma
  51086. ---------- --------------------------------- --- --- ---
  51087. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  51088. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  51089. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  51090. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  51091. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  51092. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  51093. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  51094. an updated (s,t) is calculated as follows
  51095. s = ( sc/|ma| + 1 ) / 2
  51096. t = ( tc/|ma| + 1 ) / 2
  51097. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  51098. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  51099. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  51100. */
  51101. // Note this method return U and V in range from 0 to size-1
  51102. // SL END
  51103. // Store the information in vector3 for convenience (faceindex, u, v)
  51104. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  51105. var maxCoord;
  51106. var faceIdx;
  51107. //absolute value 3
  51108. var absX = Math.abs(x);
  51109. var absY = Math.abs(y);
  51110. var absZ = Math.abs(z);
  51111. if (absX >= absY && absX >= absZ) {
  51112. maxCoord = absX;
  51113. if (x >= 0) {
  51114. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  51115. }
  51116. else {
  51117. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51118. }
  51119. }
  51120. else if (absY >= absX && absY >= absZ) {
  51121. maxCoord = absY;
  51122. if (y >= 0) {
  51123. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51124. }
  51125. else {
  51126. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51127. }
  51128. }
  51129. else {
  51130. maxCoord = absZ;
  51131. if (z >= 0) {
  51132. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51133. }
  51134. else {
  51135. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51136. }
  51137. }
  51138. //divide through by max coord so face vector lies on cube face
  51139. var scale = 1 / maxCoord;
  51140. x *= scale;
  51141. y *= scale;
  51142. z *= scale;
  51143. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  51144. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  51145. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  51146. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  51147. // Modify original AMD code to return value from 0 to Size - 1
  51148. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  51149. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  51150. PMREMGenerator._vectorTemp.x = faceIdx;
  51151. PMREMGenerator._vectorTemp.y = u;
  51152. PMREMGenerator._vectorTemp.z = v;
  51153. return PMREMGenerator._vectorTemp;
  51154. };
  51155. //--------------------------------------------------------------------------------------
  51156. //Original code from Ignacio CastaÒo
  51157. // This formula is from Manne ÷hrstrˆm's thesis.
  51158. // Take two coordiantes in the range [-1, 1] that define a portion of a
  51159. // cube face and return the area of the projection of that portion on the
  51160. // surface of the sphere.
  51161. //--------------------------------------------------------------------------------------
  51162. PMREMGenerator.prototype.areaElement = function (x, y) {
  51163. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  51164. };
  51165. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  51166. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  51167. // (+ 0.5f is for texel center addressing)
  51168. u = (2.0 * (u + 0.5) / size) - 1.0;
  51169. v = (2.0 * (v + 0.5) / size) - 1.0;
  51170. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  51171. var invResolution = 1.0 / size;
  51172. // U and V are the -1..1 texture coordinate on the current face.
  51173. // Get projected area for this texel
  51174. var x0 = u - invResolution;
  51175. var y0 = v - invResolution;
  51176. var x1 = u + invResolution;
  51177. var y1 = v + invResolution;
  51178. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  51179. return solidAngle;
  51180. };
  51181. //--------------------------------------------------------------------------------------
  51182. //The key to the speed of these filtering routines is to quickly define a per-face
  51183. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  51184. // Later these pixels are selectively processed based on their dot products to see if
  51185. // they reside within the filtering cone.
  51186. //
  51187. //This is done by computing the smallest per-texel angle to get a conservative estimate
  51188. // of the number of texels needed to be covered in width and height order to filter the
  51189. // region. the bounding box for the center taps face is defined first, and if the
  51190. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  51191. // defined next
  51192. //--------------------------------------------------------------------------------------
  51193. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  51194. // note that pixels within these regions may be rejected
  51195. // based on the anlge
  51196. var iCubeFace;
  51197. var u;
  51198. var v;
  51199. // bounding box per face to specify region to process
  51200. var filterExtents = [];
  51201. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51202. filterExtents.push(new CMGBoundinBox());
  51203. }
  51204. // min angle a src texel can cover (in degrees)
  51205. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  51206. // angle about center tap to define filter cone
  51207. // filter angle is 1/2 the cone angle
  51208. var filterAngle = filterConeAngle / 2.0;
  51209. //ensure filter angle is larger than a texel
  51210. if (filterAngle < srcTexelAngle) {
  51211. filterAngle = srcTexelAngle;
  51212. }
  51213. //ensure filter cone is always smaller than the hemisphere
  51214. if (filterAngle > 90.0) {
  51215. filterAngle = 90.0;
  51216. }
  51217. // the maximum number of texels in 1D the filter cone angle will cover
  51218. // used to determine bounding box size for filter extents
  51219. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  51220. // ensure conservative region always covers at least one texel
  51221. if (filterSize < 1) {
  51222. filterSize = 1;
  51223. }
  51224. // dotProdThresh threshold based on cone angle to determine whether or not taps
  51225. // reside within the cone angle
  51226. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  51227. // process required faces
  51228. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51229. //iterate over dst cube map face texel
  51230. for (v = 0; v < dstSize; v++) {
  51231. for (u = 0; u < dstSize; u++) {
  51232. //get center tap direction
  51233. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  51234. //clear old per-face filter extents
  51235. this.clearFilterExtents(filterExtents);
  51236. //define per-face filter extents
  51237. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  51238. //perform filtering of src faces using filter extents
  51239. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  51240. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  51241. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  51242. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  51243. }
  51244. }
  51245. }
  51246. };
  51247. //--------------------------------------------------------------------------------------
  51248. //Clear filter extents for the 6 cube map faces
  51249. //--------------------------------------------------------------------------------------
  51250. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  51251. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  51252. filterExtents[iCubeFaces].clear();
  51253. }
  51254. };
  51255. //--------------------------------------------------------------------------------------
  51256. //Define per-face bounding box filter extents
  51257. //
  51258. // These define conservative texel regions in each of the faces the filter can possibly
  51259. // process. When the pixels in the regions are actually processed, the dot product
  51260. // between the tap vector and the center tap vector is used to determine the weight of
  51261. // the tap and whether or not the tap is within the cone.
  51262. //
  51263. //--------------------------------------------------------------------------------------
  51264. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  51265. //neighboring face and bleed over amount, and width of BBOX for
  51266. // left, right, top, and bottom edges of this face
  51267. var bleedOverAmount = [0, 0, 0, 0];
  51268. var bleedOverBBoxMin = [0, 0, 0, 0];
  51269. var bleedOverBBoxMax = [0, 0, 0, 0];
  51270. var neighborFace;
  51271. var neighborEdge;
  51272. var oppositeFaceIdx;
  51273. //get face idx, and u, v info from center tap dir
  51274. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  51275. var faceIdx = result.x;
  51276. var u = result.y;
  51277. var v = result.z;
  51278. //define bbox size within face
  51279. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  51280. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  51281. filterExtents[faceIdx].clampMin(0, 0, 0);
  51282. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  51283. //u and v extent in face corresponding to center tap
  51284. var minU = filterExtents[faceIdx].min.x;
  51285. var minV = filterExtents[faceIdx].min.y;
  51286. var maxU = filterExtents[faceIdx].max.x;
  51287. var maxV = filterExtents[faceIdx].max.y;
  51288. //bleed over amounts for face across u=0 edge (left)
  51289. bleedOverAmount[0] = (bboxSize - u);
  51290. bleedOverBBoxMin[0] = minV;
  51291. bleedOverBBoxMax[0] = maxV;
  51292. //bleed over amounts for face across u=1 edge (right)
  51293. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  51294. bleedOverBBoxMin[1] = minV;
  51295. bleedOverBBoxMax[1] = maxV;
  51296. //bleed over to face across v=0 edge (up)
  51297. bleedOverAmount[2] = (bboxSize - v);
  51298. bleedOverBBoxMin[2] = minU;
  51299. bleedOverBBoxMax[2] = maxU;
  51300. //bleed over to face across v=1 edge (down)
  51301. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  51302. bleedOverBBoxMin[3] = minU;
  51303. bleedOverBBoxMax[3] = maxU;
  51304. //compute bleed over regions in neighboring faces
  51305. for (var i = 0; i < 4; i++) {
  51306. if (bleedOverAmount[i] > 0) {
  51307. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  51308. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  51309. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  51310. // be flipped: the cases are
  51311. // if a left edge mates with a left or bottom edge on the neighbor
  51312. // if a top edge mates with a top or right edge on the neighbor
  51313. // if a right edge mates with a right or top edge on the neighbor
  51314. // if a bottom edge mates with a bottom or left edge on the neighbor
  51315. //Seeing as the edges are enumerated as follows
  51316. // left =0
  51317. // right =1
  51318. // top =2
  51319. // bottom =3
  51320. //
  51321. // so if the edge enums are the same, or the sum of the enums == 3,
  51322. // the bbox needs to be flipped
  51323. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  51324. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  51325. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  51326. }
  51327. //The way the bounding box is extended onto the neighboring face
  51328. // depends on which edge of neighboring face abuts with this one
  51329. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  51330. case PMREMGenerator.CP_EDGE_LEFT:
  51331. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  51332. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51333. break;
  51334. case PMREMGenerator.CP_EDGE_RIGHT:
  51335. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  51336. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51337. break;
  51338. case PMREMGenerator.CP_EDGE_TOP:
  51339. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  51340. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  51341. break;
  51342. case PMREMGenerator.CP_EDGE_BOTTOM:
  51343. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  51344. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  51345. break;
  51346. }
  51347. //clamp filter extents in non-center tap faces to remain within surface
  51348. filterExtents[neighborFace].clampMin(0, 0, 0);
  51349. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  51350. }
  51351. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  51352. // from the center tap face, then process the opposite face entirely for now.
  51353. //Note that the cases in which this happens, what usually happens is that
  51354. // more than one edge bleeds onto the opposite face, and the bounding box
  51355. // encompasses the entire cube map face.
  51356. if (bleedOverAmount[i] > srcSize) {
  51357. //determine opposite face
  51358. switch (faceIdx) {
  51359. case PMREMGenerator.CP_FACE_X_POS:
  51360. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51361. break;
  51362. case PMREMGenerator.CP_FACE_X_NEG:
  51363. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  51364. break;
  51365. case PMREMGenerator.CP_FACE_Y_POS:
  51366. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51367. break;
  51368. case PMREMGenerator.CP_FACE_Y_NEG:
  51369. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51370. break;
  51371. case PMREMGenerator.CP_FACE_Z_POS:
  51372. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51373. break;
  51374. case PMREMGenerator.CP_FACE_Z_NEG:
  51375. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51376. break;
  51377. default:
  51378. break;
  51379. }
  51380. //just encompass entire face for now
  51381. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  51382. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  51383. }
  51384. }
  51385. };
  51386. //--------------------------------------------------------------------------------------
  51387. //ProcessFilterExtents
  51388. // Process bounding box in each cube face
  51389. //
  51390. //--------------------------------------------------------------------------------------
  51391. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  51392. //accumulators are 64-bit floats in order to have the precision needed
  51393. // over a summation of a large number of pixels
  51394. var dstAccum = [0, 0, 0, 0];
  51395. var weightAccum = 0;
  51396. var k = 0;
  51397. var nSrcChannels = this.numChannels;
  51398. // norm cube map and srcCubeMap have same face width
  51399. var faceWidth = srcSize;
  51400. //amount to add to pointer to move to next scanline in images
  51401. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  51402. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  51403. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  51404. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  51405. // iterate over cubefaces
  51406. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  51407. //if bbox is non empty
  51408. if (!filterExtents[iFaceIdx].empty()) {
  51409. var uStart = filterExtents[iFaceIdx].min.x;
  51410. var vStart = filterExtents[iFaceIdx].min.y;
  51411. var uEnd = filterExtents[iFaceIdx].max.x;
  51412. var vEnd = filterExtents[iFaceIdx].max.y;
  51413. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  51414. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  51415. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  51416. for (var v = vStart; v <= vEnd; v++) {
  51417. var normCubeRowWalk = 0;
  51418. var srcCubeRowWalk = 0;
  51419. for (var u = uStart; u <= uEnd; u++) {
  51420. //pointer to direction in cube map associated with texel
  51421. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  51422. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  51423. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  51424. //check dot product to see if texel is within cone
  51425. var tapDotProd = texelVectX * centerTapDir.x +
  51426. texelVectY * centerTapDir.y +
  51427. texelVectZ * centerTapDir.z;
  51428. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  51429. //solid angle stored in 4th channel of normalizer/solid angle cube map
  51430. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  51431. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  51432. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  51433. // so just adding one to specularpower do the trick.
  51434. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  51435. //iterate over channels
  51436. for (k = 0; k < nSrcChannels; k++) {
  51437. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  51438. srcCubeRowWalk++;
  51439. }
  51440. weightAccum += weight; //accumulate weight
  51441. }
  51442. else {
  51443. //step across source pixel
  51444. srcCubeRowWalk += nSrcChannels;
  51445. }
  51446. normCubeRowWalk += 4; // 4 channels per norm cube map.
  51447. }
  51448. startIndexNormCubeMap += normCubePitch;
  51449. startIndexSrcCubeMap += srcCubePitch;
  51450. }
  51451. }
  51452. }
  51453. //divide through by weights if weight is non zero
  51454. if (weightAccum != 0.0) {
  51455. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  51456. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  51457. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  51458. if (this.numChannels > 3) {
  51459. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  51460. }
  51461. }
  51462. else {
  51463. // otherwise sample nearest
  51464. // get face idx and u, v texel coordinate in face
  51465. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  51466. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  51467. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  51468. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  51469. if (this.numChannels > 3) {
  51470. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  51471. }
  51472. }
  51473. return PMREMGenerator._vectorTemp;
  51474. };
  51475. //--------------------------------------------------------------------------------------
  51476. // Fixup cube edges
  51477. //
  51478. // average texels on cube map faces across the edges
  51479. // WARP/BENT Method Only.
  51480. //--------------------------------------------------------------------------------------
  51481. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  51482. var k;
  51483. var j;
  51484. var i;
  51485. var iFace;
  51486. var iCorner = 0;
  51487. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  51488. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  51489. // note that if functionality to filter across the three texels for each corner, then
  51490. //indexed by corner and face idx. the array contains the face the start points belongs to.
  51491. var cornerPtr = [
  51492. [[], [], []],
  51493. [[], [], []],
  51494. [[], [], []],
  51495. [[], [], []],
  51496. [[], [], []],
  51497. [[], [], []],
  51498. [[], [], []],
  51499. [[], [], []]
  51500. ];
  51501. //if there is no fixup, or fixup width = 0, do nothing
  51502. if (cubeMapSize < 1) {
  51503. return;
  51504. }
  51505. //special case 1x1 cubemap, average face colors
  51506. if (cubeMapSize == 1) {
  51507. //iterate over channels
  51508. for (k = 0; k < this.numChannels; k++) {
  51509. var accum = 0.0;
  51510. //iterate over faces to accumulate face colors
  51511. for (iFace = 0; iFace < 6; iFace++) {
  51512. accum += cubeMap[iFace][k];
  51513. }
  51514. //compute average over 6 face colors
  51515. accum /= 6.0;
  51516. //iterate over faces to distribute face colors
  51517. for (iFace = 0; iFace < 6; iFace++) {
  51518. cubeMap[iFace][k] = accum;
  51519. }
  51520. }
  51521. return;
  51522. }
  51523. //iterate over faces to collect list of corner texel pointers
  51524. for (iFace = 0; iFace < 6; iFace++) {
  51525. //the 4 corner pointers for this face
  51526. faceCornerStartIndicies[0] = [iFace, 0];
  51527. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  51528. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  51529. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  51530. //iterate over face corners to collect cube corner pointers
  51531. for (iCorner = 0; iCorner < 4; iCorner++) {
  51532. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  51533. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  51534. cornerNumPtrs[corner]++;
  51535. }
  51536. }
  51537. //iterate over corners to average across corner tap values
  51538. for (iCorner = 0; iCorner < 8; iCorner++) {
  51539. for (k = 0; k < this.numChannels; k++) {
  51540. var cornerTapAccum = 0.0;
  51541. //iterate over corner texels and average results
  51542. for (i = 0; i < 3; i++) {
  51543. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  51544. }
  51545. //divide by 3 to compute average of corner tap values
  51546. cornerTapAccum *= (1.0 / 3.0);
  51547. //iterate over corner texels and average results
  51548. for (i = 0; i < 3; i++) {
  51549. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  51550. }
  51551. }
  51552. }
  51553. //iterate over the twelve edges of the cube to average across edges
  51554. for (i = 0; i < 12; i++) {
  51555. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  51556. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  51557. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  51558. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  51559. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  51560. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  51561. var edgeWalk = 0;
  51562. var neighborEdgeWalk = 0;
  51563. //Determine walking pointers based on edge type
  51564. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  51565. switch (edge) {
  51566. case PMREMGenerator.CP_EDGE_LEFT:
  51567. // no change to faceEdgeStartPtr
  51568. edgeWalk = this.numChannels * cubeMapSize;
  51569. break;
  51570. case PMREMGenerator.CP_EDGE_RIGHT:
  51571. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51572. edgeWalk = this.numChannels * cubeMapSize;
  51573. break;
  51574. case PMREMGenerator.CP_EDGE_TOP:
  51575. // no change to faceEdgeStartPtr
  51576. edgeWalk = this.numChannels;
  51577. break;
  51578. case PMREMGenerator.CP_EDGE_BOTTOM:
  51579. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51580. edgeWalk = this.numChannels;
  51581. break;
  51582. }
  51583. //For certain types of edge abutments, the neighbor edge walk needs to
  51584. // be flipped: the cases are
  51585. // if a left edge mates with a left or bottom edge on the neighbor
  51586. // if a top edge mates with a top or right edge on the neighbor
  51587. // if a right edge mates with a right or top edge on the neighbor
  51588. // if a bottom edge mates with a bottom or left edge on the neighbor
  51589. //Seeing as the edges are enumerated as follows
  51590. // left =0
  51591. // right =1
  51592. // top =2
  51593. // bottom =3
  51594. //
  51595. //If the edge enums are the same, or the sum of the enums == 3,
  51596. // the neighbor edge walk needs to be flipped
  51597. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  51598. switch (neighborEdge) {
  51599. case PMREMGenerator.CP_EDGE_LEFT:
  51600. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  51601. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51602. break;
  51603. case PMREMGenerator.CP_EDGE_RIGHT:
  51604. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51605. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51606. break;
  51607. case PMREMGenerator.CP_EDGE_TOP:
  51608. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51609. neighborEdgeWalk = -this.numChannels;
  51610. break;
  51611. case PMREMGenerator.CP_EDGE_BOTTOM:
  51612. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51613. neighborEdgeWalk = -this.numChannels;
  51614. break;
  51615. }
  51616. }
  51617. else {
  51618. //swapped direction neighbor edge walk
  51619. switch (neighborEdge) {
  51620. case PMREMGenerator.CP_EDGE_LEFT:
  51621. //no change to neighborEdgeStartPtr for this case since it points
  51622. // to the upper left corner already
  51623. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51624. break;
  51625. case PMREMGenerator.CP_EDGE_RIGHT:
  51626. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51627. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51628. break;
  51629. case PMREMGenerator.CP_EDGE_TOP:
  51630. //no change to neighborEdgeStartPtr for this case since it points
  51631. // to the upper left corner already
  51632. neighborEdgeWalk = this.numChannels;
  51633. break;
  51634. case PMREMGenerator.CP_EDGE_BOTTOM:
  51635. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51636. neighborEdgeWalk = this.numChannels;
  51637. break;
  51638. }
  51639. }
  51640. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  51641. //nearby neighborhood
  51642. //step ahead one texel on edge
  51643. edgeStartIndex += edgeWalk;
  51644. neighborEdgeStartIndex += neighborEdgeWalk;
  51645. // note that this loop does not process the corner texels, since they have already been
  51646. // averaged across faces across earlier
  51647. for (j = 1; j < (cubeMapSize - 1); j++) {
  51648. //for each set of taps along edge, average them
  51649. // and rewrite the results into the edges
  51650. for (k = 0; k < this.numChannels; k++) {
  51651. var edgeTap = cubeMap[face][edgeStartIndex + k];
  51652. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  51653. //compute average of tap intensity values
  51654. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  51655. //propagate average of taps to edge taps
  51656. cubeMap[face][edgeStartIndex + k] = avgTap;
  51657. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  51658. }
  51659. edgeStartIndex += edgeWalk;
  51660. neighborEdgeStartIndex += neighborEdgeWalk;
  51661. }
  51662. }
  51663. };
  51664. return PMREMGenerator;
  51665. }());
  51666. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  51667. PMREMGenerator.CP_UDIR = 0;
  51668. PMREMGenerator.CP_VDIR = 1;
  51669. PMREMGenerator.CP_FACEAXIS = 2;
  51670. //used to index cube faces
  51671. PMREMGenerator.CP_FACE_X_POS = 0;
  51672. PMREMGenerator.CP_FACE_X_NEG = 1;
  51673. PMREMGenerator.CP_FACE_Y_POS = 2;
  51674. PMREMGenerator.CP_FACE_Y_NEG = 3;
  51675. PMREMGenerator.CP_FACE_Z_POS = 4;
  51676. PMREMGenerator.CP_FACE_Z_NEG = 5;
  51677. //used to index image edges
  51678. // NOTE.. the actual number corresponding to the edge is important
  51679. // do not change these, or the code will break
  51680. //
  51681. // CP_EDGE_LEFT is u = 0
  51682. // CP_EDGE_RIGHT is u = width-1
  51683. // CP_EDGE_TOP is v = 0
  51684. // CP_EDGE_BOTTOM is v = height-1
  51685. PMREMGenerator.CP_EDGE_LEFT = 0;
  51686. PMREMGenerator.CP_EDGE_RIGHT = 1;
  51687. PMREMGenerator.CP_EDGE_TOP = 2;
  51688. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  51689. //corners of CUBE map (P or N specifys if it corresponds to the
  51690. // positive or negative direction each of X, Y, and Z
  51691. PMREMGenerator.CP_CORNER_NNN = 0;
  51692. PMREMGenerator.CP_CORNER_NNP = 1;
  51693. PMREMGenerator.CP_CORNER_NPN = 2;
  51694. PMREMGenerator.CP_CORNER_NPP = 3;
  51695. PMREMGenerator.CP_CORNER_PNN = 4;
  51696. PMREMGenerator.CP_CORNER_PNP = 5;
  51697. PMREMGenerator.CP_CORNER_PPN = 6;
  51698. PMREMGenerator.CP_CORNER_PPP = 7;
  51699. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  51700. //3x2 matrices that map cube map indexing vectors in 3d
  51701. // (after face selection and divide through by the
  51702. // _ABSOLUTE VALUE_ of the max coord)
  51703. // into NVC space
  51704. //Note this currently assumes the D3D cube face ordering and orientation
  51705. PMREMGenerator._sgFace2DMapping = [
  51706. //XPOS face
  51707. [[0, 0, -1],
  51708. [0, -1, 0],
  51709. [1, 0, 0]],
  51710. //XNEG face
  51711. [[0, 0, 1],
  51712. [0, -1, 0],
  51713. [-1, 0, 0]],
  51714. //YPOS face
  51715. [[1, 0, 0],
  51716. [0, 0, 1],
  51717. [0, 1, 0]],
  51718. //YNEG face
  51719. [[1, 0, 0],
  51720. [0, 0, -1],
  51721. [0, -1, 0]],
  51722. //ZPOS face
  51723. [[1, 0, 0],
  51724. [0, -1, 0],
  51725. [0, 0, 1]],
  51726. //ZNEG face
  51727. [[-1, 0, 0],
  51728. [0, -1, 0],
  51729. [0, 0, -1]],
  51730. ];
  51731. //------------------------------------------------------------------------------
  51732. // D3D cube map face specification
  51733. // mapping from 3D x,y,z cube map lookup coordinates
  51734. // to 2D within face u,v coordinates
  51735. //
  51736. // --------------------> U direction
  51737. // | (within-face texture space)
  51738. // | _____
  51739. // | | |
  51740. // | | +Y |
  51741. // | _____|_____|_____ _____
  51742. // | | | | | |
  51743. // | | -X | +Z | +X | -Z |
  51744. // | |_____|_____|_____|_____|
  51745. // | | |
  51746. // | | -Y |
  51747. // | |_____|
  51748. // |
  51749. // v V direction
  51750. // (within-face texture space)
  51751. //------------------------------------------------------------------------------
  51752. //Information about neighbors and how texture coorrdinates change across faces
  51753. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  51754. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  51755. //Note this currently assumes the D3D cube face ordering and orientation
  51756. PMREMGenerator._sgCubeNgh = [
  51757. //XPOS face
  51758. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51759. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51760. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51761. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  51762. //XNEG face
  51763. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51764. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  51765. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  51766. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  51767. //YPOS face
  51768. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51769. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51770. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51771. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  51772. //YNEG face
  51773. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51774. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51775. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51776. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  51777. //ZPOS face
  51778. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51779. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51780. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51781. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  51782. //ZNEG face
  51783. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51784. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51785. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  51786. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  51787. ];
  51788. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  51789. // this table is used to average over the edges.
  51790. PMREMGenerator._sgCubeEdgeList = [
  51791. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51792. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51793. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51794. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51795. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51796. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51797. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51798. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51799. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  51800. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51801. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51802. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  51803. ];
  51804. //Information about which of the 8 cube corners are correspond to the
  51805. // the 4 corners in each cube face
  51806. // the order is upper left, upper right, lower left, lower right
  51807. PMREMGenerator._sgCubeCornerList = [
  51808. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  51809. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  51810. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  51811. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  51812. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  51813. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  51814. ];
  51815. Internals.PMREMGenerator = PMREMGenerator;
  51816. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51817. })(BABYLON || (BABYLON = {}));
  51818. //# sourceMappingURL=babylon.tools.pmremGenerator.js.map
  51819. var BABYLON;
  51820. (function (BABYLON) {
  51821. /**
  51822. * This represents a texture coming from an HDR input.
  51823. *
  51824. * The only supported format is currently panorama picture stored in RGBE format.
  51825. * Example of such files can be found on HDRLib: http://hdrlib.com/
  51826. */
  51827. var HDRCubeTexture = (function (_super) {
  51828. __extends(HDRCubeTexture, _super);
  51829. /**
  51830. * Instantiates an HDRTexture from the following parameters.
  51831. *
  51832. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  51833. * @param scene The scene the texture will be used in
  51834. * @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.
  51835. * @param noMipmap Forces to not generate the mipmap if true
  51836. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  51837. * @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)
  51838. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  51839. */
  51840. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  51841. if (noMipmap === void 0) { noMipmap = false; }
  51842. if (generateHarmonics === void 0) { generateHarmonics = true; }
  51843. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  51844. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  51845. var _this = _super.call(this, scene) || this;
  51846. _this._useInGammaSpace = false;
  51847. _this._generateHarmonics = true;
  51848. _this._isBABYLONPreprocessed = false;
  51849. /**
  51850. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  51851. */
  51852. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  51853. /**
  51854. * The spherical polynomial data extracted from the texture.
  51855. */
  51856. _this.sphericalPolynomial = null;
  51857. /**
  51858. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  51859. * This is usefull at run time to apply the good shader.
  51860. */
  51861. _this.isPMREM = false;
  51862. if (!url) {
  51863. return _this;
  51864. }
  51865. _this.name = url;
  51866. _this.url = url;
  51867. _this.hasAlpha = false;
  51868. _this.isCube = true;
  51869. _this._textureMatrix = BABYLON.Matrix.Identity();
  51870. if (size) {
  51871. _this._isBABYLONPreprocessed = false;
  51872. _this._noMipmap = noMipmap;
  51873. _this._size = size;
  51874. _this._useInGammaSpace = useInGammaSpace;
  51875. _this._usePMREMGenerator = usePMREMGenerator &&
  51876. scene.getEngine().getCaps().textureLOD &&
  51877. _this.getScene().getEngine().getCaps().textureFloat &&
  51878. !_this._useInGammaSpace;
  51879. }
  51880. else {
  51881. _this._isBABYLONPreprocessed = true;
  51882. _this._noMipmap = false;
  51883. _this._useInGammaSpace = false;
  51884. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  51885. _this.getScene().getEngine().getCaps().textureFloat &&
  51886. !_this._useInGammaSpace;
  51887. }
  51888. _this.isPMREM = _this._usePMREMGenerator;
  51889. _this._texture = _this._getFromCache(url, _this._noMipmap);
  51890. if (!_this._texture) {
  51891. if (!scene.useDelayedTextureLoading) {
  51892. _this.loadTexture();
  51893. }
  51894. else {
  51895. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  51896. }
  51897. }
  51898. return _this;
  51899. }
  51900. /**
  51901. * Occurs when the file is a preprocessed .babylon.hdr file.
  51902. */
  51903. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  51904. var _this = this;
  51905. var mipLevels = 0;
  51906. var floatArrayView = null;
  51907. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  51908. var mips = [];
  51909. var startIndex = 30;
  51910. for (var level = 0; level < mipLevels; level++) {
  51911. mips.push([]);
  51912. // Fill each pixel of the mip level.
  51913. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  51914. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51915. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  51916. mips[level].push(faceData);
  51917. startIndex += faceSize;
  51918. }
  51919. }
  51920. return mips;
  51921. } : null;
  51922. var callback = function (buffer) {
  51923. // Create Native Array Views
  51924. var intArrayView = new Int32Array(buffer);
  51925. floatArrayView = new Float32Array(buffer);
  51926. // Fill header.
  51927. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  51928. _this._size = intArrayView[1]; // CubeMap max mip face size.
  51929. // Update Texture Information.
  51930. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  51931. // Fill polynomial information.
  51932. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  51933. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  51934. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  51935. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  51936. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  51937. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  51938. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  51939. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  51940. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  51941. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  51942. // Fill pixel data.
  51943. mipLevels = intArrayView[29]; // Number of mip levels.
  51944. var startIndex = 30;
  51945. var data = [];
  51946. var faceSize = Math.pow(_this._size, 2) * 3;
  51947. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51948. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  51949. startIndex += faceSize;
  51950. }
  51951. var results = [];
  51952. var byteArray = null;
  51953. // Push each faces.
  51954. for (var k = 0; k < 6; k++) {
  51955. var dataFace = null;
  51956. // If special cases.
  51957. if (!mipmapGenerator) {
  51958. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  51959. dataFace = data[j];
  51960. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  51961. // 3 channels of 1 bytes per pixel in bytes.
  51962. var byteBuffer = new ArrayBuffer(faceSize);
  51963. byteArray = new Uint8Array(byteBuffer);
  51964. }
  51965. for (var i = 0; i < _this._size * _this._size; i++) {
  51966. // Put in gamma space if requested.
  51967. if (_this._useInGammaSpace) {
  51968. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  51969. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  51970. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  51971. }
  51972. // Convert to int texture for fallback.
  51973. if (byteArray) {
  51974. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  51975. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  51976. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  51977. // May use luminance instead if the result is not accurate.
  51978. var max = Math.max(Math.max(r, g), b);
  51979. if (max > 255) {
  51980. var scale = 255 / max;
  51981. r *= scale;
  51982. g *= scale;
  51983. b *= scale;
  51984. }
  51985. byteArray[(i * 3) + 0] = r;
  51986. byteArray[(i * 3) + 1] = g;
  51987. byteArray[(i * 3) + 2] = b;
  51988. }
  51989. }
  51990. }
  51991. else {
  51992. dataFace = data[k];
  51993. }
  51994. // Fill the array accordingly.
  51995. if (byteArray) {
  51996. results.push(byteArray);
  51997. }
  51998. else {
  51999. results.push(dataFace);
  52000. }
  52001. }
  52002. return results;
  52003. };
  52004. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator);
  52005. };
  52006. /**
  52007. * Occurs when the file is raw .hdr file.
  52008. */
  52009. HDRCubeTexture.prototype.loadHDRTexture = function () {
  52010. var _this = this;
  52011. var callback = function (buffer) {
  52012. // Extract the raw linear data.
  52013. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  52014. // Generate harmonics if needed.
  52015. if (_this._generateHarmonics) {
  52016. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  52017. }
  52018. var results = [];
  52019. var byteArray = null;
  52020. // Push each faces.
  52021. for (var j = 0; j < 6; j++) {
  52022. // Create uintarray fallback.
  52023. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  52024. // 3 channels of 1 bytes per pixel in bytes.
  52025. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  52026. byteArray = new Uint8Array(byteBuffer);
  52027. }
  52028. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  52029. // If special cases.
  52030. if (_this._useInGammaSpace || byteArray) {
  52031. for (var i = 0; i < _this._size * _this._size; i++) {
  52032. // Put in gamma space if requested.
  52033. if (_this._useInGammaSpace) {
  52034. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  52035. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  52036. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  52037. }
  52038. // Convert to int texture for fallback.
  52039. if (byteArray) {
  52040. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  52041. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  52042. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  52043. // May use luminance instead if the result is not accurate.
  52044. var max = Math.max(Math.max(r, g), b);
  52045. if (max > 255) {
  52046. var scale = 255 / max;
  52047. r *= scale;
  52048. g *= scale;
  52049. b *= scale;
  52050. }
  52051. byteArray[(i * 3) + 0] = r;
  52052. byteArray[(i * 3) + 1] = g;
  52053. byteArray[(i * 3) + 2] = b;
  52054. }
  52055. }
  52056. }
  52057. if (byteArray) {
  52058. results.push(byteArray);
  52059. }
  52060. else {
  52061. results.push(dataFace);
  52062. }
  52063. }
  52064. return results;
  52065. };
  52066. var mipmapGenerator = null;
  52067. if (!this._noMipmap &&
  52068. this._usePMREMGenerator) {
  52069. mipmapGenerator = function (data) {
  52070. // Custom setup of the generator matching with the PBR shader values.
  52071. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  52072. return generator.filterCubeMap();
  52073. };
  52074. }
  52075. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator);
  52076. };
  52077. /**
  52078. * Starts the loading process of the texture.
  52079. */
  52080. HDRCubeTexture.prototype.loadTexture = function () {
  52081. if (this._isBABYLONPreprocessed) {
  52082. this.loadBabylonTexture();
  52083. }
  52084. else {
  52085. this.loadHDRTexture();
  52086. }
  52087. };
  52088. HDRCubeTexture.prototype.clone = function () {
  52089. var size = this._isBABYLONPreprocessed ? null : this._size;
  52090. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  52091. // Base texture
  52092. newTexture.level = this.level;
  52093. newTexture.wrapU = this.wrapU;
  52094. newTexture.wrapV = this.wrapV;
  52095. newTexture.coordinatesIndex = this.coordinatesIndex;
  52096. newTexture.coordinatesMode = this.coordinatesMode;
  52097. return newTexture;
  52098. };
  52099. // Methods
  52100. HDRCubeTexture.prototype.delayLoad = function () {
  52101. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  52102. return;
  52103. }
  52104. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  52105. this._texture = this._getFromCache(this.url, this._noMipmap);
  52106. if (!this._texture) {
  52107. this.loadTexture();
  52108. }
  52109. };
  52110. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  52111. return this._textureMatrix;
  52112. };
  52113. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  52114. var texture = null;
  52115. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  52116. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  52117. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  52118. texture.name = parsedTexture.name;
  52119. texture.hasAlpha = parsedTexture.hasAlpha;
  52120. texture.level = parsedTexture.level;
  52121. texture.coordinatesMode = parsedTexture.coordinatesMode;
  52122. }
  52123. return texture;
  52124. };
  52125. HDRCubeTexture.prototype.serialize = function () {
  52126. if (!this.name) {
  52127. return null;
  52128. }
  52129. var serializationObject = {};
  52130. serializationObject.name = this.name;
  52131. serializationObject.hasAlpha = this.hasAlpha;
  52132. serializationObject.isCube = true;
  52133. serializationObject.level = this.level;
  52134. serializationObject.size = this._size;
  52135. serializationObject.coordinatesMode = this.coordinatesMode;
  52136. serializationObject.useInGammaSpace = this._useInGammaSpace;
  52137. serializationObject.generateHarmonics = this._generateHarmonics;
  52138. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  52139. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  52140. serializationObject.customType = "BABYLON.HDRCubeTexture";
  52141. return serializationObject;
  52142. };
  52143. /**
  52144. * Saves as a file the data contained in the texture in a binary format.
  52145. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  52146. * as the spherical used in the lighting.
  52147. * @param url The HDR file url.
  52148. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  52149. * @param onError Method called if any error happens during download.
  52150. * @return The packed binary data.
  52151. */
  52152. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  52153. if (onError === void 0) { onError = null; }
  52154. var callback = function (buffer) {
  52155. var data = new Blob([buffer], { type: 'application/octet-stream' });
  52156. // Returns a URL you can use as a href.
  52157. var objUrl = window.URL.createObjectURL(data);
  52158. // Simulates a link to it and click to dowload.
  52159. var a = document.createElement("a");
  52160. document.body.appendChild(a);
  52161. a.style.display = "none";
  52162. a.href = objUrl;
  52163. a.download = "envmap.babylon.hdr";
  52164. a.click();
  52165. };
  52166. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  52167. };
  52168. /**
  52169. * Serializes the data contained in the texture in a binary format.
  52170. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  52171. * as the spherical used in the lighting.
  52172. * @param url The HDR file url.
  52173. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  52174. * @param onError Method called if any error happens during download.
  52175. * @return The packed binary data.
  52176. */
  52177. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  52178. if (onError === void 0) { onError = null; }
  52179. // Needs the url tho create the texture.
  52180. if (!url) {
  52181. return null;
  52182. }
  52183. // Check Power of two size.
  52184. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  52185. return null;
  52186. }
  52187. var getDataCallback = function (dataBuffer) {
  52188. // Extract the raw linear data.
  52189. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  52190. // Generate harmonics if needed.
  52191. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  52192. // Generate seamless faces
  52193. var mipGeneratorArray = [];
  52194. // Data are known to be in +X +Y +Z -X -Y -Z
  52195. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  52196. mipGeneratorArray.push(cubeData.right); // +X
  52197. mipGeneratorArray.push(cubeData.left); // -X
  52198. mipGeneratorArray.push(cubeData.up); // +Y
  52199. mipGeneratorArray.push(cubeData.down); // -Y
  52200. mipGeneratorArray.push(cubeData.front); // +Z
  52201. mipGeneratorArray.push(cubeData.back); // -Z
  52202. // Custom setup of the generator matching with the PBR shader values.
  52203. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  52204. var mippedData = generator.filterCubeMap();
  52205. // Compute required byte length.
  52206. var byteLength = 1 * 4; // Raw Data Version int32.
  52207. byteLength += 4; // CubeMap max mip face size int32.
  52208. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  52209. // Add data size.
  52210. byteLength += 4; // Number of mip levels int32.
  52211. for (var level = 0; level < mippedData.length; level++) {
  52212. var mipSize = size >> level;
  52213. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  52214. }
  52215. // Prepare binary structure.
  52216. var buffer = new ArrayBuffer(byteLength);
  52217. var intArrayView = new Int32Array(buffer);
  52218. var floatArrayView = new Float32Array(buffer);
  52219. // Fill header.
  52220. intArrayView[0] = 1; // Version 1.
  52221. intArrayView[1] = size; // CubeMap max mip face size.
  52222. // Fill polynomial information.
  52223. sphericalPolynomial.x.toArray(floatArrayView, 2);
  52224. sphericalPolynomial.y.toArray(floatArrayView, 5);
  52225. sphericalPolynomial.z.toArray(floatArrayView, 8);
  52226. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  52227. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  52228. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  52229. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  52230. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  52231. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  52232. // Fill pixel data.
  52233. intArrayView[29] = mippedData.length; // Number of mip levels.
  52234. var startIndex = 30;
  52235. for (var level = 0; level < mippedData.length; level++) {
  52236. // Fill each pixel of the mip level.
  52237. var faceSize = Math.pow(size >> level, 2) * 3;
  52238. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52239. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  52240. startIndex += faceSize;
  52241. }
  52242. }
  52243. // Callback.
  52244. callback(buffer);
  52245. };
  52246. // Download and process.
  52247. BABYLON.Tools.LoadFile(url, function (data) {
  52248. getDataCallback(data);
  52249. }, null, null, true, onError);
  52250. };
  52251. return HDRCubeTexture;
  52252. }(BABYLON.BaseTexture));
  52253. HDRCubeTexture._facesMapping = [
  52254. "right",
  52255. "up",
  52256. "front",
  52257. "left",
  52258. "down",
  52259. "back"
  52260. ];
  52261. BABYLON.HDRCubeTexture = HDRCubeTexture;
  52262. })(BABYLON || (BABYLON = {}));
  52263. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  52264. var BABYLON;
  52265. (function (BABYLON) {
  52266. var Debug;
  52267. (function (Debug) {
  52268. /**
  52269. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  52270. */
  52271. var SkeletonViewer = (function () {
  52272. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  52273. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  52274. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  52275. this.skeleton = skeleton;
  52276. this.mesh = mesh;
  52277. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  52278. this.renderingGroupId = renderingGroupId;
  52279. this.color = BABYLON.Color3.White();
  52280. this._debugLines = [];
  52281. this._isEnabled = false;
  52282. this._scene = scene;
  52283. this.update();
  52284. this._renderFunction = this.update.bind(this);
  52285. }
  52286. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  52287. get: function () {
  52288. return this._isEnabled;
  52289. },
  52290. set: function (value) {
  52291. if (this._isEnabled === value) {
  52292. return;
  52293. }
  52294. this._isEnabled = value;
  52295. if (value) {
  52296. this._scene.registerBeforeRender(this._renderFunction);
  52297. }
  52298. else {
  52299. this._scene.unregisterBeforeRender(this._renderFunction);
  52300. }
  52301. },
  52302. enumerable: true,
  52303. configurable: true
  52304. });
  52305. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  52306. if (x === void 0) { x = 0; }
  52307. if (y === void 0) { y = 0; }
  52308. if (z === void 0) { z = 0; }
  52309. var tmat = BABYLON.Tmp.Matrix[0];
  52310. var parentBone = bone.getParent();
  52311. tmat.copyFrom(bone.getLocalMatrix());
  52312. if (x !== 0 || y !== 0 || z !== 0) {
  52313. var tmat2 = BABYLON.Tmp.Matrix[1];
  52314. BABYLON.Matrix.IdentityToRef(tmat2);
  52315. tmat2.m[12] = x;
  52316. tmat2.m[13] = y;
  52317. tmat2.m[14] = z;
  52318. tmat2.multiplyToRef(tmat, tmat);
  52319. }
  52320. if (parentBone) {
  52321. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  52322. }
  52323. tmat.multiplyToRef(meshMat, tmat);
  52324. position.x = tmat.m[12];
  52325. position.y = tmat.m[13];
  52326. position.z = tmat.m[14];
  52327. };
  52328. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  52329. var len = bones.length;
  52330. for (var i = 0; i < len; i++) {
  52331. var bone = bones[i];
  52332. var points = this._debugLines[i];
  52333. if (!points) {
  52334. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52335. this._debugLines[i] = points;
  52336. }
  52337. this._getBonePosition(points[0], bone, meshMat);
  52338. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  52339. }
  52340. };
  52341. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  52342. var len = bones.length;
  52343. var boneNum = 0;
  52344. for (var i = len - 1; i >= 0; i--) {
  52345. var childBone = bones[i];
  52346. var parentBone = childBone.getParent();
  52347. if (!parentBone) {
  52348. continue;
  52349. }
  52350. var points = this._debugLines[boneNum];
  52351. if (!points) {
  52352. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52353. this._debugLines[boneNum] = points;
  52354. }
  52355. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  52356. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  52357. boneNum++;
  52358. }
  52359. };
  52360. SkeletonViewer.prototype.update = function () {
  52361. if (this.autoUpdateBonesMatrices) {
  52362. this.skeleton.computeAbsoluteTransforms();
  52363. }
  52364. if (this.skeleton.bones[0].length === undefined) {
  52365. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  52366. }
  52367. else {
  52368. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  52369. }
  52370. if (!this._debugMesh) {
  52371. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  52372. this._debugMesh.renderingGroupId = this.renderingGroupId;
  52373. }
  52374. else {
  52375. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  52376. }
  52377. this._debugMesh.color = this.color;
  52378. };
  52379. SkeletonViewer.prototype.dispose = function () {
  52380. if (this._debugMesh) {
  52381. this.isEnabled = false;
  52382. this._debugMesh.dispose();
  52383. this._debugMesh = null;
  52384. }
  52385. };
  52386. return SkeletonViewer;
  52387. }());
  52388. Debug.SkeletonViewer = SkeletonViewer;
  52389. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52390. })(BABYLON || (BABYLON = {}));
  52391. //# sourceMappingURL=babylon.skeletonViewer.js.map
  52392. var BABYLON;
  52393. (function (BABYLON) {
  52394. var Debug;
  52395. (function (Debug) {
  52396. var AxesViewer = (function () {
  52397. function AxesViewer(scene, scaleLines) {
  52398. if (scaleLines === void 0) { scaleLines = 1; }
  52399. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52400. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52401. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52402. this.scaleLines = 1;
  52403. this.scaleLines = scaleLines;
  52404. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  52405. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  52406. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  52407. this._xmesh.renderingGroupId = 2;
  52408. this._ymesh.renderingGroupId = 2;
  52409. this._zmesh.renderingGroupId = 2;
  52410. this._xmesh.material.checkReadyOnlyOnce = true;
  52411. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  52412. this._ymesh.material.checkReadyOnlyOnce = true;
  52413. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  52414. this._zmesh.material.checkReadyOnlyOnce = true;
  52415. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  52416. this.scene = scene;
  52417. }
  52418. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  52419. var scaleLines = this.scaleLines;
  52420. var point1 = this._xline[0];
  52421. var point2 = this._xline[1];
  52422. point1.x = position.x;
  52423. point1.y = position.y;
  52424. point1.z = position.z;
  52425. point2.x = point1.x + xaxis.x * scaleLines;
  52426. point2.y = point1.y + xaxis.y * scaleLines;
  52427. point2.z = point1.z + xaxis.z * scaleLines;
  52428. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  52429. point1 = this._yline[0];
  52430. point2 = this._yline[1];
  52431. point1.x = position.x;
  52432. point1.y = position.y;
  52433. point1.z = position.z;
  52434. point2.x = point1.x + yaxis.x * scaleLines;
  52435. point2.y = point1.y + yaxis.y * scaleLines;
  52436. point2.z = point1.z + yaxis.z * scaleLines;
  52437. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  52438. point1 = this._zline[0];
  52439. point2 = this._zline[1];
  52440. point1.x = position.x;
  52441. point1.y = position.y;
  52442. point1.z = position.z;
  52443. point2.x = point1.x + zaxis.x * scaleLines;
  52444. point2.y = point1.y + zaxis.y * scaleLines;
  52445. point2.z = point1.z + zaxis.z * scaleLines;
  52446. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  52447. };
  52448. AxesViewer.prototype.dispose = function () {
  52449. if (this._xmesh) {
  52450. this._xmesh.dispose();
  52451. this._ymesh.dispose();
  52452. this._zmesh.dispose();
  52453. this._xmesh = null;
  52454. this._ymesh = null;
  52455. this._zmesh = null;
  52456. this._xline = null;
  52457. this._yline = null;
  52458. this._zline = null;
  52459. this.scene = null;
  52460. }
  52461. };
  52462. return AxesViewer;
  52463. }());
  52464. Debug.AxesViewer = AxesViewer;
  52465. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52466. })(BABYLON || (BABYLON = {}));
  52467. //# sourceMappingURL=babylon.axesViewer.js.map
  52468. var BABYLON;
  52469. (function (BABYLON) {
  52470. var Debug;
  52471. (function (Debug) {
  52472. var BoneAxesViewer = (function (_super) {
  52473. __extends(BoneAxesViewer, _super);
  52474. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  52475. if (scaleLines === void 0) { scaleLines = 1; }
  52476. var _this = _super.call(this, scene, scaleLines) || this;
  52477. _this.pos = BABYLON.Vector3.Zero();
  52478. _this.xaxis = BABYLON.Vector3.Zero();
  52479. _this.yaxis = BABYLON.Vector3.Zero();
  52480. _this.zaxis = BABYLON.Vector3.Zero();
  52481. _this.mesh = mesh;
  52482. _this.bone = bone;
  52483. return _this;
  52484. }
  52485. BoneAxesViewer.prototype.update = function () {
  52486. var bone = this.bone;
  52487. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  52488. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  52489. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  52490. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  52491. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  52492. };
  52493. BoneAxesViewer.prototype.dispose = function () {
  52494. if (this.pos) {
  52495. this.pos = null;
  52496. this.xaxis = null;
  52497. this.yaxis = null;
  52498. this.zaxis = null;
  52499. this.mesh = null;
  52500. this.bone = null;
  52501. _super.prototype.dispose.call(this);
  52502. }
  52503. };
  52504. return BoneAxesViewer;
  52505. }(Debug.AxesViewer));
  52506. Debug.BoneAxesViewer = BoneAxesViewer;
  52507. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52508. })(BABYLON || (BABYLON = {}));
  52509. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  52510. var BABYLON;
  52511. (function (BABYLON) {
  52512. /**
  52513. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  52514. * It can help converting any input color in a desired output one. This can then be used to create effects
  52515. * from sepia, black and white to sixties or futuristic rendering...
  52516. *
  52517. * The only supported format is currently 3dl.
  52518. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  52519. */
  52520. var ColorGradingTexture = (function (_super) {
  52521. __extends(ColorGradingTexture, _super);
  52522. /**
  52523. * Instantiates a ColorGradingTexture from the following parameters.
  52524. *
  52525. * @param url The location of the color gradind data (currently only supporting 3dl)
  52526. * @param scene The scene the texture will be used in
  52527. */
  52528. function ColorGradingTexture(url, scene) {
  52529. var _this = _super.call(this, scene) || this;
  52530. if (!url) {
  52531. return _this;
  52532. }
  52533. _this._textureMatrix = BABYLON.Matrix.Identity();
  52534. _this.name = url;
  52535. _this.url = url;
  52536. _this.hasAlpha = false;
  52537. _this.isCube = false;
  52538. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52539. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52540. _this.anisotropicFilteringLevel = 1;
  52541. _this._texture = _this._getFromCache(url, true);
  52542. if (!_this._texture) {
  52543. if (!scene.useDelayedTextureLoading) {
  52544. _this.loadTexture();
  52545. }
  52546. else {
  52547. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  52548. }
  52549. }
  52550. return _this;
  52551. }
  52552. /**
  52553. * Returns the texture matrix used in most of the material.
  52554. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  52555. */
  52556. ColorGradingTexture.prototype.getTextureMatrix = function () {
  52557. return this._textureMatrix;
  52558. };
  52559. /**
  52560. * Occurs when the file being loaded is a .3dl LUT file.
  52561. */
  52562. ColorGradingTexture.prototype.load3dlTexture = function () {
  52563. var _this = this;
  52564. var mipLevels = 0;
  52565. var floatArrayView = null;
  52566. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52567. this._texture = texture;
  52568. var callback = function (text) {
  52569. var data;
  52570. var tempData;
  52571. var line;
  52572. var lines = text.split('\n');
  52573. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  52574. var maxColor = 0;
  52575. for (var i = 0; i < lines.length; i++) {
  52576. line = lines[i];
  52577. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  52578. continue;
  52579. if (line.indexOf('#') === 0)
  52580. continue;
  52581. var words = line.split(" ");
  52582. if (size === 0) {
  52583. // Number of space + one
  52584. size = words.length;
  52585. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  52586. tempData = new Float32Array(size * size * size * 4);
  52587. continue;
  52588. }
  52589. if (size != 0) {
  52590. var r = Math.max(parseInt(words[0]), 0);
  52591. var g = Math.max(parseInt(words[1]), 0);
  52592. var b = Math.max(parseInt(words[2]), 0);
  52593. maxColor = Math.max(r, maxColor);
  52594. maxColor = Math.max(g, maxColor);
  52595. maxColor = Math.max(b, maxColor);
  52596. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  52597. tempData[pixelStorageIndex + 0] = r;
  52598. tempData[pixelStorageIndex + 1] = g;
  52599. tempData[pixelStorageIndex + 2] = b;
  52600. tempData[pixelStorageIndex + 3] = 0;
  52601. pixelIndexSlice++;
  52602. if (pixelIndexSlice % size == 0) {
  52603. pixelIndexH++;
  52604. pixelIndexSlice = 0;
  52605. if (pixelIndexH % size == 0) {
  52606. pixelIndexW++;
  52607. pixelIndexH = 0;
  52608. }
  52609. }
  52610. }
  52611. }
  52612. for (var i = 0; i < tempData.length; i++) {
  52613. var value = tempData[i];
  52614. data[i] = (value / maxColor * 255);
  52615. }
  52616. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  52617. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  52618. };
  52619. BABYLON.Tools.LoadFile(this.url, callback);
  52620. return this._texture;
  52621. };
  52622. /**
  52623. * Starts the loading process of the texture.
  52624. */
  52625. ColorGradingTexture.prototype.loadTexture = function () {
  52626. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  52627. this.load3dlTexture();
  52628. }
  52629. };
  52630. /**
  52631. * Clones the color gradind texture.
  52632. */
  52633. ColorGradingTexture.prototype.clone = function () {
  52634. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  52635. // Base texture
  52636. newTexture.level = this.level;
  52637. return newTexture;
  52638. };
  52639. /**
  52640. * Called during delayed load for textures.
  52641. */
  52642. ColorGradingTexture.prototype.delayLoad = function () {
  52643. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  52644. return;
  52645. }
  52646. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  52647. this._texture = this._getFromCache(this.url, true);
  52648. if (!this._texture) {
  52649. this.loadTexture();
  52650. }
  52651. };
  52652. /**
  52653. * Binds the color grading to the shader.
  52654. * @param colorGrading The texture to bind
  52655. * @param effect The effect to bind to
  52656. */
  52657. ColorGradingTexture.Bind = function (colorGrading, effect) {
  52658. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  52659. var x = colorGrading.level; // Texture Level
  52660. var y = colorGrading.getSize().height; // Texture Size example with 8
  52661. var z = y - 1.0; // SizeMinusOne 8 - 1
  52662. var w = 1 / y; // Space of 1 slice 1 / 8
  52663. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  52664. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  52665. 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
  52666. 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
  52667. 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
  52668. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  52669. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  52670. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  52671. };
  52672. /**
  52673. * Prepare the list of uniforms associated with the ColorGrading effects.
  52674. * @param uniformsList The list of uniforms used in the effect
  52675. * @param samplersList The list of samplers used in the effect
  52676. */
  52677. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  52678. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  52679. samplersList.push("cameraColorGrading2DSampler");
  52680. };
  52681. /**
  52682. * Parses a color grading texture serialized by Babylon.
  52683. * @param parsedTexture The texture information being parsedTexture
  52684. * @param scene The scene to load the texture in
  52685. * @param rootUrl The root url of the data assets to load
  52686. * @return A color gradind texture
  52687. */
  52688. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  52689. var texture = null;
  52690. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  52691. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  52692. texture.name = parsedTexture.name;
  52693. texture.level = parsedTexture.level;
  52694. }
  52695. return texture;
  52696. };
  52697. /**
  52698. * Serializes the LUT texture to json format.
  52699. */
  52700. ColorGradingTexture.prototype.serialize = function () {
  52701. if (!this.name) {
  52702. return null;
  52703. }
  52704. var serializationObject = {};
  52705. serializationObject.name = this.name;
  52706. serializationObject.level = this.level;
  52707. serializationObject.customType = "BABYLON.ColorGradingTexture";
  52708. return serializationObject;
  52709. };
  52710. return ColorGradingTexture;
  52711. }(BABYLON.BaseTexture));
  52712. /**
  52713. * Empty line regex stored for GC.
  52714. */
  52715. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  52716. BABYLON.ColorGradingTexture = ColorGradingTexture;
  52717. })(BABYLON || (BABYLON = {}));
  52718. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  52719. var BABYLON;
  52720. (function (BABYLON) {
  52721. /**
  52722. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  52723. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  52724. * 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;
  52725. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  52726. */
  52727. var ColorCurves = (function () {
  52728. function ColorCurves() {
  52729. this._dirty = true;
  52730. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  52731. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  52732. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  52733. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  52734. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  52735. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  52736. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  52737. this._globalHue = 30;
  52738. this._globalDensity = 0;
  52739. this._globalSaturation = 0;
  52740. this._globalExposure = 0;
  52741. this._highlightsHue = 30;
  52742. this._highlightsDensity = 0;
  52743. this._highlightsSaturation = 0;
  52744. this._highlightsExposure = 0;
  52745. this._midtonesHue = 30;
  52746. this._midtonesDensity = 0;
  52747. this._midtonesSaturation = 0;
  52748. this._midtonesExposure = 0;
  52749. this._shadowsHue = 30;
  52750. this._shadowsDensity = 0;
  52751. this._shadowsSaturation = 0;
  52752. this._shadowsExposure = 0;
  52753. }
  52754. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  52755. /**
  52756. * Gets the global Hue value.
  52757. * 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).
  52758. */
  52759. get: function () {
  52760. return this._globalHue;
  52761. },
  52762. /**
  52763. * Sets the global Hue value.
  52764. * 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).
  52765. */
  52766. set: function (value) {
  52767. this._globalHue = value;
  52768. this._dirty = true;
  52769. },
  52770. enumerable: true,
  52771. configurable: true
  52772. });
  52773. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  52774. /**
  52775. * Gets the global Density value.
  52776. * 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.
  52777. * Values less than zero provide a filter of opposite hue.
  52778. */
  52779. get: function () {
  52780. return this._globalDensity;
  52781. },
  52782. /**
  52783. * Sets the global Density value.
  52784. * 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.
  52785. * Values less than zero provide a filter of opposite hue.
  52786. */
  52787. set: function (value) {
  52788. this._globalDensity = value;
  52789. this._dirty = true;
  52790. },
  52791. enumerable: true,
  52792. configurable: true
  52793. });
  52794. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  52795. /**
  52796. * Gets the global Saturation value.
  52797. * 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.
  52798. */
  52799. get: function () {
  52800. return this._globalSaturation;
  52801. },
  52802. /**
  52803. * Sets the global Saturation value.
  52804. * 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.
  52805. */
  52806. set: function (value) {
  52807. this._globalSaturation = value;
  52808. this._dirty = true;
  52809. },
  52810. enumerable: true,
  52811. configurable: true
  52812. });
  52813. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  52814. /**
  52815. * Gets the highlights Hue value.
  52816. * 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).
  52817. */
  52818. get: function () {
  52819. return this._highlightsHue;
  52820. },
  52821. /**
  52822. * Sets the highlights Hue value.
  52823. * 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).
  52824. */
  52825. set: function (value) {
  52826. this._highlightsHue = value;
  52827. this._dirty = true;
  52828. },
  52829. enumerable: true,
  52830. configurable: true
  52831. });
  52832. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  52833. /**
  52834. * Gets the highlights Density value.
  52835. * 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.
  52836. * Values less than zero provide a filter of opposite hue.
  52837. */
  52838. get: function () {
  52839. return this._highlightsDensity;
  52840. },
  52841. /**
  52842. * Sets the highlights Density value.
  52843. * 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.
  52844. * Values less than zero provide a filter of opposite hue.
  52845. */
  52846. set: function (value) {
  52847. this._highlightsDensity = value;
  52848. this._dirty = true;
  52849. },
  52850. enumerable: true,
  52851. configurable: true
  52852. });
  52853. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  52854. /**
  52855. * Gets the highlights Saturation value.
  52856. * 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.
  52857. */
  52858. get: function () {
  52859. return this._highlightsSaturation;
  52860. },
  52861. /**
  52862. * Sets the highlights Saturation value.
  52863. * 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.
  52864. */
  52865. set: function (value) {
  52866. this._highlightsSaturation = value;
  52867. this._dirty = true;
  52868. },
  52869. enumerable: true,
  52870. configurable: true
  52871. });
  52872. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  52873. /**
  52874. * Gets the highlights Exposure value.
  52875. * 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.
  52876. */
  52877. get: function () {
  52878. return this._highlightsExposure;
  52879. },
  52880. /**
  52881. * Sets the highlights Exposure value.
  52882. * 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.
  52883. */
  52884. set: function (value) {
  52885. this._highlightsExposure = value;
  52886. this._dirty = true;
  52887. },
  52888. enumerable: true,
  52889. configurable: true
  52890. });
  52891. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  52892. /**
  52893. * Gets the midtones Hue value.
  52894. * 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).
  52895. */
  52896. get: function () {
  52897. return this._midtonesHue;
  52898. },
  52899. /**
  52900. * Sets the midtones Hue value.
  52901. * 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).
  52902. */
  52903. set: function (value) {
  52904. this._midtonesHue = value;
  52905. this._dirty = true;
  52906. },
  52907. enumerable: true,
  52908. configurable: true
  52909. });
  52910. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  52911. /**
  52912. * Gets the midtones Density value.
  52913. * 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.
  52914. * Values less than zero provide a filter of opposite hue.
  52915. */
  52916. get: function () {
  52917. return this._midtonesDensity;
  52918. },
  52919. /**
  52920. * Sets the midtones Density value.
  52921. * 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.
  52922. * Values less than zero provide a filter of opposite hue.
  52923. */
  52924. set: function (value) {
  52925. this._midtonesDensity = value;
  52926. this._dirty = true;
  52927. },
  52928. enumerable: true,
  52929. configurable: true
  52930. });
  52931. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  52932. /**
  52933. * Gets the midtones Saturation value.
  52934. * 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.
  52935. */
  52936. get: function () {
  52937. return this._midtonesSaturation;
  52938. },
  52939. /**
  52940. * Sets the midtones Saturation value.
  52941. * 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.
  52942. */
  52943. set: function (value) {
  52944. this._midtonesSaturation = value;
  52945. this._dirty = true;
  52946. },
  52947. enumerable: true,
  52948. configurable: true
  52949. });
  52950. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  52951. /**
  52952. * Gets the midtones Exposure value.
  52953. * 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.
  52954. */
  52955. get: function () {
  52956. return this._midtonesExposure;
  52957. },
  52958. /**
  52959. * Sets the midtones Exposure value.
  52960. * 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.
  52961. */
  52962. set: function (value) {
  52963. this._midtonesExposure = value;
  52964. this._dirty = true;
  52965. },
  52966. enumerable: true,
  52967. configurable: true
  52968. });
  52969. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  52970. /**
  52971. * Gets the shadows Hue value.
  52972. * 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).
  52973. */
  52974. get: function () {
  52975. return this._shadowsHue;
  52976. },
  52977. /**
  52978. * Sets the shadows Hue value.
  52979. * 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).
  52980. */
  52981. set: function (value) {
  52982. this._shadowsHue = value;
  52983. this._dirty = true;
  52984. },
  52985. enumerable: true,
  52986. configurable: true
  52987. });
  52988. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  52989. /**
  52990. * Gets the shadows Density value.
  52991. * 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.
  52992. * Values less than zero provide a filter of opposite hue.
  52993. */
  52994. get: function () {
  52995. return this._shadowsDensity;
  52996. },
  52997. /**
  52998. * Sets the shadows Density value.
  52999. * 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.
  53000. * Values less than zero provide a filter of opposite hue.
  53001. */
  53002. set: function (value) {
  53003. this._shadowsDensity = value;
  53004. this._dirty = true;
  53005. },
  53006. enumerable: true,
  53007. configurable: true
  53008. });
  53009. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  53010. /**
  53011. * Gets the shadows Saturation value.
  53012. * 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.
  53013. */
  53014. get: function () {
  53015. return this._shadowsSaturation;
  53016. },
  53017. /**
  53018. * Sets the shadows Saturation value.
  53019. * 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.
  53020. */
  53021. set: function (value) {
  53022. this._shadowsSaturation = value;
  53023. this._dirty = true;
  53024. },
  53025. enumerable: true,
  53026. configurable: true
  53027. });
  53028. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  53029. /**
  53030. * Gets the shadows Exposure value.
  53031. * 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.
  53032. */
  53033. get: function () {
  53034. return this._shadowsExposure;
  53035. },
  53036. /**
  53037. * Sets the shadows Exposure value.
  53038. * 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.
  53039. */
  53040. set: function (value) {
  53041. this._shadowsExposure = value;
  53042. this._dirty = true;
  53043. },
  53044. enumerable: true,
  53045. configurable: true
  53046. });
  53047. /**
  53048. * Binds the color curves to the shader.
  53049. * @param colorCurves The color curve to bind
  53050. * @param effect The effect to bind to
  53051. */
  53052. ColorCurves.Bind = function (colorCurves, effect) {
  53053. if (colorCurves._dirty) {
  53054. colorCurves._dirty = false;
  53055. // Fill in global info.
  53056. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  53057. // Compute highlights info.
  53058. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  53059. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  53060. // Compute midtones info.
  53061. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  53062. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  53063. // Compute shadows info.
  53064. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  53065. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  53066. // Compute deltas (neutral is midtones).
  53067. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  53068. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  53069. }
  53070. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  53071. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  53072. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  53073. };
  53074. /**
  53075. * Prepare the list of uniforms associated with the ColorCurves effects.
  53076. * @param uniformsList The list of uniforms used in the effect
  53077. */
  53078. ColorCurves.PrepareUniforms = function (uniformsList) {
  53079. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  53080. };
  53081. /**
  53082. * Returns color grading data based on a hue, density, saturation and exposure value.
  53083. * @param filterHue The hue of the color filter.
  53084. * @param filterDensity The density of the color filter.
  53085. * @param saturation The saturation.
  53086. * @param exposure The exposure.
  53087. * @param result The result data container.
  53088. */
  53089. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  53090. if (hue == null) {
  53091. return;
  53092. }
  53093. hue = ColorCurves.clamp(hue, 0, 360);
  53094. density = ColorCurves.clamp(density, -100, 100);
  53095. saturation = ColorCurves.clamp(saturation, -100, 100);
  53096. exposure = ColorCurves.clamp(exposure, -100, 100);
  53097. // Remap the slider/config filter density with non-linear mapping and also scale by half
  53098. // so that the maximum filter density is only 50% control. This provides fine control
  53099. // for small values and reasonable range.
  53100. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  53101. density *= 0.5;
  53102. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  53103. if (density < 0) {
  53104. density *= -1;
  53105. hue = (hue + 180) % 360;
  53106. }
  53107. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  53108. result.scaleToRef(2, result);
  53109. result.a = 1 + 0.01 * saturation;
  53110. };
  53111. /**
  53112. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  53113. * @param value The input slider value in range [-100,100].
  53114. * @returns Adjusted value.
  53115. */
  53116. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  53117. value /= 100;
  53118. var x = Math.abs(value);
  53119. x = Math.pow(x, 2);
  53120. if (value < 0) {
  53121. x *= -1;
  53122. }
  53123. x *= 100;
  53124. return x;
  53125. };
  53126. /**
  53127. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  53128. * @param hue The hue (H) input.
  53129. * @param saturation The saturation (S) input.
  53130. * @param brightness The brightness (B) input.
  53131. * @result An RGBA color represented as Vector4.
  53132. */
  53133. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  53134. var h = ColorCurves.clamp(hue, 0, 360);
  53135. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  53136. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  53137. if (s === 0) {
  53138. result.r = v;
  53139. result.g = v;
  53140. result.b = v;
  53141. }
  53142. else {
  53143. // sector 0 to 5
  53144. h /= 60;
  53145. var i = Math.floor(h);
  53146. // fractional part of h
  53147. var f = h - i;
  53148. var p = v * (1 - s);
  53149. var q = v * (1 - s * f);
  53150. var t = v * (1 - s * (1 - f));
  53151. switch (i) {
  53152. case 0:
  53153. result.r = v;
  53154. result.g = t;
  53155. result.b = p;
  53156. break;
  53157. case 1:
  53158. result.r = q;
  53159. result.g = v;
  53160. result.b = p;
  53161. break;
  53162. case 2:
  53163. result.r = p;
  53164. result.g = v;
  53165. result.b = t;
  53166. break;
  53167. case 3:
  53168. result.r = p;
  53169. result.g = q;
  53170. result.b = v;
  53171. break;
  53172. case 4:
  53173. result.r = t;
  53174. result.g = p;
  53175. result.b = v;
  53176. break;
  53177. default:
  53178. result.r = v;
  53179. result.g = p;
  53180. result.b = q;
  53181. break;
  53182. }
  53183. }
  53184. result.a = 1;
  53185. };
  53186. /**
  53187. * Returns a value clamped between min and max
  53188. * @param value The value to clamp
  53189. * @param min The minimum of value
  53190. * @param max The maximum of value
  53191. * @returns The clamped value.
  53192. */
  53193. ColorCurves.clamp = function (value, min, max) {
  53194. return Math.min(Math.max(value, min), max);
  53195. };
  53196. /**
  53197. * Clones the current color curve instance.
  53198. * @return The cloned curves
  53199. */
  53200. ColorCurves.prototype.clone = function () {
  53201. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  53202. };
  53203. /**
  53204. * Serializes the current color curve instance to a json representation.
  53205. * @return a JSON representation
  53206. */
  53207. ColorCurves.prototype.serialize = function () {
  53208. return BABYLON.SerializationHelper.Serialize(this);
  53209. };
  53210. /**
  53211. * Parses the color curve from a json representation.
  53212. * @param source the JSON source to parse
  53213. * @return The parsed curves
  53214. */
  53215. ColorCurves.Parse = function (source) {
  53216. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  53217. };
  53218. return ColorCurves;
  53219. }());
  53220. __decorate([
  53221. BABYLON.serialize()
  53222. ], ColorCurves.prototype, "_globalHue", void 0);
  53223. __decorate([
  53224. BABYLON.serialize()
  53225. ], ColorCurves.prototype, "_globalDensity", void 0);
  53226. __decorate([
  53227. BABYLON.serialize()
  53228. ], ColorCurves.prototype, "_globalSaturation", void 0);
  53229. __decorate([
  53230. BABYLON.serialize()
  53231. ], ColorCurves.prototype, "_globalExposure", void 0);
  53232. __decorate([
  53233. BABYLON.serialize()
  53234. ], ColorCurves.prototype, "_highlightsHue", void 0);
  53235. __decorate([
  53236. BABYLON.serialize()
  53237. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  53238. __decorate([
  53239. BABYLON.serialize()
  53240. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  53241. __decorate([
  53242. BABYLON.serialize()
  53243. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  53244. __decorate([
  53245. BABYLON.serialize()
  53246. ], ColorCurves.prototype, "_midtonesHue", void 0);
  53247. __decorate([
  53248. BABYLON.serialize()
  53249. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  53250. __decorate([
  53251. BABYLON.serialize()
  53252. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  53253. __decorate([
  53254. BABYLON.serialize()
  53255. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  53256. BABYLON.ColorCurves = ColorCurves;
  53257. })(BABYLON || (BABYLON = {}));
  53258. //# sourceMappingURL=babylon.colorCurves.js.map
  53259. var BABYLON;
  53260. (function (BABYLON) {
  53261. var PBRMaterialDefines = (function (_super) {
  53262. __extends(PBRMaterialDefines, _super);
  53263. function PBRMaterialDefines() {
  53264. var _this = _super.call(this) || this;
  53265. _this.ALBEDO = false;
  53266. _this.AMBIENT = false;
  53267. _this.OPACITY = false;
  53268. _this.OPACITYRGB = false;
  53269. _this.REFLECTION = false;
  53270. _this.EMISSIVE = false;
  53271. _this.REFLECTIVITY = false;
  53272. _this.BUMP = false;
  53273. _this.PARALLAX = false;
  53274. _this.PARALLAXOCCLUSION = false;
  53275. _this.SPECULAROVERALPHA = false;
  53276. _this.CLIPPLANE = false;
  53277. _this.ALPHATEST = false;
  53278. _this.ALPHAFROMALBEDO = false;
  53279. _this.POINTSIZE = false;
  53280. _this.FOG = false;
  53281. _this.SPECULARTERM = false;
  53282. _this.OPACITYFRESNEL = false;
  53283. _this.EMISSIVEFRESNEL = false;
  53284. _this.FRESNEL = false;
  53285. _this.NORMAL = false;
  53286. _this.UV1 = false;
  53287. _this.UV2 = false;
  53288. _this.VERTEXCOLOR = false;
  53289. _this.VERTEXALPHA = false;
  53290. _this.NUM_BONE_INFLUENCERS = 0;
  53291. _this.BonesPerMesh = 0;
  53292. _this.INSTANCES = false;
  53293. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  53294. _this.MICROSURFACEAUTOMATIC = false;
  53295. _this.EMISSIVEASILLUMINATION = false;
  53296. _this.LINKEMISSIVEWITHALBEDO = false;
  53297. _this.LIGHTMAP = false;
  53298. _this.USELIGHTMAPASSHADOWMAP = false;
  53299. _this.REFLECTIONMAP_3D = false;
  53300. _this.REFLECTIONMAP_SPHERICAL = false;
  53301. _this.REFLECTIONMAP_PLANAR = false;
  53302. _this.REFLECTIONMAP_CUBIC = false;
  53303. _this.REFLECTIONMAP_PROJECTION = false;
  53304. _this.REFLECTIONMAP_SKYBOX = false;
  53305. _this.REFLECTIONMAP_EXPLICIT = false;
  53306. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  53307. _this.INVERTCUBICMAP = false;
  53308. _this.LOGARITHMICDEPTH = false;
  53309. _this.CAMERATONEMAP = false;
  53310. _this.CAMERACONTRAST = false;
  53311. _this.CAMERACOLORGRADING = false;
  53312. _this.CAMERACOLORCURVES = false;
  53313. _this.OVERLOADEDVALUES = false;
  53314. _this.OVERLOADEDSHADOWVALUES = false;
  53315. _this.USESPHERICALFROMREFLECTIONMAP = false;
  53316. _this.REFRACTION = false;
  53317. _this.REFRACTIONMAP_3D = false;
  53318. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  53319. _this.REFRACTIONMAPINLINEARSPACE = false;
  53320. _this.LODBASEDMICROSFURACE = false;
  53321. _this.USEPHYSICALLIGHTFALLOFF = false;
  53322. _this.RADIANCEOVERALPHA = false;
  53323. _this.USEPMREMREFLECTION = false;
  53324. _this.USEPMREMREFRACTION = false;
  53325. _this.OPENGLNORMALMAP = false;
  53326. _this.INVERTNORMALMAPX = false;
  53327. _this.INVERTNORMALMAPY = false;
  53328. _this.SHADOWFULLFLOAT = false;
  53329. _this.METALLICWORKFLOW = false;
  53330. _this.METALLICROUGHNESSMAP = false;
  53331. _this.METALLICROUGHNESSGSTOREINALPHA = false;
  53332. _this.METALLICROUGHNESSGSTOREINGREEN = false;
  53333. _this.rebuild();
  53334. return _this;
  53335. }
  53336. return PBRMaterialDefines;
  53337. }(BABYLON.MaterialDefines));
  53338. /**
  53339. * The Physically based material of BJS.
  53340. *
  53341. * This offers the main features of a standard PBR material.
  53342. * For more information, please refer to the documentation :
  53343. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  53344. */
  53345. var PBRMaterial = (function (_super) {
  53346. __extends(PBRMaterial, _super);
  53347. /**
  53348. * Instantiates a new PBRMaterial instance.
  53349. *
  53350. * @param name The material name
  53351. * @param scene The scene the material will be use in.
  53352. */
  53353. function PBRMaterial(name, scene) {
  53354. var _this = _super.call(this, name, scene) || this;
  53355. /**
  53356. * Intensity of the direct lights e.g. the four lights available in your scene.
  53357. * This impacts both the direct diffuse and specular highlights.
  53358. */
  53359. _this.directIntensity = 1.0;
  53360. /**
  53361. * Intensity of the emissive part of the material.
  53362. * This helps controlling the emissive effect without modifying the emissive color.
  53363. */
  53364. _this.emissiveIntensity = 1.0;
  53365. /**
  53366. * Intensity of the environment e.g. how much the environment will light the object
  53367. * either through harmonics for rough material or through the refelction for shiny ones.
  53368. */
  53369. _this.environmentIntensity = 1.0;
  53370. /**
  53371. * This is a special control allowing the reduction of the specular highlights coming from the
  53372. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  53373. */
  53374. _this.specularIntensity = 1.0;
  53375. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  53376. /**
  53377. * Debug Control allowing disabling the bump map on this material.
  53378. */
  53379. _this.disableBumpMap = false;
  53380. /**
  53381. * Debug Control helping enforcing or dropping the darkness of shadows.
  53382. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  53383. */
  53384. _this.overloadedShadowIntensity = 1.0;
  53385. /**
  53386. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  53387. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  53388. */
  53389. _this.overloadedShadeIntensity = 1.0;
  53390. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  53391. /**
  53392. * The camera exposure used on this material.
  53393. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  53394. * This corresponds to a photographic exposure.
  53395. */
  53396. _this.cameraExposure = 1.0;
  53397. /**
  53398. * The camera contrast used on this material.
  53399. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  53400. */
  53401. _this.cameraContrast = 1.0;
  53402. /**
  53403. * Color Grading 2D Lookup Texture.
  53404. * This allows special effects like sepia, black and white to sixties rendering style.
  53405. */
  53406. _this.cameraColorGradingTexture = null;
  53407. /**
  53408. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  53409. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  53410. * 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;
  53411. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  53412. */
  53413. _this.cameraColorCurves = null;
  53414. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  53415. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  53416. /**
  53417. * Debug Control allowing to overload the ambient color.
  53418. * This as to be use with the overloadedAmbientIntensity parameter.
  53419. */
  53420. _this.overloadedAmbient = BABYLON.Color3.White();
  53421. /**
  53422. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  53423. */
  53424. _this.overloadedAmbientIntensity = 0.0;
  53425. /**
  53426. * Debug Control allowing to overload the albedo color.
  53427. * This as to be use with the overloadedAlbedoIntensity parameter.
  53428. */
  53429. _this.overloadedAlbedo = BABYLON.Color3.White();
  53430. /**
  53431. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  53432. */
  53433. _this.overloadedAlbedoIntensity = 0.0;
  53434. /**
  53435. * Debug Control allowing to overload the reflectivity color.
  53436. * This as to be use with the overloadedReflectivityIntensity parameter.
  53437. */
  53438. _this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  53439. /**
  53440. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  53441. */
  53442. _this.overloadedReflectivityIntensity = 0.0;
  53443. /**
  53444. * Debug Control allowing to overload the emissive color.
  53445. * This as to be use with the overloadedEmissiveIntensity parameter.
  53446. */
  53447. _this.overloadedEmissive = BABYLON.Color3.White();
  53448. /**
  53449. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  53450. */
  53451. _this.overloadedEmissiveIntensity = 0.0;
  53452. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  53453. /**
  53454. * Debug Control allowing to overload the reflection color.
  53455. * This as to be use with the overloadedReflectionIntensity parameter.
  53456. */
  53457. _this.overloadedReflection = BABYLON.Color3.White();
  53458. /**
  53459. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  53460. */
  53461. _this.overloadedReflectionIntensity = 0.0;
  53462. /**
  53463. * Debug Control allowing to overload the microsurface.
  53464. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  53465. */
  53466. _this.overloadedMicroSurface = 0.0;
  53467. /**
  53468. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  53469. */
  53470. _this.overloadedMicroSurfaceIntensity = 0.0;
  53471. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  53472. /**
  53473. * AKA Occlusion Texture Intensity in other nomenclature.
  53474. */
  53475. _this.ambientTextureStrength = 1.0;
  53476. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  53477. /**
  53478. * AKA Diffuse Color in other nomenclature.
  53479. */
  53480. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  53481. /**
  53482. * AKA Specular Color in other nomenclature.
  53483. */
  53484. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  53485. _this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  53486. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  53487. /**
  53488. * AKA Glossiness in other nomenclature.
  53489. */
  53490. _this.microSurface = 0.9;
  53491. /**
  53492. * source material index of refraction (IOR)' / 'destination material IOR.
  53493. */
  53494. _this.indexOfRefraction = 0.66;
  53495. /**
  53496. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  53497. */
  53498. _this.invertRefractionY = false;
  53499. /**
  53500. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  53501. * Materials half opaque for instance using refraction could benefit from this control.
  53502. */
  53503. _this.linkRefractionWithTransparency = false;
  53504. /**
  53505. * The emissive and albedo are linked to never be more than one (Energy conservation).
  53506. */
  53507. _this.linkEmissiveWithAlbedo = false;
  53508. _this.useLightmapAsShadowmap = false;
  53509. /**
  53510. * In this mode, the emissive informtaion will always be added to the lighting once.
  53511. * A light for instance can be thought as emissive.
  53512. */
  53513. _this.useEmissiveAsIllumination = false;
  53514. /**
  53515. * Secifies that the alpha is coming form the albedo channel alpha channel.
  53516. */
  53517. _this.useAlphaFromAlbedoTexture = false;
  53518. /**
  53519. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  53520. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  53521. */
  53522. _this.useSpecularOverAlpha = true;
  53523. /**
  53524. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  53525. */
  53526. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  53527. /**
  53528. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  53529. */
  53530. _this.useRoughnessFromMetallicTextureAlpha = true;
  53531. /**
  53532. * Specifies if the metallic texture contains the roughness information in its green channel.
  53533. */
  53534. _this.useRoughnessFromMetallicTextureGreen = false;
  53535. /**
  53536. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  53537. * The material will try to infer what glossiness each pixel should be.
  53538. */
  53539. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  53540. /**
  53541. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  53542. * the creation of the material.
  53543. */
  53544. _this.useScalarInLinearSpace = false;
  53545. /**
  53546. * BJS is using an harcoded light falloff based on a manually sets up range.
  53547. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  53548. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  53549. */
  53550. _this.usePhysicalLightFalloff = true;
  53551. /**
  53552. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  53553. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  53554. */
  53555. _this.useRadianceOverAlpha = true;
  53556. /**
  53557. * Allows using the bump map in parallax mode.
  53558. */
  53559. _this.useParallax = false;
  53560. /**
  53561. * Allows using the bump map in parallax occlusion mode.
  53562. */
  53563. _this.useParallaxOcclusion = false;
  53564. /**
  53565. * Controls the scale bias of the parallax mode.
  53566. */
  53567. _this.parallaxScaleBias = 0.05;
  53568. /**
  53569. * If sets to true, disables all the lights affecting the material.
  53570. */
  53571. _this.disableLighting = false;
  53572. /**
  53573. * Number of Simultaneous lights allowed on the material.
  53574. */
  53575. _this.maxSimultaneousLights = 4;
  53576. /**
  53577. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  53578. */
  53579. _this.invertNormalMapX = false;
  53580. /**
  53581. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  53582. */
  53583. _this.invertNormalMapY = false;
  53584. _this._renderTargets = new BABYLON.SmartArray(16);
  53585. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  53586. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  53587. _this._tempColor = new BABYLON.Color3();
  53588. _this._defines = new PBRMaterialDefines();
  53589. _this._cachedDefines = new PBRMaterialDefines();
  53590. _this._myScene = null;
  53591. _this._myShadowGenerator = null;
  53592. _this._cachedDefines.BonesPerMesh = -1;
  53593. _this.getRenderTargetTextures = function () {
  53594. _this._renderTargets.reset();
  53595. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  53596. _this._renderTargets.push(_this.reflectionTexture);
  53597. }
  53598. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  53599. _this._renderTargets.push(_this.refractionTexture);
  53600. }
  53601. return _this._renderTargets;
  53602. };
  53603. return _this;
  53604. }
  53605. PBRMaterial.prototype.getClassName = function () {
  53606. return "PBRMaterial";
  53607. };
  53608. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  53609. get: function () {
  53610. return this._useLogarithmicDepth;
  53611. },
  53612. set: function (value) {
  53613. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  53614. },
  53615. enumerable: true,
  53616. configurable: true
  53617. });
  53618. PBRMaterial.prototype.needAlphaBlending = function () {
  53619. if (this.linkRefractionWithTransparency) {
  53620. return false;
  53621. }
  53622. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  53623. };
  53624. PBRMaterial.prototype.needAlphaTesting = function () {
  53625. if (this.linkRefractionWithTransparency) {
  53626. return false;
  53627. }
  53628. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  53629. };
  53630. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  53631. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  53632. };
  53633. PBRMaterial.prototype.getAlphaTestTexture = function () {
  53634. return this.albedoTexture;
  53635. };
  53636. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53637. if (!mesh) {
  53638. return true;
  53639. }
  53640. if (this._defines.INSTANCES !== useInstances) {
  53641. return false;
  53642. }
  53643. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  53644. return true;
  53645. }
  53646. return false;
  53647. };
  53648. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  53649. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  53650. };
  53651. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  53652. if (!useScalarInLinear) {
  53653. color.toLinearSpaceToRef(ref);
  53654. }
  53655. else {
  53656. ref.r = color.r;
  53657. ref.g = color.g;
  53658. ref.b = color.b;
  53659. }
  53660. };
  53661. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  53662. var lightIndex = 0;
  53663. var depthValuesAlreadySet = false;
  53664. for (var index = 0; index < scene.lights.length; index++) {
  53665. var light = scene.lights[index];
  53666. if (!light.isEnabled()) {
  53667. continue;
  53668. }
  53669. if (!light.canAffectMesh(mesh)) {
  53670. continue;
  53671. }
  53672. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  53673. // GAMMA CORRECTION.
  53674. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  53675. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  53676. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  53677. if (defines["SPECULARTERM"]) {
  53678. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  53679. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  53680. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  53681. }
  53682. // Shadows
  53683. if (scene.shadowsEnabled) {
  53684. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  53685. }
  53686. lightIndex++;
  53687. if (lightIndex === maxSimultaneousLights)
  53688. break;
  53689. }
  53690. };
  53691. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  53692. if (this.isFrozen) {
  53693. if (this._wasPreviouslyReady) {
  53694. return true;
  53695. }
  53696. }
  53697. var scene = this.getScene();
  53698. var engine = scene.getEngine();
  53699. var needNormals = false;
  53700. var needUVs = false;
  53701. this._defines.reset();
  53702. if (scene.lightsEnabled && !this.disableLighting) {
  53703. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  53704. }
  53705. if (!this.checkReadyOnEveryCall) {
  53706. if (this._renderId === scene.getRenderId()) {
  53707. if (this._checkCache(scene, mesh, useInstances)) {
  53708. return true;
  53709. }
  53710. }
  53711. }
  53712. if (scene.texturesEnabled) {
  53713. if (scene.getEngine().getCaps().textureLOD) {
  53714. this._defines.LODBASEDMICROSFURACE = true;
  53715. }
  53716. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53717. if (!this.albedoTexture.isReady()) {
  53718. return false;
  53719. }
  53720. else {
  53721. needUVs = true;
  53722. this._defines.ALBEDO = true;
  53723. }
  53724. }
  53725. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  53726. if (!this.ambientTexture.isReady()) {
  53727. return false;
  53728. }
  53729. else {
  53730. needUVs = true;
  53731. this._defines.AMBIENT = true;
  53732. }
  53733. }
  53734. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  53735. if (!this.opacityTexture.isReady()) {
  53736. return false;
  53737. }
  53738. else {
  53739. needUVs = true;
  53740. this._defines.OPACITY = true;
  53741. if (this.opacityTexture.getAlphaFromRGB) {
  53742. this._defines.OPACITYRGB = true;
  53743. }
  53744. }
  53745. }
  53746. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  53747. if (!this.reflectionTexture.isReady()) {
  53748. return false;
  53749. }
  53750. else {
  53751. needNormals = true;
  53752. this._defines.REFLECTION = true;
  53753. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  53754. this._defines.INVERTCUBICMAP = true;
  53755. }
  53756. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  53757. switch (this.reflectionTexture.coordinatesMode) {
  53758. case BABYLON.Texture.CUBIC_MODE:
  53759. case BABYLON.Texture.INVCUBIC_MODE:
  53760. this._defines.REFLECTIONMAP_CUBIC = true;
  53761. break;
  53762. case BABYLON.Texture.EXPLICIT_MODE:
  53763. this._defines.REFLECTIONMAP_EXPLICIT = true;
  53764. break;
  53765. case BABYLON.Texture.PLANAR_MODE:
  53766. this._defines.REFLECTIONMAP_PLANAR = true;
  53767. break;
  53768. case BABYLON.Texture.PROJECTION_MODE:
  53769. this._defines.REFLECTIONMAP_PROJECTION = true;
  53770. break;
  53771. case BABYLON.Texture.SKYBOX_MODE:
  53772. this._defines.REFLECTIONMAP_SKYBOX = true;
  53773. break;
  53774. case BABYLON.Texture.SPHERICAL_MODE:
  53775. this._defines.REFLECTIONMAP_SPHERICAL = true;
  53776. break;
  53777. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  53778. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  53779. break;
  53780. }
  53781. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  53782. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  53783. needNormals = true;
  53784. if (this.reflectionTexture.isPMREM) {
  53785. this._defines.USEPMREMREFLECTION = true;
  53786. }
  53787. }
  53788. }
  53789. }
  53790. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  53791. if (!this.lightmapTexture.isReady()) {
  53792. return false;
  53793. }
  53794. else {
  53795. needUVs = true;
  53796. this._defines.LIGHTMAP = true;
  53797. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  53798. }
  53799. }
  53800. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  53801. if (!this.emissiveTexture.isReady()) {
  53802. return false;
  53803. }
  53804. else {
  53805. needUVs = true;
  53806. this._defines.EMISSIVE = true;
  53807. }
  53808. }
  53809. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  53810. if (this.metallicTexture) {
  53811. if (!this.metallicTexture.isReady()) {
  53812. return false;
  53813. }
  53814. else {
  53815. needUVs = true;
  53816. this._defines.METALLICWORKFLOW = true;
  53817. this._defines.METALLICROUGHNESSMAP = true;
  53818. this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
  53819. this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  53820. }
  53821. }
  53822. else if (this.reflectivityTexture) {
  53823. if (!this.reflectivityTexture.isReady()) {
  53824. return false;
  53825. }
  53826. else {
  53827. needUVs = true;
  53828. this._defines.REFLECTIVITY = true;
  53829. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  53830. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  53831. }
  53832. }
  53833. }
  53834. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  53835. if (!this.bumpTexture.isReady()) {
  53836. return false;
  53837. }
  53838. else {
  53839. needUVs = true;
  53840. this._defines.BUMP = true;
  53841. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53842. this._defines.PARALLAX = true;
  53843. if (this.useParallaxOcclusion) {
  53844. this._defines.PARALLAXOCCLUSION = true;
  53845. }
  53846. }
  53847. if (this.invertNormalMapX) {
  53848. this._defines.INVERTNORMALMAPX = true;
  53849. }
  53850. if (this.invertNormalMapY) {
  53851. this._defines.INVERTNORMALMAPY = true;
  53852. }
  53853. if (scene._mirroredCameraPosition) {
  53854. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  53855. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  53856. }
  53857. }
  53858. }
  53859. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  53860. if (!this.refractionTexture.isReady()) {
  53861. return false;
  53862. }
  53863. else {
  53864. needUVs = true;
  53865. this._defines.REFRACTION = true;
  53866. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  53867. if (this.linkRefractionWithTransparency) {
  53868. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  53869. }
  53870. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  53871. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  53872. if (this.refractionTexture.isPMREM) {
  53873. this._defines.USEPMREMREFRACTION = true;
  53874. }
  53875. }
  53876. }
  53877. }
  53878. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  53879. if (!this.cameraColorGradingTexture.isReady()) {
  53880. return false;
  53881. }
  53882. else {
  53883. this._defines.CAMERACOLORGRADING = true;
  53884. }
  53885. }
  53886. }
  53887. // Effect
  53888. if (scene.clipPlane) {
  53889. this._defines.CLIPPLANE = true;
  53890. }
  53891. if (engine.getAlphaTesting()) {
  53892. this._defines.ALPHATEST = true;
  53893. }
  53894. if (this._shouldUseAlphaFromAlbedoTexture()) {
  53895. this._defines.ALPHAFROMALBEDO = true;
  53896. }
  53897. if (this.useEmissiveAsIllumination) {
  53898. this._defines.EMISSIVEASILLUMINATION = true;
  53899. }
  53900. if (this.linkEmissiveWithAlbedo) {
  53901. this._defines.LINKEMISSIVEWITHALBEDO = true;
  53902. }
  53903. if (this.useLogarithmicDepth) {
  53904. this._defines.LOGARITHMICDEPTH = true;
  53905. }
  53906. if (this.cameraContrast != 1) {
  53907. this._defines.CAMERACONTRAST = true;
  53908. }
  53909. if (this.cameraExposure != 1) {
  53910. this._defines.CAMERATONEMAP = true;
  53911. }
  53912. if (this.cameraColorCurves) {
  53913. this._defines.CAMERACOLORCURVES = true;
  53914. }
  53915. if (this.overloadedShadeIntensity != 1 ||
  53916. this.overloadedShadowIntensity != 1) {
  53917. this._defines.OVERLOADEDSHADOWVALUES = true;
  53918. }
  53919. if (this.overloadedMicroSurfaceIntensity > 0 ||
  53920. this.overloadedEmissiveIntensity > 0 ||
  53921. this.overloadedReflectivityIntensity > 0 ||
  53922. this.overloadedAlbedoIntensity > 0 ||
  53923. this.overloadedAmbientIntensity > 0 ||
  53924. this.overloadedReflectionIntensity > 0) {
  53925. this._defines.OVERLOADEDVALUES = true;
  53926. }
  53927. // Point size
  53928. if (this.pointsCloud || scene.forcePointsCloud) {
  53929. this._defines.POINTSIZE = true;
  53930. }
  53931. // Fog
  53932. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53933. this._defines.FOG = true;
  53934. }
  53935. if (BABYLON.StandardMaterial.FresnelEnabled) {
  53936. // Fresnel
  53937. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  53938. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53939. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  53940. this._defines.OPACITYFRESNEL = true;
  53941. }
  53942. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53943. this._defines.EMISSIVEFRESNEL = true;
  53944. }
  53945. needNormals = true;
  53946. this._defines.FRESNEL = true;
  53947. }
  53948. }
  53949. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  53950. this._defines.SPECULAROVERALPHA = true;
  53951. }
  53952. if (this.usePhysicalLightFalloff) {
  53953. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  53954. }
  53955. if (this.useRadianceOverAlpha) {
  53956. this._defines.RADIANCEOVERALPHA = true;
  53957. }
  53958. if (this.metallic !== undefined || this.roughness !== undefined) {
  53959. this._defines.METALLICWORKFLOW = true;
  53960. }
  53961. // Attribs
  53962. if (mesh) {
  53963. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53964. this._defines.NORMAL = true;
  53965. }
  53966. if (needUVs) {
  53967. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53968. this._defines.UV1 = true;
  53969. }
  53970. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53971. this._defines.UV2 = true;
  53972. }
  53973. }
  53974. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53975. this._defines.VERTEXCOLOR = true;
  53976. if (mesh.hasVertexAlpha) {
  53977. this._defines.VERTEXALPHA = true;
  53978. }
  53979. }
  53980. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53981. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  53982. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  53983. }
  53984. // Instances
  53985. if (useInstances) {
  53986. this._defines.INSTANCES = true;
  53987. }
  53988. }
  53989. // Get correct effect
  53990. if (!this._defines.isEqual(this._cachedDefines)) {
  53991. this._defines.cloneTo(this._cachedDefines);
  53992. scene.resetCachedMaterial();
  53993. // Fallbacks
  53994. var fallbacks = new BABYLON.EffectFallbacks();
  53995. if (this._defines.REFLECTION) {
  53996. fallbacks.addFallback(0, "REFLECTION");
  53997. }
  53998. if (this._defines.REFRACTION) {
  53999. fallbacks.addFallback(0, "REFRACTION");
  54000. }
  54001. if (this._defines.REFLECTIVITY) {
  54002. fallbacks.addFallback(0, "REFLECTIVITY");
  54003. }
  54004. if (this._defines.BUMP) {
  54005. fallbacks.addFallback(0, "BUMP");
  54006. }
  54007. if (this._defines.PARALLAX) {
  54008. fallbacks.addFallback(1, "PARALLAX");
  54009. }
  54010. if (this._defines.PARALLAXOCCLUSION) {
  54011. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  54012. }
  54013. if (this._defines.SPECULAROVERALPHA) {
  54014. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  54015. }
  54016. if (this._defines.FOG) {
  54017. fallbacks.addFallback(1, "FOG");
  54018. }
  54019. if (this._defines.POINTSIZE) {
  54020. fallbacks.addFallback(0, "POINTSIZE");
  54021. }
  54022. if (this._defines.LOGARITHMICDEPTH) {
  54023. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  54024. }
  54025. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  54026. if (this._defines.SPECULARTERM) {
  54027. fallbacks.addFallback(0, "SPECULARTERM");
  54028. }
  54029. if (this._defines.OPACITYFRESNEL) {
  54030. fallbacks.addFallback(1, "OPACITYFRESNEL");
  54031. }
  54032. if (this._defines.EMISSIVEFRESNEL) {
  54033. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  54034. }
  54035. if (this._defines.FRESNEL) {
  54036. fallbacks.addFallback(3, "FRESNEL");
  54037. }
  54038. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  54039. fallbacks.addCPUSkinningFallback(0, mesh);
  54040. }
  54041. //Attributes
  54042. var attribs = [BABYLON.VertexBuffer.PositionKind];
  54043. if (this._defines.NORMAL) {
  54044. attribs.push(BABYLON.VertexBuffer.NormalKind);
  54045. }
  54046. if (this._defines.UV1) {
  54047. attribs.push(BABYLON.VertexBuffer.UVKind);
  54048. }
  54049. if (this._defines.UV2) {
  54050. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  54051. }
  54052. if (this._defines.VERTEXCOLOR) {
  54053. attribs.push(BABYLON.VertexBuffer.ColorKind);
  54054. }
  54055. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  54056. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  54057. // Legacy browser patch
  54058. var join = this._defines.toString();
  54059. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  54060. "vFogInfos", "vFogColor", "pointSize",
  54061. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  54062. "mBones",
  54063. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  54064. "depthValues",
  54065. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  54066. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  54067. "logarithmicDepthConstant",
  54068. "vSphericalX", "vSphericalY", "vSphericalZ",
  54069. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  54070. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  54071. "vMicrosurfaceTextureLods",
  54072. "vCameraInfos"
  54073. ];
  54074. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  54075. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  54076. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  54077. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  54078. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  54079. }
  54080. if (!this._effect.isReady()) {
  54081. return false;
  54082. }
  54083. this._renderId = scene.getRenderId();
  54084. this._wasPreviouslyReady = true;
  54085. if (mesh) {
  54086. if (!mesh._materialDefines) {
  54087. mesh._materialDefines = new PBRMaterialDefines();
  54088. }
  54089. this._defines.cloneTo(mesh._materialDefines);
  54090. }
  54091. return true;
  54092. };
  54093. PBRMaterial.prototype.unbind = function () {
  54094. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  54095. this._effect.setTexture("reflection2DSampler", null);
  54096. }
  54097. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  54098. this._effect.setTexture("refraction2DSampler", null);
  54099. }
  54100. _super.prototype.unbind.call(this);
  54101. };
  54102. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  54103. this._effect.setMatrix("world", world);
  54104. };
  54105. PBRMaterial.prototype.bind = function (world, mesh) {
  54106. this._myScene = this.getScene();
  54107. // Matrices
  54108. this.bindOnlyWorldMatrix(world);
  54109. // Bones
  54110. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  54111. if (this._myScene.getCachedMaterial() !== this) {
  54112. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  54113. if (BABYLON.StandardMaterial.FresnelEnabled) {
  54114. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  54115. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  54116. }
  54117. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  54118. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  54119. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  54120. }
  54121. }
  54122. // Textures
  54123. if (this._myScene.texturesEnabled) {
  54124. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  54125. this._effect.setTexture("albedoSampler", this.albedoTexture);
  54126. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  54127. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  54128. }
  54129. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  54130. this._effect.setTexture("ambientSampler", this.ambientTexture);
  54131. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  54132. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  54133. }
  54134. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  54135. this._effect.setTexture("opacitySampler", this.opacityTexture);
  54136. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  54137. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  54138. }
  54139. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  54140. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  54141. if (this.reflectionTexture.isCube) {
  54142. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  54143. }
  54144. else {
  54145. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  54146. }
  54147. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  54148. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  54149. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  54150. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  54151. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  54152. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  54153. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  54154. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  54155. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  54156. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  54157. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  54158. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  54159. }
  54160. }
  54161. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  54162. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  54163. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  54164. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  54165. }
  54166. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  54167. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  54168. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  54169. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  54170. }
  54171. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  54172. if (this.metallicTexture) {
  54173. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  54174. this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
  54175. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  54176. }
  54177. else if (this.reflectivityTexture) {
  54178. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  54179. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  54180. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  54181. }
  54182. }
  54183. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  54184. this._effect.setTexture("bumpSampler", this.bumpTexture);
  54185. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  54186. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  54187. }
  54188. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  54189. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  54190. var depth = 1.0;
  54191. if (this.refractionTexture.isCube) {
  54192. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  54193. }
  54194. else {
  54195. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  54196. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  54197. if (this.refractionTexture.depth) {
  54198. depth = this.refractionTexture.depth;
  54199. }
  54200. }
  54201. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  54202. }
  54203. if ((this.reflectionTexture || this.refractionTexture)) {
  54204. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  54205. }
  54206. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  54207. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  54208. }
  54209. }
  54210. // Clip plane
  54211. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  54212. // Point size
  54213. if (this.pointsCloud) {
  54214. this._effect.setFloat("pointSize", this.pointSize);
  54215. }
  54216. // Colors
  54217. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  54218. if (this._defines.METALLICWORKFLOW) {
  54219. PBRMaterial._scaledReflectivity.r = this.metallic === undefined ? 1 : this.metallic;
  54220. PBRMaterial._scaledReflectivity.g = this.roughness === undefined ? 1 : this.roughness;
  54221. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  54222. }
  54223. else {
  54224. // GAMMA CORRECTION.
  54225. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  54226. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  54227. }
  54228. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  54229. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  54230. // GAMMA CORRECTION.
  54231. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  54232. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  54233. // GAMMA CORRECTION.
  54234. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  54235. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  54236. }
  54237. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  54238. // GAMMA CORRECTION.
  54239. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  54240. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  54241. // Lights
  54242. if (this._myScene.lightsEnabled && !this.disableLighting) {
  54243. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  54244. }
  54245. // View
  54246. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  54247. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  54248. }
  54249. // Fog
  54250. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  54251. this._lightingInfos.x = this.directIntensity;
  54252. this._lightingInfos.y = this.emissiveIntensity;
  54253. this._lightingInfos.z = this.environmentIntensity;
  54254. this._lightingInfos.w = this.specularIntensity;
  54255. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  54256. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  54257. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  54258. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  54259. this._cameraInfos.x = this.cameraExposure;
  54260. this._cameraInfos.y = this.cameraContrast;
  54261. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  54262. if (this.cameraColorCurves) {
  54263. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  54264. }
  54265. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  54266. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  54267. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  54268. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  54269. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  54270. this._effect.setColor3("vOverloadedAmbient", this.overloadedAmbient);
  54271. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  54272. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  54273. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  54274. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  54275. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  54276. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  54277. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  54278. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  54279. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  54280. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  54281. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  54282. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  54283. // Log. depth
  54284. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  54285. }
  54286. _super.prototype.bind.call(this, world, mesh);
  54287. this._myScene = null;
  54288. };
  54289. PBRMaterial.prototype.getAnimatables = function () {
  54290. var results = [];
  54291. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  54292. results.push(this.albedoTexture);
  54293. }
  54294. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  54295. results.push(this.ambientTexture);
  54296. }
  54297. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  54298. results.push(this.opacityTexture);
  54299. }
  54300. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  54301. results.push(this.reflectionTexture);
  54302. }
  54303. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  54304. results.push(this.emissiveTexture);
  54305. }
  54306. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  54307. results.push(this.metallicTexture);
  54308. }
  54309. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  54310. results.push(this.reflectivityTexture);
  54311. }
  54312. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  54313. results.push(this.bumpTexture);
  54314. }
  54315. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  54316. results.push(this.lightmapTexture);
  54317. }
  54318. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  54319. results.push(this.refractionTexture);
  54320. }
  54321. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  54322. results.push(this.cameraColorGradingTexture);
  54323. }
  54324. return results;
  54325. };
  54326. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54327. if (forceDisposeTextures) {
  54328. if (this.albedoTexture) {
  54329. this.albedoTexture.dispose();
  54330. }
  54331. if (this.ambientTexture) {
  54332. this.ambientTexture.dispose();
  54333. }
  54334. if (this.opacityTexture) {
  54335. this.opacityTexture.dispose();
  54336. }
  54337. if (this.reflectionTexture) {
  54338. this.reflectionTexture.dispose();
  54339. }
  54340. if (this.emissiveTexture) {
  54341. this.emissiveTexture.dispose();
  54342. }
  54343. if (this.metallicTexture) {
  54344. this.metallicTexture.dispose();
  54345. }
  54346. if (this.reflectivityTexture) {
  54347. this.reflectivityTexture.dispose();
  54348. }
  54349. if (this.bumpTexture) {
  54350. this.bumpTexture.dispose();
  54351. }
  54352. if (this.lightmapTexture) {
  54353. this.lightmapTexture.dispose();
  54354. }
  54355. if (this.refractionTexture) {
  54356. this.refractionTexture.dispose();
  54357. }
  54358. if (this.cameraColorGradingTexture) {
  54359. this.cameraColorGradingTexture.dispose();
  54360. }
  54361. }
  54362. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54363. };
  54364. PBRMaterial.prototype.clone = function (name) {
  54365. var _this = this;
  54366. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  54367. };
  54368. PBRMaterial.prototype.serialize = function () {
  54369. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54370. serializationObject.customType = "BABYLON.PBRMaterial";
  54371. return serializationObject;
  54372. };
  54373. // Statics
  54374. PBRMaterial.Parse = function (source, scene, rootUrl) {
  54375. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  54376. };
  54377. return PBRMaterial;
  54378. }(BABYLON.Material));
  54379. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  54380. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  54381. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  54382. PBRMaterial._scaledReflection = new BABYLON.Color3();
  54383. __decorate([
  54384. BABYLON.serialize()
  54385. ], PBRMaterial.prototype, "directIntensity", void 0);
  54386. __decorate([
  54387. BABYLON.serialize()
  54388. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  54389. __decorate([
  54390. BABYLON.serialize()
  54391. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  54392. __decorate([
  54393. BABYLON.serialize()
  54394. ], PBRMaterial.prototype, "specularIntensity", void 0);
  54395. __decorate([
  54396. BABYLON.serialize()
  54397. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  54398. __decorate([
  54399. BABYLON.serialize()
  54400. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  54401. __decorate([
  54402. BABYLON.serialize()
  54403. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  54404. __decorate([
  54405. BABYLON.serialize()
  54406. ], PBRMaterial.prototype, "cameraExposure", void 0);
  54407. __decorate([
  54408. BABYLON.serialize()
  54409. ], PBRMaterial.prototype, "cameraContrast", void 0);
  54410. __decorate([
  54411. BABYLON.serializeAsTexture()
  54412. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  54413. __decorate([
  54414. BABYLON.serializeAsColorCurves()
  54415. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  54416. __decorate([
  54417. BABYLON.serializeAsColor3()
  54418. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  54419. __decorate([
  54420. BABYLON.serialize()
  54421. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  54422. __decorate([
  54423. BABYLON.serializeAsColor3()
  54424. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  54425. __decorate([
  54426. BABYLON.serialize()
  54427. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  54428. __decorate([
  54429. BABYLON.serializeAsColor3()
  54430. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  54431. __decorate([
  54432. BABYLON.serialize()
  54433. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  54434. __decorate([
  54435. BABYLON.serializeAsColor3()
  54436. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  54437. __decorate([
  54438. BABYLON.serialize()
  54439. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  54440. __decorate([
  54441. BABYLON.serializeAsColor3()
  54442. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  54443. __decorate([
  54444. BABYLON.serialize()
  54445. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  54446. __decorate([
  54447. BABYLON.serialize()
  54448. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  54449. __decorate([
  54450. BABYLON.serialize()
  54451. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  54452. __decorate([
  54453. BABYLON.serializeAsTexture()
  54454. ], PBRMaterial.prototype, "albedoTexture", void 0);
  54455. __decorate([
  54456. BABYLON.serializeAsTexture()
  54457. ], PBRMaterial.prototype, "ambientTexture", void 0);
  54458. __decorate([
  54459. BABYLON.serialize()
  54460. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  54461. __decorate([
  54462. BABYLON.serializeAsTexture()
  54463. ], PBRMaterial.prototype, "opacityTexture", void 0);
  54464. __decorate([
  54465. BABYLON.serializeAsTexture()
  54466. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  54467. __decorate([
  54468. BABYLON.serializeAsTexture()
  54469. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  54470. __decorate([
  54471. BABYLON.serializeAsTexture()
  54472. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  54473. __decorate([
  54474. BABYLON.serializeAsTexture()
  54475. ], PBRMaterial.prototype, "metallicTexture", void 0);
  54476. __decorate([
  54477. BABYLON.serialize()
  54478. ], PBRMaterial.prototype, "metallic", void 0);
  54479. __decorate([
  54480. BABYLON.serialize()
  54481. ], PBRMaterial.prototype, "roughness", void 0);
  54482. __decorate([
  54483. BABYLON.serializeAsTexture()
  54484. ], PBRMaterial.prototype, "bumpTexture", void 0);
  54485. __decorate([
  54486. BABYLON.serializeAsTexture()
  54487. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  54488. __decorate([
  54489. BABYLON.serializeAsTexture()
  54490. ], PBRMaterial.prototype, "refractionTexture", void 0);
  54491. __decorate([
  54492. BABYLON.serializeAsColor3("ambient")
  54493. ], PBRMaterial.prototype, "ambientColor", void 0);
  54494. __decorate([
  54495. BABYLON.serializeAsColor3("albedo")
  54496. ], PBRMaterial.prototype, "albedoColor", void 0);
  54497. __decorate([
  54498. BABYLON.serializeAsColor3("reflectivity")
  54499. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  54500. __decorate([
  54501. BABYLON.serializeAsColor3("reflection")
  54502. ], PBRMaterial.prototype, "reflectionColor", void 0);
  54503. __decorate([
  54504. BABYLON.serializeAsColor3("emissive")
  54505. ], PBRMaterial.prototype, "emissiveColor", void 0);
  54506. __decorate([
  54507. BABYLON.serialize()
  54508. ], PBRMaterial.prototype, "microSurface", void 0);
  54509. __decorate([
  54510. BABYLON.serialize()
  54511. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  54512. __decorate([
  54513. BABYLON.serialize()
  54514. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  54515. __decorate([
  54516. BABYLON.serializeAsFresnelParameters()
  54517. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  54518. __decorate([
  54519. BABYLON.serializeAsFresnelParameters()
  54520. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  54521. __decorate([
  54522. BABYLON.serialize()
  54523. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  54524. __decorate([
  54525. BABYLON.serialize()
  54526. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  54527. __decorate([
  54528. BABYLON.serialize()
  54529. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  54530. __decorate([
  54531. BABYLON.serialize()
  54532. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  54533. __decorate([
  54534. BABYLON.serialize()
  54535. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  54536. __decorate([
  54537. BABYLON.serialize()
  54538. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  54539. __decorate([
  54540. BABYLON.serialize()
  54541. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  54542. __decorate([
  54543. BABYLON.serialize()
  54544. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  54545. __decorate([
  54546. BABYLON.serialize()
  54547. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  54548. __decorate([
  54549. BABYLON.serialize()
  54550. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  54551. __decorate([
  54552. BABYLON.serialize()
  54553. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  54554. __decorate([
  54555. BABYLON.serialize()
  54556. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  54557. __decorate([
  54558. BABYLON.serialize()
  54559. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  54560. __decorate([
  54561. BABYLON.serialize()
  54562. ], PBRMaterial.prototype, "useParallax", void 0);
  54563. __decorate([
  54564. BABYLON.serialize()
  54565. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  54566. __decorate([
  54567. BABYLON.serialize()
  54568. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  54569. __decorate([
  54570. BABYLON.serialize()
  54571. ], PBRMaterial.prototype, "disableLighting", void 0);
  54572. __decorate([
  54573. BABYLON.serialize()
  54574. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  54575. __decorate([
  54576. BABYLON.serialize()
  54577. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  54578. __decorate([
  54579. BABYLON.serialize()
  54580. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  54581. __decorate([
  54582. BABYLON.serialize()
  54583. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  54584. BABYLON.PBRMaterial = PBRMaterial;
  54585. })(BABYLON || (BABYLON = {}));
  54586. //# sourceMappingURL=babylon.pbrMaterial.js.map
  54587. var BABYLON;
  54588. (function (BABYLON) {
  54589. var DebugLayer = (function () {
  54590. function DebugLayer(scene) {
  54591. this._scene = scene;
  54592. }
  54593. /** Creates the inspector window. */
  54594. DebugLayer.prototype._createInspector = function (popup) {
  54595. if (!this._inspector) {
  54596. this._inspector = new INSPECTOR.Inspector(this._scene, popup);
  54597. } // else nothing to do,; instance is already existing
  54598. };
  54599. DebugLayer.prototype.isVisible = function () {
  54600. return false;
  54601. };
  54602. DebugLayer.prototype.hide = function () {
  54603. if (this._inspector) {
  54604. this._inspector.dispose();
  54605. this._inspector = null;
  54606. }
  54607. };
  54608. DebugLayer.prototype.show = function (popup) {
  54609. if (typeof INSPECTOR == 'undefined') {
  54610. // Load inspector and add it to the DOM
  54611. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, popup));
  54612. }
  54613. else {
  54614. // Otherwise creates the inspector
  54615. this._createInspector(popup);
  54616. }
  54617. };
  54618. return DebugLayer;
  54619. }());
  54620. DebugLayer.InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js';
  54621. BABYLON.DebugLayer = DebugLayer;
  54622. })(BABYLON || (BABYLON = {}));
  54623. //# sourceMappingURL=babylon.debugLayer.js.map
  54624. var BABYLON;
  54625. (function (BABYLON) {
  54626. var StandardRenderingPipeline = (function (_super) {
  54627. __extends(StandardRenderingPipeline, _super);
  54628. /**
  54629. * @constructor
  54630. * @param {string} name - The rendering pipeline name
  54631. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54632. * @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)
  54633. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  54634. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54635. */
  54636. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  54637. if (originalPostProcess === void 0) { originalPostProcess = null; }
  54638. var _this = _super.call(this, scene.getEngine(), name) || this;
  54639. _this.downSampleX4PostProcess = null;
  54640. _this.brightPassPostProcess = null;
  54641. _this.gaussianBlurHPostProcesses = [];
  54642. _this.gaussianBlurVPostProcesses = [];
  54643. _this.textureAdderPostProcess = null;
  54644. _this.textureAdderFinalPostProcess = null;
  54645. _this.lensFlarePostProcess = null;
  54646. _this.lensFlareComposePostProcess = null;
  54647. _this.depthOfFieldPostProcess = null;
  54648. // Values
  54649. _this.brightThreshold = 1.0;
  54650. _this.blurWidth = 2.0;
  54651. _this.gaussianCoefficient = 0.25;
  54652. _this.gaussianMean = 1.0;
  54653. _this.gaussianStandardDeviation = 1.0;
  54654. _this.exposure = 1.0;
  54655. _this.lensTexture = null;
  54656. _this.lensColorTexture = null;
  54657. _this.lensFlareStrength = 20.0;
  54658. _this.lensFlareGhostDispersal = 1.4;
  54659. _this.lensFlareHaloWidth = 0.7;
  54660. _this.lensFlareDistortionStrength = 16.0;
  54661. _this.lensStarTexture = null;
  54662. _this.lensFlareDirtTexture = null;
  54663. _this.depthOfFieldDistance = 10.0;
  54664. // IAnimatable
  54665. _this.animations = [];
  54666. _this._depthRenderer = null;
  54667. // Getters and setters
  54668. _this._depthOfFieldEnabled = true;
  54669. _this._lensFlareEnabled = true;
  54670. // Initialize
  54671. _this._scene = scene;
  54672. // Create pass post-processe
  54673. if (!originalPostProcess) {
  54674. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  54675. }
  54676. else {
  54677. _this.originalPostProcess = originalPostProcess;
  54678. }
  54679. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  54680. // Create down sample X4 post-process
  54681. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  54682. // Create bright pass post-process
  54683. _this._createBrightPassPostProcess(scene, ratio / 2);
  54684. // Create gaussian blur post-processes (down sampling blurs)
  54685. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  54686. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  54687. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  54688. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  54689. // Create texture adder post-process
  54690. _this._createTextureAdderPostProcess(scene, ratio);
  54691. // Create depth-of-field source post-process
  54692. _this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54693. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  54694. // Create lens flare post-process
  54695. _this._createLensFlarePostProcess(scene, ratio);
  54696. // Create gaussian blur used by depth-of-field
  54697. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5);
  54698. // Create depth-of-field post-process
  54699. _this._createDepthOfFieldPostProcess(scene, ratio);
  54700. // Finish
  54701. scene.postProcessRenderPipelineManager.addPipeline(_this);
  54702. if (cameras !== null) {
  54703. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54704. }
  54705. // Deactivate
  54706. _this.LensFlareEnabled = false;
  54707. _this.DepthOfFieldEnabled = false;
  54708. return _this;
  54709. }
  54710. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  54711. get: function () {
  54712. return this._depthOfFieldEnabled;
  54713. },
  54714. set: function (enabled) {
  54715. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  54716. if (enabled && !this._depthOfFieldEnabled) {
  54717. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54718. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54719. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  54720. this._depthRenderer = this._scene.enableDepthRenderer();
  54721. }
  54722. else if (!enabled && this._depthOfFieldEnabled) {
  54723. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54724. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54725. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  54726. }
  54727. this._depthOfFieldEnabled = enabled;
  54728. },
  54729. enumerable: true,
  54730. configurable: true
  54731. });
  54732. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  54733. get: function () {
  54734. return this._lensFlareEnabled;
  54735. },
  54736. set: function (enabled) {
  54737. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  54738. if (enabled && !this._lensFlareEnabled) {
  54739. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  54740. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  54741. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54742. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54743. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  54744. }
  54745. else if (!enabled && this._lensFlareEnabled) {
  54746. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  54747. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  54748. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54749. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54750. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  54751. }
  54752. this._lensFlareEnabled = enabled;
  54753. },
  54754. enumerable: true,
  54755. configurable: true
  54756. });
  54757. // Down Sample X4 Post-Processs
  54758. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  54759. var _this = this;
  54760. var downSampleX4Offsets = new Array(32);
  54761. 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);
  54762. this.downSampleX4PostProcess.onApply = function (effect) {
  54763. var id = 0;
  54764. for (var i = -2; i < 2; i++) {
  54765. for (var j = -2; j < 2; j++) {
  54766. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  54767. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  54768. id += 2;
  54769. }
  54770. }
  54771. effect.setArray2("dsOffsets", downSampleX4Offsets);
  54772. };
  54773. // Add to pipeline
  54774. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  54775. };
  54776. // Brightpass Post-Process
  54777. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  54778. var _this = this;
  54779. var brightOffsets = new Array(8);
  54780. 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);
  54781. this.brightPassPostProcess.onApply = function (effect) {
  54782. var sU = (1.0 / _this.brightPassPostProcess.width);
  54783. var sV = (1.0 / _this.brightPassPostProcess.height);
  54784. brightOffsets[0] = -0.5 * sU;
  54785. brightOffsets[1] = 0.5 * sV;
  54786. brightOffsets[2] = 0.5 * sU;
  54787. brightOffsets[3] = 0.5 * sV;
  54788. brightOffsets[4] = -0.5 * sU;
  54789. brightOffsets[5] = -0.5 * sV;
  54790. brightOffsets[6] = 0.5 * sU;
  54791. brightOffsets[7] = -0.5 * sV;
  54792. effect.setArray2("dsOffsets", brightOffsets);
  54793. effect.setFloat("brightThreshold", _this.brightThreshold);
  54794. };
  54795. // Add to pipeline
  54796. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  54797. };
  54798. // Create gaussian blur H&V post-processes
  54799. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  54800. var _this = this;
  54801. var blurOffsets = new Array(9);
  54802. var blurWeights = new Array(9);
  54803. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  54804. var callback = function (height) {
  54805. return function (effect) {
  54806. // Weights
  54807. var x = 0.0;
  54808. for (var i = 0; i < 9; i++) {
  54809. x = (i - 4.0) / 4.0;
  54810. blurWeights[i] =
  54811. _this.gaussianCoefficient
  54812. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  54813. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  54814. }
  54815. var lastOutputDimensions = {
  54816. width: scene.getEngine().getRenderWidth(),
  54817. height: scene.getEngine().getRenderHeight()
  54818. };
  54819. for (var i = 0; i < 9; i++) {
  54820. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  54821. blurOffsets[i] = value;
  54822. }
  54823. effect.setArray("blurOffsets", blurOffsets);
  54824. effect.setArray("blurWeights", blurWeights);
  54825. effect.setFloat("blurWidth", _this.blurWidth);
  54826. };
  54827. };
  54828. // Create horizontal gaussian blur post-processes
  54829. var gaussianBlurHPostProcess = new BABYLON.PostProcess("HDRGaussianBlurH" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54830. gaussianBlurHPostProcess.onApply = callback(false);
  54831. // Create vertical gaussian blur post-process
  54832. var gaussianBlurVPostProcess = new BABYLON.PostProcess("HDRGaussianBlurV" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54833. gaussianBlurVPostProcess.onApply = callback(true);
  54834. // Add to pipeline
  54835. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  54836. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  54837. // Finish
  54838. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  54839. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  54840. };
  54841. // Create texture adder post-process
  54842. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  54843. var _this = this;
  54844. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  54845. 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);
  54846. this.textureAdderPostProcess.onApply = function (effect) {
  54847. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  54848. effect.setTexture("lensSampler", _this.lensTexture);
  54849. effect.setFloat("exposure", _this.exposure);
  54850. };
  54851. // Add to pipeline
  54852. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  54853. };
  54854. // Create lens flare post-process
  54855. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  54856. var _this = this;
  54857. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54858. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, false));
  54859. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  54860. 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);
  54861. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, false));
  54862. var resolution = new BABYLON.Vector2(0, 0);
  54863. // Lens flare
  54864. this.lensFlarePostProcess.onApply = function (effect) {
  54865. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  54866. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  54867. effect.setFloat("strength", _this.lensFlareStrength);
  54868. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  54869. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  54870. // Shift
  54871. resolution.x = _this.lensFlarePostProcess.width;
  54872. resolution.y = _this.lensFlarePostProcess.height;
  54873. effect.setVector2("resolution", resolution);
  54874. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  54875. };
  54876. // Compose
  54877. 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);
  54878. 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);
  54879. this.lensFlareComposePostProcess.onApply = function (effect) {
  54880. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  54881. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  54882. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  54883. // Lens start rotation matrix
  54884. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  54885. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  54886. 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));
  54887. camRot *= 4.0;
  54888. 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);
  54889. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  54890. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  54891. };
  54892. };
  54893. // Create depth-of-field post-process
  54894. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  54895. var _this = this;
  54896. 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);
  54897. this.depthOfFieldPostProcess.onApply = function (effect) {
  54898. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  54899. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  54900. effect.setFloat("distance", _this.depthOfFieldDistance);
  54901. };
  54902. // Add to pipeline
  54903. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  54904. };
  54905. // Dispose
  54906. StandardRenderingPipeline.prototype.dispose = function () {
  54907. for (var i = 0; i < this._scene.cameras.length; i++) {
  54908. var camera = this._scene.cameras[i];
  54909. this.originalPostProcess.dispose(camera);
  54910. this.downSampleX4PostProcess.dispose(camera);
  54911. this.brightPassPostProcess.dispose(camera);
  54912. this.textureAdderPostProcess.dispose(camera);
  54913. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  54914. this.gaussianBlurHPostProcesses[j].dispose(camera);
  54915. }
  54916. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  54917. this.gaussianBlurVPostProcesses[j].dispose(camera);
  54918. }
  54919. this.textureAdderFinalPostProcess.dispose(camera);
  54920. this.lensFlarePostProcess.dispose(camera);
  54921. this.lensFlareComposePostProcess.dispose(camera);
  54922. this.depthOfFieldPostProcess.dispose(camera);
  54923. }
  54924. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54925. _super.prototype.dispose.call(this);
  54926. };
  54927. return StandardRenderingPipeline;
  54928. }(BABYLON.PostProcessRenderPipeline));
  54929. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  54930. })(BABYLON || (BABYLON = {}));
  54931. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  54932. BABYLON.Effect.ShadersStore={"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}","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}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","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}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","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}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef 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#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\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}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,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<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\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}","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}","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}","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","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\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":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\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}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","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}","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}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\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}","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}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\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}","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}","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","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}","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}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV+uvOffset);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\nambientColor=vec3(1.,1.,1.)-((vec3(1.,1.,1.)-ambientColor)*vAmbientInfos.z);\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef METALLICROUGHNESSMAP\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#ifdef METALLICROUGHNESSGSTOREINALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef METALLICROUGHNESSGSTOREINGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n\nvec3 baseColor=surfaceAlbedo.rgb;\n\nsurfaceAlbedo.rgb*=(1.0-metallicRoughness.r);\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\nmicroSurface=1.0-metallicRoughness.g;\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,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 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<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}","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}","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}","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}","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\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\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\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\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n#endif\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}","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}","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\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float blurWidth;\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n","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}","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}","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 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\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","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}"};
  54933. 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","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","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,vBumpUV);\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(viewDirectionW,TBN,vBumpUV+uvOffset);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,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","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","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}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","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}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\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 float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\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","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","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}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","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-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\nlightDiffuseContribution+=lightmapColor*notShadowLevel;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nlightSpecularContribution+=info.specular*notShadowLevel*lightmapColor;\n#endif\n#endif\n#else\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif\n#endif","pbrShadowFunctions":"\n#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,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,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\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\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))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,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\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,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 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_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;\nreturn vec3(s,t,0);\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}","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,float bias)\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))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,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\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\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))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,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\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,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 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n"};
  54934. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return!(t.x>o.x+i)&&(!(o.x-i>e.x)&&(!(t.y>o.y+i)&&(!(o.y-i>e.y)&&(!(t.z>o.z+i)&&!(o.z-i>e.z)))))},o=function(){var t={root:0,found:!1};return function(e,o,i,s){t.root=0,t.found=!1;var r=o*o-4*e*i;if(r<0)return t;var n=Math.sqrt(r),c=(-o-n)/(2*e),h=(-o+n)/(2*e);if(c>h){var a=h;h=c,c=a}return c>0&&c<s?(t.root=c,t.found=!0,t):h>0&&h<s?(t.root=h,t.found=!0,t):t}}(),i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return!(n<0)&&(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),!(n<0)&&(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return!(n>this.velocityWorldLength+c+i)&&!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||V<0)return;h<0&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var f=this.velocity.lengthSquared(),m=f;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;c<s;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;c<a;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;s<r;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;t<s;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;t<a;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\";var o;!function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(o=e.WorkerTaskType||(e.WorkerTaskType={}));var i;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(i=e.WorkerReplyType||(e.WorkerReplyType={}));var t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t}();t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,r){void 0===r&&(r=1.401298e-45);var n=t-i;return-r<=n&&n<=r},t.ToHex=function(t){var i=t.toString(16);return t<=15?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,r){return void 0===i&&(i=0),void 0===r&&(r=1),Math.min(r,Math.max(i,t))},t}();t.MathTools=i;var r=function(){function r(t,i,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),this.r=t,this.g=i,this.b=r}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.getClassName=function(){return\"Color3\"},r.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,r){return this.r===t&&this.g===i&&this.b===r},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,r){return this.r=t,this.g=i,this.b=r,this},r.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},r.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new r(0,0,0);var i=parseInt(t.substring(1,3),16),n=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return r.FromInts(i,n,o)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,e=t.g+(i.g-t.g)*n,s=t.b+(i.b-t.b)*n;return new r(o,e,s)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r.Random=function(){return new r(Math.random(),Math.random(),Math.random())},r}();t.Color3=r;var n=function(){function t(t,i,r,n){this.r=t,this.g=i,this.b=r,this.a=n}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var r=parseInt(i.substring(1,3),16),n=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(r,n,o,e)},t.Lerp=function(i,r,n){var o=new t(0,0,0,0);return t.LerpToRef(i,r,n,o),o},t.LerpToRef=function(t,i,r,n){n.r=t.r+(i.r-t.r)*r,n.g=t.g+(i.g-t.g)*r,n.b=t.b+(i.b-t.b)*r,n.a=t.a+(i.a-t.a)*r},t.FromArray=function(i,r){return void 0===r&&(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.FromInts=function(i,r,n,o){return new t(i/255,r/255,n/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var r=[],n=0;n<t.length;n+=3){var o=n/3*4;r[o]=t[n],r[o+1]=t[n+1],r[o+2]=t[n+2],r[o+3]=1}return r}return t},t}();t.Color4=n;var o=function(){function r(t,i){this.x=t,this.y=i}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},r.prototype.getClassName=function(){return\"Vector2\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},r.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},r.prototype.addVector3=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},r.prototype.multiplyByFloats=function(t,i){return new r(this.x*t,this.y*i)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},r.prototype.negate=function(){return new r((-this.x),(-this.y))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t)},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},r.prototype.clone=function(){return new r(this.x,this.y)},r.Zero=function(){return new r(0,0)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h);return new r(a,u)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>n.y?n.y:e,e=e<i.y?i.y:e,new r(o,e)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y;return new r(c,p)},r.Lerp=function(t,i,n){var o=t.x+(i.x-t.x)*n,e=t.y+(i.y-t.y)*n;return new r(o,e)},r.Dot=function(t,i){return t.x*i.x+t.y*i.y},r.Normalize=function(t){var i=t.clone();return i.normalize(),i},r.Minimize=function(t,i){var n=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new r(n,o)},r.Maximize=function(t,i){var n=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new r(n,o)},r.Transform=function(t,i){var n=r.Zero();return r.TransformToRef(t,i,n),n},r.TransformToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];r.x=n,r.y=o},r.PointInTriangle=function(t,i,r,n){var o=.5*(-r.y*n.x+i.y*(-r.x+n.x)+i.x*(r.y-n.y)+r.x*n.y),e=o<0?-1:1,s=(i.y*n.x-i.x*n.y+(n.y-i.y)*t.x+(i.x-n.x)*t.y)*e,h=(i.x*r.y-i.y*r.x+(i.y-r.y)*t.x+(r.x-i.x)*t.y)*e;return s>0&&h>0&&s+h<2*o*e},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y;return r*r+n*n},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.DistanceOfPointFromSegment=function(t,i,n){var o=r.DistanceSquared(i,n);if(0===o)return r.Distance(t,i);var e=n.subtract(i),s=Math.max(0,Math.min(1,r.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return r.Distance(t,h)},r}();t.Vector2=o;var e=function(){function r(t,i,r){this.x=t,this.y=i,this.z=r}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},r.prototype.getClassName=function(){return\"Vector3\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},r.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),r=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=n*s,t.y=-o*s,t.z=r*e,t.w=i*e,t},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},r.prototype.subtractFromFloats=function(t,i,n){return new r(this.x-t,this.y-i,this.z-n)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-r,this},r.prototype.negate=function(){return new r((-this.x),(-this.y),(-this.z))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t)},r.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)},r.prototype.equalsToFloats=function(t,i,r){return this.x===t&&this.y===i&&this.z===r},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},r.prototype.multiplyByFloats=function(t,i,n){return new r(this.x*t,this.y*i,this.z*n)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},r.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},r.prototype.clone=function(){return new r(this.x,this.y,this.z)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},r.prototype.copyFromFloats=function(t,i,r){return this.x=t,this.y=i,this.z=r,this},r.GetClipFactor=function(t,i,n,o){var e=r.Dot(t,n)-o,s=r.Dot(i,n)-o,h=e/(e-s);return h},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromFloatArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatsToRef=function(t,i,r,n){n.x=t,n.y=i,n.z=r},r.Zero=function(){return new r(0,0,0)},r.Up=function(){return new r(0,1,0)},r.Forward=function(){return new r(0,0,1)},r.Right=function(){return new r(1,0,0)},r.Left=function(){return new r((-1),0,0)},r.TransformCoordinates=function(t,i){var n=r.Zero();return r.TransformCoordinatesToRef(t,i,n),n},r.TransformCoordinatesToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];r.x=n/s,r.y=o/s,r.z=e/s},r.TransformCoordinatesFromFloatsToRef=function(t,i,r,n,o){var e=t*n.m[0]+i*n.m[4]+r*n.m[8]+n.m[12],s=t*n.m[1]+i*n.m[5]+r*n.m[9]+n.m[13],h=t*n.m[2]+i*n.m[6]+r*n.m[10]+n.m[14],a=t*n.m[3]+i*n.m[7]+r*n.m[11]+n.m[15];o.x=e/a,o.y=s/a,o.z=h/a},r.TransformNormal=function(t,i){var n=r.Zero();return r.TransformNormalToRef(t,i,n),n},r.TransformNormalToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10];r.x=n,r.y=o,r.z=e},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o){o.x=t*n.m[0]+i*n.m[4]+r*n.m[8],o.y=t*n.m[1]+i*n.m[5]+r*n.m[9],o.z=t*n.m[2]+i*n.m[6]+r*n.m[10]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h),m=.5*(2*i.z+(-t.z+n.z)*e+(2*t.z-5*i.z+4*n.z-o.z)*s+(-t.z+3*i.z-3*n.z+o.z)*h);return new r(a,u,m)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>n.y?n.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>n.z?n.z:s,s=s<i.z?i.z:s,new r(o,e,s)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y,f=t.z*a+n.z*u+i.z*m+o.z*y;return new r(c,p,f)},r.Lerp=function(t,i,n){var o=new r(0,0,0);return r.LerpToRef(t,i,n,o),o},r.LerpToRef=function(t,i,r,n){n.x=t.x+(i.x-t.x)*r,n.y=t.y+(i.y-t.y)*r,n.z=t.z+(i.z-t.z)*r},r.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},r.Cross=function(t,i){var n=r.Zero();return r.CrossToRef(t,i,n),n},r.CrossToRef=function(t,i,r){A.Vector3[0].x=t.y*i.z-t.z*i.y,A.Vector3[0].y=t.z*i.x-t.x*i.z,A.Vector3[0].z=t.x*i.y-t.y*i.x,r.copyFrom(A.Vector3[0])},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Project=function(t,i,n,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=r._viewportMatrixCache?r._viewportMatrixCache:r._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,1,0,h+e/2,s/2+a,0,1,m);var y=r._matrixCache?r._matrixCache:r._matrixCache=new u;return i.multiplyToRef(n,y),y.multiplyToRef(m,y),r.TransformCoordinates(t,y)},r.UnprojectFromTransform=function(t,n,o,e,s){var h=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/n*2-1,t.y=-(t.y/o*2-1);var a=r.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},r.Unproject=function(t,n,o,e,s,h){var a=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new r(t.x/n*2-1,(-(t.y/o*2-1)),2*t.z-1),y=r.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z;return r*r+n*n+o*o},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.RotationFromAxis=function(t,i,n){var o=r.Zero();return r.RotationFromAxisToRef(t,i,n,o),o},r.RotationFromAxisToRef=function(n,o,e,s){var h=n.normalize(),a=e.normalize(),u=f.X,m=f.Y,y=0,c=0,p=0,x=0,l=0,z=0,w=0,v=-1,d=0,g=A.Vector3[0],R=0,T=A.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?x=1:(w=a.z/a.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),T.x=x,T.y=l,T.z=z,T.normalize(),r.CrossToRef(h,T,g),g.normalize(),r.Dot(a,g)<0&&(v=1),R=r.Dot(h,T),R=Math.min(1,Math.max(-1,R)),p=Math.acos(R)*v,r.Dot(T,u)<0&&(p=Math.PI+p,T=T.scaleInPlace(-1),d++);var _=A.Vector3[2],M=A.Vector3[3];x=0,l=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?x=1:(w=T.z/T.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=x,_.y=l,_.z=z,_.normalize(),r.CrossToRef(_,T,M),M.normalize(),r.CrossToRef(a,_,g),g.normalize(),r.Dot(T,g)<0&&(v=1),R=r.Dot(a,_),R=Math.min(1,Math.max(-1,R)),c=Math.acos(R)*v,r.Dot(M,m)<0&&(c=Math.PI+c,d++),v=-1,r.CrossToRef(u,T,g),g.normalize(),r.Dot(g,m)<0&&(v=1),R=r.Dot(T,u),R=Math.min(1,Math.max(-1,R)),y=-Math.acos(R)*v,R<0&&d<2&&(y=Math.PI+y),s.x=c,s.y=y,s.z=p},r}();t.Vector3=e;var s=function(){function r(t,i,r,n){this.x=t,this.y=i,this.z=r,this.w=n}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},r.prototype.getClassName=function(){return\"Vector4\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},r.prototype.subtractFromFloats=function(t,i,n,o){return new r(this.x-t,this.y-i,this.z-n,this.w-o)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-r,o.w=this.w-n,this},r.prototype.negate=function(){return new r((-this.x),(-this.y),(-this.z),(-this.w))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t,this.w*t)},r.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)&&i.WithinEpsilon(this.w,r.w,n)},r.prototype.equalsToFloats=function(t,i,r,n){return this.x===t&&this.y===i&&this.z===r&&this.w===n},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},r.prototype.multiplyByFloats=function(t,i,n,o){return new r(this.x*t,this.y*i,this.z*n,this.w*o)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},r.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},r.prototype.clone=function(){return new r(this.x,this.y,this.z,this.w)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},r.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2],t[i+3])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatsToRef=function(t,i,r,n,o){o.x=t,o.y=i,o.z=r,o.w=n},r.Zero=function(){return new r(0,0,0,0)},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return r*r+n*n+o*o+e*e},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r}();t.Vector4=s;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){this.width=t,this.height=i},t.prototype.multiplyByFloats=function(i,r){return new t(this.width*i,this.height*r)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return!!t&&(this.width===t.width&&this.height===t.height)},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){var r=new t(this.width+i.width,this.height+i.height);return r},t.prototype.substract=function(i){var r=new t(this.width-i.width,this.height-i.height);return r},t.Lerp=function(i,r,n){var o=i.width+(r.width-i.width)*n,e=i.height+(r.height-i.height)*n;return new t(o,e)},t}();t.Size=h;var a=function(){function t(t,i,r,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=r,this.w=n}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.getClassName=function(){return\"Quaternion\"},t.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var r=new t(0,0,0,1);return this.multiplyToRef(i,r),r},t.prototype.multiplyToRef=function(t,i){var r=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,e=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(r,n,o,e),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t((-this.x),(-this.y),(-this.z),this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var r=this.z,n=this.x,o=this.y,e=this.w,s=e*e,h=r*r,a=n*n,u=o*o,m=o*r-n*e,y=.4999999;return m<-y?(t.y=2*Math.atan2(o,e),t.x=Math.PI/2,t.z=0):m>y?(t.y=2*Math.atan2(o,e),t.x=-Math.PI/2,t.z=0):(t.z=Math.atan2(2*(n*o+r*e),-h-a+u+s),t.x=Math.asin(-2*(r*o-n*e)),t.y=Math.atan2(2*(r*n+o*e),h-a-u+s)),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,r=this.y*this.y,n=this.z*this.z,o=this.x*this.y,e=this.z*this.w,s=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(r+n),t.m[1]=2*(o+e),t.m[2]=2*(s-h),t.m[3]=0,t.m[4]=2*(o-e),t.m[5]=1-2*(n+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(s+h),t.m[9]=2*(a-u),t.m[10]=1-2*(r+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var r=new t;return t.FromRotationMatrixToRef(i,r),r},t.FromRotationMatrixToRef=function(t,i){var r,n=t.m,o=n[0],e=n[4],s=n[8],h=n[1],a=n[5],u=n[9],m=n[2],y=n[6],c=n[10],p=o+a+c;p>0?(r=.5/Math.sqrt(p+1),i.w=.25/r,i.x=(y-u)*r,i.y=(s-m)*r,i.z=(h-e)*r):o>a&&o>c?(r=2*Math.sqrt(1+o-a-c),i.w=(y-u)/r,i.x=.25*r,i.y=(e+h)/r,i.z=(s+m)/r):a>c?(r=2*Math.sqrt(1+a-o-c),i.w=(s-m)/r,i.x=(e+h)/r,i.y=.25*r,i.z=(u+y)/r):(r=2*Math.sqrt(1+c-o-a),i.w=(h-e)/r,i.x=(s+m)/r,i.y=(u+y)/r,i.z=.25*r)},t.Inverse=function(i){return new t((-i.x),(-i.y),(-i.z),i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,r){return t.RotationAxisToRef(i,r,new t)},t.RotationAxisToRef=function(t,i,r){var n=Math.sin(i/2);return t.normalize(),r.w=Math.cos(i/2),r.x=t.x*n,r.y=t.y*n,r.z=t.z*n,r},t.FromArray=function(i,r){return r||(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.RotationYawPitchRoll=function(i,r,n){var o=new t;return t.RotationYawPitchRollToRef(i,r,n,o),o},t.RotationYawPitchRollToRef=function(t,i,r,n){var o=.5*r,e=.5*i,s=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(e),m=Math.cos(e),y=Math.sin(s),c=Math.cos(s);n.x=c*u*a+y*m*h,n.y=y*m*a-c*u*h,n.z=c*m*h-y*u*a,n.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,r,n){var o=new t;return t.RotationAlphaBetaGammaToRef(i,r,n,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,r,n){var o=.5*(r+t),e=.5*(r-t),s=.5*i;n.x=Math.cos(e)*Math.sin(s),n.y=Math.sin(e)*Math.sin(s),n.z=Math.sin(o)*Math.cos(s),n.w=Math.cos(o)*Math.cos(s)},t.Slerp=function(i,r,n){var o=t.Identity();return t.SlerpToRef(i,r,n,o),o},t.SlerpToRef=function(t,i,r,n){var o,e,s=r,h=t.x*i.x+t.y*i.y+t.z*i.z+t.w*i.w,a=!1;if(h<0&&(a=!0,h=-h),h>.999999)e=1-s,o=a?-s:s;else{var u=Math.acos(h),m=1/Math.sin(u);e=Math.sin((1-s)*u)*m,o=a?-Math.sin(s*u)*m:Math.sin(s*u)*m}n.x=e*t.x+o*i.x,n.y=e*t.y+o*i.y,n.z=e*t.z+o*i.z,n.w=e*t.w+o*i.w},t}();t.Quaternion=a;var u=function(){function r(){this.m=new Float32Array(16)}return r.prototype.isIdentity=function(){return 1===this.m[0]&&1===this.m[5]&&1===this.m[10]&&1===this.m[15]&&(0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14])},r.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],r=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],e=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*r)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*e)-this.m[3]*(this.m[4]*r-this.m[5]*o+this.m[6]*e)},r.prototype.toArray=function(){return this.m},r.prototype.asArray=function(){return this.toArray()},r.prototype.invert=function(){return this.invertToRef(this),this},r.prototype.reset=function(){for(var t=0;t<16;t++)this.m[t]=0;return this},r.prototype.add=function(t){var i=new r;return this.addToRef(t,i),i},r.prototype.addToRef=function(t,i){for(var r=0;r<16;r++)i.m[r]=this.m[r]+t.m[r];return this},r.prototype.addToSelf=function(t){for(var i=0;i<16;i++)this.m[i]+=t.m[i];return this},r.prototype.invertToRef=function(t){var i=this.m[0],r=this.m[1],n=this.m[2],o=this.m[3],e=this.m[4],s=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],x=this.m[14],l=this.m[15],z=y*l-c*x,w=m*l-c*f,v=m*x-y*f,d=u*l-c*p,g=u*x-y*p,R=u*f-m*p,T=s*z-h*w+a*v,_=-(e*z-h*d+a*g),M=e*w-s*d+a*R,A=-(e*v-s*g+h*R),F=1/(i*T+r*_+n*M+o*A),b=h*l-a*x,L=s*l-a*f,C=s*x-h*f,P=e*l-a*p,Z=e*x-h*p,S=e*f-s*p,I=h*c-a*y,H=s*c-a*m,V=s*y-h*m,q=e*c-a*u,D=e*y-h*u,N=e*m-s*u;return t.m[0]=T*F,t.m[4]=_*F,t.m[8]=M*F,t.m[12]=A*F,t.m[1]=-(r*z-n*w+o*v)*F,t.m[5]=(i*z-n*d+o*g)*F,t.m[9]=-(i*w-r*d+o*R)*F,t.m[13]=(i*v-r*g+n*R)*F,t.m[2]=(r*b-n*L+o*C)*F,t.m[6]=-(i*b-n*P+o*Z)*F,t.m[10]=(i*L-r*P+o*S)*F,t.m[14]=-(i*C-r*Z+n*S)*F,t.m[3]=-(r*I-n*H+o*V)*F,t.m[7]=(i*I-n*q+o*D)*F,t.m[11]=-(i*H-r*q+o*N)*F,t.m[15]=(i*V-r*D+n*N)*F,this},r.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},r.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},r.prototype.multiply=function(t){\nvar i=new r;return this.multiplyToRef(t,i),i},r.prototype.copyFrom=function(t){for(var i=0;i<16;i++)this.m[i]=t.m[i];return this},r.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var r=0;r<16;r++)t[i+r]=this.m[r];return this},r.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},r.prototype.multiplyToArray=function(t,i,r){var n=this.m[0],o=this.m[1],e=this.m[2],s=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],x=this.m[12],l=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],R=t.m[3],T=t.m[4],_=t.m[5],M=t.m[6],A=t.m[7],F=t.m[8],b=t.m[9],L=t.m[10],C=t.m[11],P=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[r]=n*v+o*T+e*F+s*P,i[r+1]=n*d+o*_+e*b+s*Z,i[r+2]=n*g+o*M+e*L+s*S,i[r+3]=n*R+o*A+e*C+s*I,i[r+4]=h*v+a*T+u*F+m*P,i[r+5]=h*d+a*_+u*b+m*Z,i[r+6]=h*g+a*M+u*L+m*S,i[r+7]=h*R+a*A+u*C+m*I,i[r+8]=y*v+c*T+p*F+f*P,i[r+9]=y*d+c*_+p*b+f*Z,i[r+10]=y*g+c*M+p*L+f*S,i[r+11]=y*R+c*A+p*C+f*I,i[r+12]=x*v+l*T+z*F+w*P,i[r+13]=x*d+l*_+z*b+w*Z,i[r+14]=x*g+l*M+z*L+w*S,i[r+15]=x*R+l*A+z*C+w*I,this},r.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},r.prototype.clone=function(){return r.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])},r.prototype.getClassName=function(){return\"Matrix\"},r.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;i<16;i++)t=397*t^(this.m[i]||0);return t},r.prototype.decompose=function(t,n,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var e=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;return t.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),t.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),t.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===t.x||0===t.y||0===t.z?(n.x=0,n.y=0,n.z=0,n.w=1,!1):(r.FromValuesToRef(this.m[0]/t.x,this.m[1]/t.x,this.m[2]/t.x,0,this.m[4]/t.y,this.m[5]/t.y,this.m[6]/t.y,0,this.m[8]/t.z,this.m[9]/t.z,this.m[10]/t.z,0,0,0,0,1,A.Matrix[0]),a.FromRotationMatrixToRef(A.Matrix[0],n),!0)},r.prototype.getRotationMatrix=function(){var t=r.Identity();return this.getRotationMatrixToRef(t),t},r.prototype.getRotationMatrixToRef=function(t){var i=this.m,n=i[0]*i[1]*i[2]*i[3]<0?-1:1,o=i[4]*i[5]*i[6]*i[7]<0?-1:1,e=i[8]*i[9]*i[10]*i[11]<0?-1:1,s=n*Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]),h=o*Math.sqrt(i[4]*i[4]+i[5]*i[5]+i[6]*i[6]),a=e*Math.sqrt(i[8]*i[8]+i[9]*i[9]+i[10]*i[10]);r.FromValuesToRef(i[0]/s,i[1]/s,i[2]/s,0,i[4]/h,i[5]/h,i[6]/h,0,i[8]/a,i[9]/a,i[10]/a,0,0,0,0,1,t)},r.FromArray=function(t,i){var n=new r;return i||(i=0),r.FromArrayToRef(t,i,n),n},r.FromArrayToRef=function(t,i,r){for(var n=0;n<16;n++)r.m[n]=t[n+i]},r.FromFloat32ArrayToRefScaled=function(t,i,r,n){for(var o=0;o<16;o++)n.m[o]=t[o+i]*r},r.FromValuesToRef=function(t,i,r,n,o,e,s,h,a,u,m,y,c,p,f,x,l){l.m[0]=t,l.m[1]=i,l.m[2]=r,l.m[3]=n,l.m[4]=o,l.m[5]=e,l.m[6]=s,l.m[7]=h,l.m[8]=a,l.m[9]=u,l.m[10]=m,l.m[11]=y,l.m[12]=c,l.m[13]=p,l.m[14]=f,l.m[15]=x},r.prototype.getRow=function(t){if(t<0||t>3)return null;var i=4*t;return new s(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},r.prototype.setRow=function(t,i){if(t<0||t>3)return this;var r=4*t;return this.m[r+0]=i.x,this.m[r+1]=i.y,this.m[r+2]=i.z,this.m[r+3]=i.w,this},r.FromValues=function(t,i,n,o,e,s,h,a,u,m,y,c,p,f,x,l){var z=new r;return z.m[0]=t,z.m[1]=i,z.m[2]=n,z.m[3]=o,z.m[4]=e,z.m[5]=s,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=x,z.m[15]=l,z},r.Compose=function(t,i,n){var o=r.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),e=r.Identity();return i.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(n),o},r.Identity=function(){return r.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},r.IdentityToRef=function(t){r.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},r.Zero=function(){return r.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},r.RotationX=function(t){var i=new r;return r.RotationXToRef(t,i),i},r.Invert=function(t){var i=new r;return t.invertToRef(i),i},r.RotationXToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-r,i.m[6]=r,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},r.RotationY=function(t){var i=new r;return r.RotationYToRef(t,i),i},r.RotationYToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-r,i.m[8]=r,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},r.RotationZ=function(t){var i=new r;return r.RotationZToRef(t,i),i},r.RotationZToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=r,i.m[4]=-r,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},r.RotationAxis=function(t,i){var n=r.Zero();return r.RotationAxisToRef(t,i,n),n},r.RotationAxisToRef=function(t,i,r){var n=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),r.m[0]=t.x*t.x*e+o,r.m[1]=t.x*t.y*e-t.z*n,r.m[2]=t.x*t.z*e+t.y*n,r.m[3]=0,r.m[4]=t.y*t.x*e+t.z*n,r.m[5]=t.y*t.y*e+o,r.m[6]=t.y*t.z*e-t.x*n,r.m[7]=0,r.m[8]=t.z*t.x*e-t.y*n,r.m[9]=t.z*t.y*e+t.x*n,r.m[10]=t.z*t.z*e+o,r.m[11]=0,r.m[15]=1},r.RotationYawPitchRoll=function(t,i,n){var o=new r;return r.RotationYawPitchRollToRef(t,i,n,o),o},r.RotationYawPitchRollToRef=function(t,i,r,n){a.RotationYawPitchRollToRef(t,i,r,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},r.Scaling=function(t,i,n){var o=r.Zero();return r.ScalingToRef(t,i,n,o),o},r.ScalingToRef=function(t,i,r,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=r,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},r.Translation=function(t,i,n){var o=r.Identity();return r.TranslationToRef(t,i,n,o),o},r.TranslationToRef=function(t,i,n,o){r.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,i,n,1,o)},r.Lerp=function(t,i,n){for(var o=r.Zero(),e=0;e<16;e++)o.m[e]=t.m[e]*(1-n)+i.m[e]*n;return o},r.DecomposeLerp=function(t,i,n){var o=new e(0,0,0),s=new a,h=new e(0,0,0);t.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);i.decompose(u,m,y);var c=e.Lerp(o,u,n),p=a.Slerp(s,m,n),f=e.Lerp(h,y,n);return r.Compose(c,p,f)},r.LookAtLH=function(t,i,n){var o=r.Zero();return r.LookAtLHToRef(t,i,n,o),o},r.LookAtLHToRef=function(t,i,n,o){i.subtractToRef(t,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return r.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,s,h,a,1,o)},r.LookAtRH=function(t,i,n){var o=r.Zero();return r.LookAtRHToRef(t,i,n,o),o},r.LookAtRHToRef=function(t,i,n,o){t.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return r.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,s,h,a,1,o)},r.OrthoLH=function(t,i,n,o){var e=r.Zero();return r.OrthoLHToRef(t,i,n,o,e),e},r.OrthoLHToRef=function(i,r,n,o,e){var s=n,h=o,a=2/i,u=2/r,m=2/(h-s),y=-(h+s)/(h-s);t.Matrix.FromValuesToRef(a,0,0,0,0,u,0,0,0,0,m,0,0,0,y,1,e)},r.OrthoOffCenterLH=function(t,i,n,o,e,s){var h=r.Zero();return r.OrthoOffCenterLHToRef(t,i,n,o,e,s,h),h},r.OrthoOffCenterLHToRef=function(i,r,n,o,e,s,h){var a=e,u=s,m=2/(r-i),y=2/(o-n),c=2/(u-a),p=-(u+a)/(u-a),f=(i+r)/(i-r),x=(o+n)/(n-o);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,0,f,x,p,1,h)},r.OrthoOffCenterRH=function(t,i,n,o,e,s){var h=r.Zero();return r.OrthoOffCenterRHToRef(t,i,n,o,e,s,h),h},r.OrthoOffCenterRHToRef=function(t,i,n,o,e,s,h){r.OrthoOffCenterLHToRef(t,i,n,o,e,s,h),h.m[10]*=-1},r.PerspectiveLH=function(i,n,o,e){var s=r.Zero(),h=o,a=e,u=2*h/i,m=2*h/n,y=(a+h)/(a-h),c=-2*a*h/(a-h);return t.Matrix.FromValuesToRef(u,0,0,0,0,m,0,0,0,0,y,1,0,0,c,0,s),s},r.PerspectiveFovLH=function(t,i,n,o){var e=r.Zero();return r.PerspectiveFovLHToRef(t,i,n,o,e),e},r.PerspectiveFovLHToRef=function(i,r,n,o,e,s){void 0===s&&(s=!0);var h=n,a=o,u=1/Math.tan(.5*i),m=s?u/r:u,y=s?u:u*r,c=(a+h)/(a-h),p=-2*a*h/(a-h);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,1,0,0,p,0,e)},r.PerspectiveFovRH=function(t,i,n,o){var e=r.Zero();return r.PerspectiveFovRHToRef(t,i,n,o,e),e},r.PerspectiveFovRHToRef=function(i,r,n,o,e,s){void 0===s&&(s=!0);var h=n,a=o,u=1/Math.tan(.5*i),m=s?u/r:u,y=s?u:u*r,c=-(a+h)/(a-h),p=-2*a*h/(a-h);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,-1,0,0,p,0,e)},r.PerspectiveFovWebVRToRef=function(t,i,r,n,o){void 0===o&&(o=!0);var e=Math.tan(t.upDegrees*Math.PI/180),s=Math.tan(t.downDegrees*Math.PI/180),h=Math.tan(t.leftDegrees*Math.PI/180),a=Math.tan(t.rightDegrees*Math.PI/180),u=2/(h+a),m=2/(e+s);n.m[0]=u,n.m[1]=n.m[2]=n.m[3]=n.m[4]=0,n.m[5]=m,n.m[6]=n.m[7]=0,n.m[8]=(h-a)*u*.5,n.m[9]=-((e-s)*m*.5),n.m[10]=-(i+r)/(r-i),n.m[11]=1,n.m[12]=n.m[13]=n.m[15]=0,n.m[14]=-(2*r*i)/(r-i)},r.GetFinalMatrix=function(t,i,n,o,e,s){var h=t.width,a=t.height,u=t.x,m=t.y,y=r.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,s-e,0,u+h/2,a/2+m,e,1);return i.multiply(n).multiply(o).multiply(y)},r.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},r.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},r.Transpose=function(t){var i=new r;return i.m[0]=t.m[0],i.m[1]=t.m[4],i.m[2]=t.m[8],i.m[3]=t.m[12],i.m[4]=t.m[1],i.m[5]=t.m[5],i.m[6]=t.m[9],i.m[7]=t.m[13],i.m[8]=t.m[2],i.m[9]=t.m[6],i.m[10]=t.m[10],i.m[11]=t.m[14],i.m[12]=t.m[3],i.m[13]=t.m[7],i.m[14]=t.m[11],i.m[15]=t.m[15],i},r.Reflection=function(t){var i=new r;return r.ReflectionToRef(t,i),i},r.ReflectionToRef=function(t,i){t.normalize();var r=t.normal.x,n=t.normal.y,o=t.normal.z,e=-2*r,s=-2*n,h=-2*o;i.m[0]=e*r+1,i.m[1]=s*r,i.m[2]=h*r,i.m[3]=0,i.m[4]=e*n,i.m[5]=s*n+1,i.m[6]=h*n,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1},r.FromXYZAxesToRef=function(t,i,r,n){n.m[0]=t.x,n.m[1]=t.y,n.m[2]=t.z,n.m[3]=0,n.m[4]=i.x,n.m[5]=i.y,n.m[6]=i.z,n.m[7]=0,n.m[8]=r.x,n.m[9]=r.y,n.m[10]=r.z,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},r.FromQuaternionToRef=function(t,i){var r=t.x*t.x,n=t.y*t.y,o=t.z*t.z,e=t.x*t.y,s=t.z*t.w,h=t.z*t.x,a=t.y*t.w,u=t.y*t.z,m=t.x*t.w;i.m[0]=1-2*(n+o),i.m[1]=2*(e+s),i.m[2]=2*(h-a),i.m[3]=0,i.m[4]=2*(e-s),i.m[5]=1-2*(o+r),i.m[6]=2*(u+m),i.m[7]=0,i.m[8]=2*(h+a),i.m[9]=2*(u-m),i.m[10]=1-2*(n+r),i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0,i.m[15]=1},r}();u._tempQuaternion=new a,u._xAxis=e.Zero(),u._yAxis=e.Zero(),u._zAxis=e.Zero(),t.Matrix=u;var m=function(){function t(t,i,r,n){this.normal=new e(t,i,r),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var r=u.Transpose(i),n=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=n*r.m[0]+o*r.m[1]+e*r.m[2]+s*r.m[3],a=n*r.m[4]+o*r.m[5]+e*r.m[6]+s*r.m[7],m=n*r.m[8]+o*r.m[9]+e*r.m[10]+s*r.m[11],y=n*r.m[12]+o*r.m[13]+e*r.m[14]+s*r.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,r){var n,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=r.x-t.x,a=r.y-t.y,u=r.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return n=0!==p?1/p:0,this.normal.x=m*n,this.normal.y=y*n,this.normal.z=c*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var r=e.Dot(this.normal,t);return r<=i},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,r,n){var o=new t(0,0,0,0);return o.copyFromPoints(i,r,n),o},t.FromPositionAndNormal=function(i,r){var n=new t(0,0,0,0);return r.normalize(),n.normal=r,n.d=-(r.x*i.x+r.y*i.y+r.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,r){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(r,i)+n},t}();t.Plane=m;var y=function(){function t(t,i,r,n){this.x=t,this.y=i,this.width=r,this.height=n}return t.prototype.toGlobal=function(i,r){return new t(this.x*i,this.y*r,this.width*i,this.height*r)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var r=[],n=0;n<6;n++)r.push(new m(0,0,0,0));return t.GetPlanesToRef(i,r),r},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c;var p;!function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(p=t.Space||(t.Space={}));var f=function(){function t(){}return t}();f.X=new e(1,0,0),f.Y=new e(0,1,0),f.Z=new e(0,0,1),t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,r,n,o){for(var e=1-3*n+3*i,s=3*n-6*i,h=3*i,a=t,u=0;u<5;u++){var m=a*a,y=m*a,c=e*y+s*m+h*a,p=1/(3*e*m+2*s*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*r+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=x;var l;!function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(l=t.Orientation||(t.Orientation={}));var z=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,r){var n=r.subtract(i),o=Math.atan2(n.y,n.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=z;var w=function(){function t(t,i,r){this.startPoint=t,this.midPoint=i,this.endPoint=r;var n=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-n)/2,s=(n-Math.pow(r.x,2)-Math.pow(r.y,2))/2,h=(t.x-i.x)*(i.y-r.y)-(i.x-r.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-r.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-r.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),u-a<-180&&(u+=360),m-u>180&&(m-=360),m-u<-180&&(m+=360),this.orientation=u-a<0?l.CW:l.CCW,this.angle=z.FromDegrees(this.orientation===l.CW?a-m:m-a)}return t}();t.Arc2=w;var v=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var r=new o(t,i),n=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(n).length(),this},t.prototype.addArcTo=function(t,i,r,n,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(r,n),u=new w(s,h,a),m=u.angle.radians()/e;u.orientation===l.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;c<e;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],r=this._points[0];t+=r.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(t<0||t>1)return o.Zero();for(var i=t*this.length(),r=0,n=0;n<this._points.length;n++){var e=(n+1)%this._points.length,s=this._points[n],h=this._points[e],a=h.subtract(s),u=a.length()+r;if(i>=r&&i<=u){var m=a.normalize(),y=i-r;return new o(s.x+m.x*y,s.y+m.y*y)}r=u}return o.Zero()},t.StartingAt=function(i,r){return new t(i,r)},t}();t.Path2=v;var d=function(){function r(t,i,r){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=r||!1,this._compute(i)}return r.prototype.getCurve=function(){return this._curve},r.prototype.getTangents=function(){return this._tangents},r.prototype.getNormals=function(){return this._normals},r.prototype.getBinormals=function(){return this._binormals},r.prototype.getDistances=function(){return this._distances},r.prototype.update=function(t,i){for(var r=0;r<t.length;r++)this._curve[r].x=t[r].x,this._curve[r].y=t[r].y,this._curve[r].z=t[r].z;return this._compute(i),this},r.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var r=this._tangents[0],n=this._normalVector(this._curve[0],r,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(r,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;u<i;u++)o=this._getLastNonNullVector(u),u<i-1&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},r.prototype._getFirstNonNullVector=function(t){for(var i=1,r=this._curve[t+i].subtract(this._curve[t]);0===r.length()&&t+i+1<this._curve.length;)i++,r=this._curve[t+i].subtract(this._curve[t]);return r},r.prototype._getLastNonNullVector=function(t){for(var i=1,r=this._curve[t].subtract(this._curve[t-i]);0===r.length()&&t>i+1;)i++,r=this._curve[t].subtract(this._curve[t-i]);return r},r.prototype._normalVector=function(r,n,o){var s,h=n.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(n.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,(-1),0),s=e.Cross(n,a)}else s=e.Cross(n,o),e.CrossToRef(s,n,s);return s.normalize(),s},r}();t.Path3D=d;var g=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,r,n,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,r,n){var o=(1-t)*(1-t)*i+2*t*(1-t)*r+t*t*n;return o},a=0;a<=o;a++)s.push(new e(h(a/o,i.x,r.x,n.x),h(a/o,i.y,r.y,n.y),h(a/o,i.z,r.z,n.z)));return new t(s)},t.CreateCubicBezier=function(i,r,n,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,r,n,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*r+3*t*t*(1-t)*n+t*t*t*o;return e},u=0;u<=s;u++)h.push(new e(a(u/s,i.x,r.x,n.x,o.x),a(u/s,i.y,r.y,n.y,o.y),a(u/s,i.z,r.z,n.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,r,n,o,s){for(var h=new Array,a=1/s,u=0;u<=s;u++)h.push(e.Hermite(i,r,n,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var r=this._points[this._points.length-1],n=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)n.push(o[e].subtract(o[0]).add(r));var s=new t(n);return s},t.prototype._computeLength=function(t){for(var i=0,r=1;r<t.length;r++)i+=t[r].subtract(t[r-1]).length();return i},t}();t.Curve3=g;var R=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,r){var n=new e(i.r,i.g,i.b),o=n.scale(r);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=R;var T=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var r=new t;return r.x=i.L11.scale(1.02333),r.y=i.L1_1.scale(1.02333),r.z=i.L10.scale(1.02333),r.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),r.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),r.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),r.yz=i.L2_1.scale(.858086),r.zx=i.L21.scale(.858086),r.xy=i.L2_2.scale(.858086),r},t}();t.SphericalPolynomial=T;var _=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=_;var M=function(){function t(t,i,r){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===r&&(r=o.Zero()),this.position=t,this.normal=i,this.uv=r}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=M;var A=function(){function t(){}return t}();A.Color3=[r.Black(),r.Black(),r.Black()],A.Vector2=[o.Zero(),o.Zero(),o.Zero()],A.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],A.Vector4=[s.Zero(),s.Zero(),s.Zero()],A.Quaternion=[new a(0,0,0,0)],A.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t.Tmp=A}(BABYLON||(BABYLON={}));";
  54935. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  54936. module.exports = BABYLON;
  54937. };