babylon.max.js 2.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560
  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. return Color3;
  211. }());
  212. BABYLON.Color3 = Color3;
  213. var Color4 = (function () {
  214. function Color4(r, g, b, a) {
  215. this.r = r;
  216. this.g = g;
  217. this.b = b;
  218. this.a = a;
  219. }
  220. // Operators
  221. Color4.prototype.addInPlace = function (right) {
  222. this.r += right.r;
  223. this.g += right.g;
  224. this.b += right.b;
  225. this.a += right.a;
  226. return this;
  227. };
  228. Color4.prototype.asArray = function () {
  229. var result = [];
  230. this.toArray(result, 0);
  231. return result;
  232. };
  233. Color4.prototype.toArray = function (array, index) {
  234. if (index === undefined) {
  235. index = 0;
  236. }
  237. array[index] = this.r;
  238. array[index + 1] = this.g;
  239. array[index + 2] = this.b;
  240. array[index + 3] = this.a;
  241. return this;
  242. };
  243. Color4.prototype.add = function (right) {
  244. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  245. };
  246. Color4.prototype.subtract = function (right) {
  247. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  248. };
  249. Color4.prototype.subtractToRef = function (right, result) {
  250. result.r = this.r - right.r;
  251. result.g = this.g - right.g;
  252. result.b = this.b - right.b;
  253. result.a = this.a - right.a;
  254. return this;
  255. };
  256. Color4.prototype.scale = function (scale) {
  257. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  258. };
  259. Color4.prototype.scaleToRef = function (scale, result) {
  260. result.r = this.r * scale;
  261. result.g = this.g * scale;
  262. result.b = this.b * scale;
  263. result.a = this.a * scale;
  264. return this;
  265. };
  266. /**
  267. * Multipy an RGBA Color4 value by another and return a new Color4 object
  268. * @param color The Color4 (RGBA) value to multiply by
  269. * @returns A new Color4.
  270. */
  271. Color4.prototype.multiply = function (color) {
  272. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  273. };
  274. /**
  275. * Multipy an RGBA Color4 value by another and push the result in a reference value
  276. * @param color The Color4 (RGBA) value to multiply by
  277. * @param result The Color4 (RGBA) to fill the result in
  278. * @returns the result Color4.
  279. */
  280. Color4.prototype.multiplyToRef = function (color, result) {
  281. result.r = this.r * color.r;
  282. result.g = this.g * color.g;
  283. result.b = this.b * color.b;
  284. result.a = this.a * color.a;
  285. return result;
  286. };
  287. Color4.prototype.toString = function () {
  288. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  289. };
  290. Color4.prototype.getClassName = function () {
  291. return "Color4";
  292. };
  293. Color4.prototype.getHashCode = function () {
  294. var hash = this.r || 0;
  295. hash = (hash * 397) ^ (this.g || 0);
  296. hash = (hash * 397) ^ (this.b || 0);
  297. hash = (hash * 397) ^ (this.a || 0);
  298. return hash;
  299. };
  300. Color4.prototype.clone = function () {
  301. return new Color4(this.r, this.g, this.b, this.a);
  302. };
  303. Color4.prototype.copyFrom = function (source) {
  304. this.r = source.r;
  305. this.g = source.g;
  306. this.b = source.b;
  307. this.a = source.a;
  308. return this;
  309. };
  310. Color4.prototype.toHexString = function () {
  311. var intR = (this.r * 255) | 0;
  312. var intG = (this.g * 255) | 0;
  313. var intB = (this.b * 255) | 0;
  314. var intA = (this.a * 255) | 0;
  315. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  316. };
  317. // Statics
  318. Color4.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  320. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  321. return new Color4(0, 0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. var a = parseInt(hex.substring(7, 9), 16);
  327. return Color4.FromInts(r, g, b, a);
  328. };
  329. Color4.Lerp = function (left, right, amount) {
  330. var result = new Color4(0, 0, 0, 0);
  331. Color4.LerpToRef(left, right, amount, result);
  332. return result;
  333. };
  334. Color4.LerpToRef = function (left, right, amount, result) {
  335. result.r = left.r + (right.r - left.r) * amount;
  336. result.g = left.g + (right.g - left.g) * amount;
  337. result.b = left.b + (right.b - left.b) * amount;
  338. result.a = left.a + (right.a - left.a) * amount;
  339. };
  340. Color4.FromArray = function (array, offset) {
  341. if (offset === void 0) { offset = 0; }
  342. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  343. };
  344. Color4.FromInts = function (r, g, b, a) {
  345. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  346. };
  347. Color4.CheckColors4 = function (colors, count) {
  348. // Check if color3 was used
  349. if (colors.length === count * 3) {
  350. var colors4 = [];
  351. for (var index = 0; index < colors.length; index += 3) {
  352. var newIndex = (index / 3) * 4;
  353. colors4[newIndex] = colors[index];
  354. colors4[newIndex + 1] = colors[index + 1];
  355. colors4[newIndex + 2] = colors[index + 2];
  356. colors4[newIndex + 3] = 1.0;
  357. }
  358. return colors4;
  359. }
  360. return colors;
  361. };
  362. return Color4;
  363. }());
  364. BABYLON.Color4 = Color4;
  365. var Vector2 = (function () {
  366. function Vector2(x, y) {
  367. this.x = x;
  368. this.y = y;
  369. }
  370. Vector2.prototype.toString = function () {
  371. return "{X: " + this.x + " Y:" + this.y + "}";
  372. };
  373. Vector2.prototype.getClassName = function () {
  374. return "Vector2";
  375. };
  376. Vector2.prototype.getHashCode = function () {
  377. var hash = this.x || 0;
  378. hash = (hash * 397) ^ (this.y || 0);
  379. return hash;
  380. };
  381. // Operators
  382. Vector2.prototype.toArray = function (array, index) {
  383. if (index === void 0) { index = 0; }
  384. array[index] = this.x;
  385. array[index + 1] = this.y;
  386. return this;
  387. };
  388. Vector2.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. Vector2.prototype.copyFrom = function (source) {
  394. this.x = source.x;
  395. this.y = source.y;
  396. return this;
  397. };
  398. Vector2.prototype.copyFromFloats = function (x, y) {
  399. this.x = x;
  400. this.y = y;
  401. return this;
  402. };
  403. Vector2.prototype.add = function (otherVector) {
  404. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  405. };
  406. Vector2.prototype.addToRef = function (otherVector, result) {
  407. result.x = this.x + otherVector.x;
  408. result.y = this.y + otherVector.y;
  409. return this;
  410. };
  411. Vector2.prototype.addInPlace = function (otherVector) {
  412. this.x += otherVector.x;
  413. this.y += otherVector.y;
  414. return this;
  415. };
  416. Vector2.prototype.addVector3 = function (otherVector) {
  417. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  418. };
  419. Vector2.prototype.subtract = function (otherVector) {
  420. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  421. };
  422. Vector2.prototype.subtractToRef = function (otherVector, result) {
  423. result.x = this.x - otherVector.x;
  424. result.y = this.y - otherVector.y;
  425. return this;
  426. };
  427. Vector2.prototype.subtractInPlace = function (otherVector) {
  428. this.x -= otherVector.x;
  429. this.y -= otherVector.y;
  430. return this;
  431. };
  432. Vector2.prototype.multiplyInPlace = function (otherVector) {
  433. this.x *= otherVector.x;
  434. this.y *= otherVector.y;
  435. return this;
  436. };
  437. Vector2.prototype.multiply = function (otherVector) {
  438. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  439. };
  440. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  441. result.x = this.x * otherVector.x;
  442. result.y = this.y * otherVector.y;
  443. return this;
  444. };
  445. Vector2.prototype.multiplyByFloats = function (x, y) {
  446. return new Vector2(this.x * x, this.y * y);
  447. };
  448. Vector2.prototype.divide = function (otherVector) {
  449. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  450. };
  451. Vector2.prototype.divideToRef = function (otherVector, result) {
  452. result.x = this.x / otherVector.x;
  453. result.y = this.y / otherVector.y;
  454. return this;
  455. };
  456. Vector2.prototype.negate = function () {
  457. return new Vector2(-this.x, -this.y);
  458. };
  459. Vector2.prototype.scaleInPlace = function (scale) {
  460. this.x *= scale;
  461. this.y *= scale;
  462. return this;
  463. };
  464. Vector2.prototype.scale = function (scale) {
  465. return new Vector2(this.x * scale, this.y * scale);
  466. };
  467. Vector2.prototype.equals = function (otherVector) {
  468. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  469. };
  470. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  471. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  472. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  473. };
  474. // Properties
  475. Vector2.prototype.length = function () {
  476. return Math.sqrt(this.x * this.x + this.y * this.y);
  477. };
  478. Vector2.prototype.lengthSquared = function () {
  479. return (this.x * this.x + this.y * this.y);
  480. };
  481. // Methods
  482. Vector2.prototype.normalize = function () {
  483. var len = this.length();
  484. if (len === 0)
  485. return this;
  486. var num = 1.0 / len;
  487. this.x *= num;
  488. this.y *= num;
  489. return this;
  490. };
  491. Vector2.prototype.clone = function () {
  492. return new Vector2(this.x, this.y);
  493. };
  494. // Statics
  495. Vector2.Zero = function () {
  496. return new Vector2(0, 0);
  497. };
  498. Vector2.FromArray = function (array, offset) {
  499. if (offset === void 0) { offset = 0; }
  500. return new Vector2(array[offset], array[offset + 1]);
  501. };
  502. Vector2.FromArrayToRef = function (array, offset, result) {
  503. result.x = array[offset];
  504. result.y = array[offset + 1];
  505. };
  506. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  507. var squared = amount * amount;
  508. var cubed = amount * squared;
  509. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  510. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  511. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  512. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  513. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  514. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  515. return new Vector2(x, y);
  516. };
  517. Vector2.Clamp = function (value, min, max) {
  518. var x = value.x;
  519. x = (x > max.x) ? max.x : x;
  520. x = (x < min.x) ? min.x : x;
  521. var y = value.y;
  522. y = (y > max.y) ? max.y : y;
  523. y = (y < min.y) ? min.y : y;
  524. return new Vector2(x, y);
  525. };
  526. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  527. var squared = amount * amount;
  528. var cubed = amount * squared;
  529. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  530. var part2 = (-2.0 * cubed) + (3.0 * squared);
  531. var part3 = (cubed - (2.0 * squared)) + amount;
  532. var part4 = cubed - squared;
  533. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  534. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  535. return new Vector2(x, y);
  536. };
  537. Vector2.Lerp = function (start, end, amount) {
  538. var x = start.x + ((end.x - start.x) * amount);
  539. var y = start.y + ((end.y - start.y) * amount);
  540. return new Vector2(x, y);
  541. };
  542. Vector2.Dot = function (left, right) {
  543. return left.x * right.x + left.y * right.y;
  544. };
  545. Vector2.Normalize = function (vector) {
  546. var newVector = vector.clone();
  547. newVector.normalize();
  548. return newVector;
  549. };
  550. Vector2.Minimize = function (left, right) {
  551. var x = (left.x < right.x) ? left.x : right.x;
  552. var y = (left.y < right.y) ? left.y : right.y;
  553. return new Vector2(x, y);
  554. };
  555. Vector2.Maximize = function (left, right) {
  556. var x = (left.x > right.x) ? left.x : right.x;
  557. var y = (left.y > right.y) ? left.y : right.y;
  558. return new Vector2(x, y);
  559. };
  560. Vector2.Transform = function (vector, transformation) {
  561. var r = Vector2.Zero();
  562. Vector2.TransformToRef(vector, transformation, r);
  563. return r;
  564. };
  565. Vector2.TransformToRef = function (vector, transformation, result) {
  566. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  567. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  568. result.x = x;
  569. result.y = y;
  570. };
  571. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  572. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  573. var sign = a < 0 ? -1 : 1;
  574. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  575. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  576. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  577. };
  578. Vector2.Distance = function (value1, value2) {
  579. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  580. };
  581. Vector2.DistanceSquared = function (value1, value2) {
  582. var x = value1.x - value2.x;
  583. var y = value1.y - value2.y;
  584. return (x * x) + (y * y);
  585. };
  586. Vector2.Center = function (value1, value2) {
  587. var center = value1.add(value2);
  588. center.scaleInPlace(0.5);
  589. return center;
  590. };
  591. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  592. var l2 = Vector2.DistanceSquared(segA, segB);
  593. if (l2 === 0.0) {
  594. return Vector2.Distance(p, segA);
  595. }
  596. var v = segB.subtract(segA);
  597. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  598. var proj = segA.add(v.multiplyByFloats(t, t));
  599. return Vector2.Distance(p, proj);
  600. };
  601. return Vector2;
  602. }());
  603. BABYLON.Vector2 = Vector2;
  604. var Vector3 = (function () {
  605. function Vector3(x, y, z) {
  606. this.x = x;
  607. this.y = y;
  608. this.z = z;
  609. }
  610. Vector3.prototype.toString = function () {
  611. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  612. };
  613. Vector3.prototype.getClassName = function () {
  614. return "Vector3";
  615. };
  616. Vector3.prototype.getHashCode = function () {
  617. var hash = this.x || 0;
  618. hash = (hash * 397) ^ (this.y || 0);
  619. hash = (hash * 397) ^ (this.z || 0);
  620. return hash;
  621. };
  622. // Operators
  623. Vector3.prototype.asArray = function () {
  624. var result = [];
  625. this.toArray(result, 0);
  626. return result;
  627. };
  628. Vector3.prototype.toArray = function (array, index) {
  629. if (index === void 0) { index = 0; }
  630. array[index] = this.x;
  631. array[index + 1] = this.y;
  632. array[index + 2] = this.z;
  633. return this;
  634. };
  635. Vector3.prototype.toQuaternion = function () {
  636. var result = new Quaternion(0, 0, 0, 1);
  637. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  638. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  639. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  640. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  641. var cosy = Math.cos(this.y * 0.5);
  642. var siny = Math.sin(this.y * 0.5);
  643. result.x = coszMinusx * siny;
  644. result.y = -sinzMinusx * siny;
  645. result.z = sinxPlusz * cosy;
  646. result.w = cosxPlusz * cosy;
  647. return result;
  648. };
  649. Vector3.prototype.addInPlace = function (otherVector) {
  650. this.x += otherVector.x;
  651. this.y += otherVector.y;
  652. this.z += otherVector.z;
  653. return this;
  654. };
  655. Vector3.prototype.add = function (otherVector) {
  656. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  657. };
  658. Vector3.prototype.addToRef = function (otherVector, result) {
  659. result.x = this.x + otherVector.x;
  660. result.y = this.y + otherVector.y;
  661. result.z = this.z + otherVector.z;
  662. return this;
  663. };
  664. Vector3.prototype.subtractInPlace = function (otherVector) {
  665. this.x -= otherVector.x;
  666. this.y -= otherVector.y;
  667. this.z -= otherVector.z;
  668. return this;
  669. };
  670. Vector3.prototype.subtract = function (otherVector) {
  671. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  672. };
  673. Vector3.prototype.subtractToRef = function (otherVector, result) {
  674. result.x = this.x - otherVector.x;
  675. result.y = this.y - otherVector.y;
  676. result.z = this.z - otherVector.z;
  677. return this;
  678. };
  679. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  680. return new Vector3(this.x - x, this.y - y, this.z - z);
  681. };
  682. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  683. result.x = this.x - x;
  684. result.y = this.y - y;
  685. result.z = this.z - z;
  686. return this;
  687. };
  688. Vector3.prototype.negate = function () {
  689. return new Vector3(-this.x, -this.y, -this.z);
  690. };
  691. Vector3.prototype.scaleInPlace = function (scale) {
  692. this.x *= scale;
  693. this.y *= scale;
  694. this.z *= scale;
  695. return this;
  696. };
  697. Vector3.prototype.scale = function (scale) {
  698. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  699. };
  700. Vector3.prototype.scaleToRef = function (scale, result) {
  701. result.x = this.x * scale;
  702. result.y = this.y * scale;
  703. result.z = this.z * scale;
  704. };
  705. Vector3.prototype.equals = function (otherVector) {
  706. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  707. };
  708. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  709. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  710. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  711. };
  712. Vector3.prototype.equalsToFloats = function (x, y, z) {
  713. return this.x === x && this.y === y && this.z === z;
  714. };
  715. Vector3.prototype.multiplyInPlace = function (otherVector) {
  716. this.x *= otherVector.x;
  717. this.y *= otherVector.y;
  718. this.z *= otherVector.z;
  719. return this;
  720. };
  721. Vector3.prototype.multiply = function (otherVector) {
  722. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  723. };
  724. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  725. result.x = this.x * otherVector.x;
  726. result.y = this.y * otherVector.y;
  727. result.z = this.z * otherVector.z;
  728. return this;
  729. };
  730. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  731. return new Vector3(this.x * x, this.y * y, this.z * z);
  732. };
  733. Vector3.prototype.divide = function (otherVector) {
  734. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  735. };
  736. Vector3.prototype.divideToRef = function (otherVector, result) {
  737. result.x = this.x / otherVector.x;
  738. result.y = this.y / otherVector.y;
  739. result.z = this.z / otherVector.z;
  740. return this;
  741. };
  742. Vector3.prototype.MinimizeInPlace = function (other) {
  743. if (other.x < this.x)
  744. this.x = other.x;
  745. if (other.y < this.y)
  746. this.y = other.y;
  747. if (other.z < this.z)
  748. this.z = other.z;
  749. return this;
  750. };
  751. Vector3.prototype.MaximizeInPlace = function (other) {
  752. if (other.x > this.x)
  753. this.x = other.x;
  754. if (other.y > this.y)
  755. this.y = other.y;
  756. if (other.z > this.z)
  757. this.z = other.z;
  758. return this;
  759. };
  760. // Properties
  761. Vector3.prototype.length = function () {
  762. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  763. };
  764. Vector3.prototype.lengthSquared = function () {
  765. return (this.x * this.x + this.y * this.y + this.z * this.z);
  766. };
  767. // Methods
  768. Vector3.prototype.normalize = function () {
  769. var len = this.length();
  770. if (len === 0 || len === 1.0)
  771. return this;
  772. var num = 1.0 / len;
  773. this.x *= num;
  774. this.y *= num;
  775. this.z *= num;
  776. return this;
  777. };
  778. Vector3.prototype.clone = function () {
  779. return new Vector3(this.x, this.y, this.z);
  780. };
  781. Vector3.prototype.copyFrom = function (source) {
  782. this.x = source.x;
  783. this.y = source.y;
  784. this.z = source.z;
  785. return this;
  786. };
  787. Vector3.prototype.copyFromFloats = function (x, y, z) {
  788. this.x = x;
  789. this.y = y;
  790. this.z = z;
  791. return this;
  792. };
  793. // Statics
  794. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  795. var d0 = Vector3.Dot(vector0, axis) - size;
  796. var d1 = Vector3.Dot(vector1, axis) - size;
  797. var s = d0 / (d0 - d1);
  798. return s;
  799. };
  800. Vector3.FromArray = function (array, offset) {
  801. if (!offset) {
  802. offset = 0;
  803. }
  804. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  805. };
  806. Vector3.FromFloatArray = function (array, offset) {
  807. if (!offset) {
  808. offset = 0;
  809. }
  810. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  811. };
  812. Vector3.FromArrayToRef = function (array, offset, result) {
  813. result.x = array[offset];
  814. result.y = array[offset + 1];
  815. result.z = array[offset + 2];
  816. };
  817. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  818. result.x = array[offset];
  819. result.y = array[offset + 1];
  820. result.z = array[offset + 2];
  821. };
  822. Vector3.FromFloatsToRef = function (x, y, z, result) {
  823. result.x = x;
  824. result.y = y;
  825. result.z = z;
  826. };
  827. Vector3.Zero = function () {
  828. return new Vector3(0, 0, 0);
  829. };
  830. Vector3.Up = function () {
  831. return new Vector3(0, 1.0, 0);
  832. };
  833. Vector3.Forward = function () {
  834. return new Vector3(0, 0, 1.0);
  835. };
  836. Vector3.Right = function () {
  837. return new Vector3(1.0, 0, 0);
  838. };
  839. Vector3.Left = function () {
  840. return new Vector3(-1.0, 0, 0);
  841. };
  842. Vector3.TransformCoordinates = function (vector, transformation) {
  843. var result = Vector3.Zero();
  844. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  845. return result;
  846. };
  847. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  848. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  849. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  850. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  851. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  852. result.x = x / w;
  853. result.y = y / w;
  854. result.z = z / w;
  855. };
  856. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  857. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  858. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  859. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  860. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  861. result.x = rx / rw;
  862. result.y = ry / rw;
  863. result.z = rz / rw;
  864. };
  865. Vector3.TransformNormal = function (vector, transformation) {
  866. var result = Vector3.Zero();
  867. Vector3.TransformNormalToRef(vector, transformation, result);
  868. return result;
  869. };
  870. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  871. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  872. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  873. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  874. result.x = x;
  875. result.y = y;
  876. result.z = z;
  877. };
  878. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  879. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  880. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  881. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  882. };
  883. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  884. var squared = amount * amount;
  885. var cubed = amount * squared;
  886. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  887. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  888. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  889. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  890. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  891. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  892. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  893. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  894. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  895. return new Vector3(x, y, z);
  896. };
  897. Vector3.Clamp = function (value, min, max) {
  898. var x = value.x;
  899. x = (x > max.x) ? max.x : x;
  900. x = (x < min.x) ? min.x : x;
  901. var y = value.y;
  902. y = (y > max.y) ? max.y : y;
  903. y = (y < min.y) ? min.y : y;
  904. var z = value.z;
  905. z = (z > max.z) ? max.z : z;
  906. z = (z < min.z) ? min.z : z;
  907. return new Vector3(x, y, z);
  908. };
  909. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  910. var squared = amount * amount;
  911. var cubed = amount * squared;
  912. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  913. var part2 = (-2.0 * cubed) + (3.0 * squared);
  914. var part3 = (cubed - (2.0 * squared)) + amount;
  915. var part4 = cubed - squared;
  916. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  917. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  918. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  919. return new Vector3(x, y, z);
  920. };
  921. Vector3.Lerp = function (start, end, amount) {
  922. var x = start.x + ((end.x - start.x) * amount);
  923. var y = start.y + ((end.y - start.y) * amount);
  924. var z = start.z + ((end.z - start.z) * amount);
  925. return new Vector3(x, y, z);
  926. };
  927. Vector3.Dot = function (left, right) {
  928. return (left.x * right.x + left.y * right.y + left.z * right.z);
  929. };
  930. Vector3.Cross = function (left, right) {
  931. var result = Vector3.Zero();
  932. Vector3.CrossToRef(left, right, result);
  933. return result;
  934. };
  935. Vector3.CrossToRef = function (left, right, result) {
  936. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  937. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  938. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  939. result.copyFrom(Tmp.Vector3[0]);
  940. };
  941. Vector3.Normalize = function (vector) {
  942. var result = Vector3.Zero();
  943. Vector3.NormalizeToRef(vector, result);
  944. return result;
  945. };
  946. Vector3.NormalizeToRef = function (vector, result) {
  947. result.copyFrom(vector);
  948. result.normalize();
  949. };
  950. Vector3.Project = function (vector, world, transform, viewport) {
  951. var cw = viewport.width;
  952. var ch = viewport.height;
  953. var cx = viewport.x;
  954. var cy = viewport.y;
  955. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  956. 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);
  957. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  958. world.multiplyToRef(transform, matrix);
  959. matrix.multiplyToRef(viewportMatrix, matrix);
  960. return Vector3.TransformCoordinates(vector, matrix);
  961. };
  962. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  963. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  964. world.multiplyToRef(transform, matrix);
  965. matrix.invert();
  966. source.x = source.x / viewportWidth * 2 - 1;
  967. source.y = -(source.y / viewportHeight * 2 - 1);
  968. var vector = Vector3.TransformCoordinates(source, matrix);
  969. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  970. if (MathTools.WithinEpsilon(num, 1.0)) {
  971. vector = vector.scale(1.0 / num);
  972. }
  973. return vector;
  974. };
  975. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  976. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  977. world.multiplyToRef(view, matrix);
  978. matrix.multiplyToRef(projection, matrix);
  979. matrix.invert();
  980. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  981. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  982. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  983. if (MathTools.WithinEpsilon(num, 1.0)) {
  984. vector = vector.scale(1.0 / num);
  985. }
  986. return vector;
  987. };
  988. Vector3.Minimize = function (left, right) {
  989. var min = left.clone();
  990. min.MinimizeInPlace(right);
  991. return min;
  992. };
  993. Vector3.Maximize = function (left, right) {
  994. var max = left.clone();
  995. max.MaximizeInPlace(right);
  996. return max;
  997. };
  998. Vector3.Distance = function (value1, value2) {
  999. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1000. };
  1001. Vector3.DistanceSquared = function (value1, value2) {
  1002. var x = value1.x - value2.x;
  1003. var y = value1.y - value2.y;
  1004. var z = value1.z - value2.z;
  1005. return (x * x) + (y * y) + (z * z);
  1006. };
  1007. Vector3.Center = function (value1, value2) {
  1008. var center = value1.add(value2);
  1009. center.scaleInPlace(0.5);
  1010. return center;
  1011. };
  1012. /**
  1013. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1014. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1015. * to something in order to rotate it from its local system to the given target system.
  1016. */
  1017. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1018. var rotation = Vector3.Zero();
  1019. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1020. return rotation;
  1021. };
  1022. /**
  1023. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1024. */
  1025. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1026. var u = axis1.normalize();
  1027. var w = axis3.normalize();
  1028. // world axis
  1029. var X = Axis.X;
  1030. var Y = Axis.Y;
  1031. // equation unknowns and vars
  1032. var yaw = 0.0;
  1033. var pitch = 0.0;
  1034. var roll = 0.0;
  1035. var x = 0.0;
  1036. var y = 0.0;
  1037. var z = 0.0;
  1038. var t = 0.0;
  1039. var sign = -1.0;
  1040. var nbRevert = 0;
  1041. var cross = Tmp.Vector3[0];
  1042. var dot = 0.0;
  1043. // step 1 : rotation around w
  1044. // Rv3(u) = u1, and u1 belongs to plane xOz
  1045. // Rv3(w) = w1 = w invariant
  1046. var u1 = Tmp.Vector3[1];
  1047. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1048. z = 1.0;
  1049. }
  1050. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1051. x = 1.0;
  1052. }
  1053. else {
  1054. t = w.z / w.x;
  1055. x = -t * Math.sqrt(1 / (1 + t * t));
  1056. z = Math.sqrt(1 / (1 + t * t));
  1057. }
  1058. u1.x = x;
  1059. u1.y = y;
  1060. u1.z = z;
  1061. u1.normalize();
  1062. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1063. cross.normalize();
  1064. if (Vector3.Dot(w, cross) < 0) {
  1065. sign = 1.0;
  1066. }
  1067. dot = Vector3.Dot(u, u1);
  1068. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1069. roll = Math.acos(dot) * sign;
  1070. if (Vector3.Dot(u1, X) < 0) {
  1071. roll = Math.PI + roll;
  1072. u1 = u1.scaleInPlace(-1);
  1073. nbRevert++;
  1074. }
  1075. // step 2 : rotate around u1
  1076. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1077. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1078. var w2 = Tmp.Vector3[2];
  1079. var v2 = Tmp.Vector3[3];
  1080. x = 0.0;
  1081. y = 0.0;
  1082. z = 0.0;
  1083. sign = -1.0;
  1084. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1085. x = 1.0;
  1086. }
  1087. else {
  1088. t = u1.z / u1.x;
  1089. x = -t * Math.sqrt(1 / (1 + t * t));
  1090. z = Math.sqrt(1 / (1 + t * t));
  1091. }
  1092. w2.x = x;
  1093. w2.y = y;
  1094. w2.z = z;
  1095. w2.normalize();
  1096. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1097. v2.normalize();
  1098. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1099. cross.normalize();
  1100. if (Vector3.Dot(u1, cross) < 0) {
  1101. sign = 1.0;
  1102. }
  1103. dot = Vector3.Dot(w, w2);
  1104. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1105. pitch = Math.acos(dot) * sign;
  1106. if (Vector3.Dot(v2, Y) < 0) {
  1107. pitch = Math.PI + pitch;
  1108. nbRevert++;
  1109. }
  1110. // step 3 : rotate around v2
  1111. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1112. sign = -1.0;
  1113. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1114. cross.normalize();
  1115. if (Vector3.Dot(cross, Y) < 0) {
  1116. sign = 1.0;
  1117. }
  1118. dot = Vector3.Dot(u1, X);
  1119. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1120. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1121. if (dot < 0 && nbRevert < 2) {
  1122. yaw = Math.PI + yaw;
  1123. }
  1124. ref.x = pitch;
  1125. ref.y = yaw;
  1126. ref.z = roll;
  1127. };
  1128. return Vector3;
  1129. }());
  1130. BABYLON.Vector3 = Vector3;
  1131. //Vector4 class created for EulerAngle class conversion to Quaternion
  1132. var Vector4 = (function () {
  1133. function Vector4(x, y, z, w) {
  1134. this.x = x;
  1135. this.y = y;
  1136. this.z = z;
  1137. this.w = w;
  1138. }
  1139. Vector4.prototype.toString = function () {
  1140. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1141. };
  1142. Vector4.prototype.getClassName = function () {
  1143. return "Vector4";
  1144. };
  1145. Vector4.prototype.getHashCode = function () {
  1146. var hash = this.x || 0;
  1147. hash = (hash * 397) ^ (this.y || 0);
  1148. hash = (hash * 397) ^ (this.z || 0);
  1149. hash = (hash * 397) ^ (this.w || 0);
  1150. return hash;
  1151. };
  1152. // Operators
  1153. Vector4.prototype.asArray = function () {
  1154. var result = [];
  1155. this.toArray(result, 0);
  1156. return result;
  1157. };
  1158. Vector4.prototype.toArray = function (array, index) {
  1159. if (index === undefined) {
  1160. index = 0;
  1161. }
  1162. array[index] = this.x;
  1163. array[index + 1] = this.y;
  1164. array[index + 2] = this.z;
  1165. array[index + 3] = this.w;
  1166. return this;
  1167. };
  1168. Vector4.prototype.addInPlace = function (otherVector) {
  1169. this.x += otherVector.x;
  1170. this.y += otherVector.y;
  1171. this.z += otherVector.z;
  1172. this.w += otherVector.w;
  1173. return this;
  1174. };
  1175. Vector4.prototype.add = function (otherVector) {
  1176. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1177. };
  1178. Vector4.prototype.addToRef = function (otherVector, result) {
  1179. result.x = this.x + otherVector.x;
  1180. result.y = this.y + otherVector.y;
  1181. result.z = this.z + otherVector.z;
  1182. result.w = this.w + otherVector.w;
  1183. return this;
  1184. };
  1185. Vector4.prototype.subtractInPlace = function (otherVector) {
  1186. this.x -= otherVector.x;
  1187. this.y -= otherVector.y;
  1188. this.z -= otherVector.z;
  1189. this.w -= otherVector.w;
  1190. return this;
  1191. };
  1192. Vector4.prototype.subtract = function (otherVector) {
  1193. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1194. };
  1195. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1196. result.x = this.x - otherVector.x;
  1197. result.y = this.y - otherVector.y;
  1198. result.z = this.z - otherVector.z;
  1199. result.w = this.w - otherVector.w;
  1200. return this;
  1201. };
  1202. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1203. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1204. };
  1205. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1206. result.x = this.x - x;
  1207. result.y = this.y - y;
  1208. result.z = this.z - z;
  1209. result.w = this.w - w;
  1210. return this;
  1211. };
  1212. Vector4.prototype.negate = function () {
  1213. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1214. };
  1215. Vector4.prototype.scaleInPlace = function (scale) {
  1216. this.x *= scale;
  1217. this.y *= scale;
  1218. this.z *= scale;
  1219. this.w *= scale;
  1220. return this;
  1221. };
  1222. Vector4.prototype.scale = function (scale) {
  1223. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1224. };
  1225. Vector4.prototype.scaleToRef = function (scale, result) {
  1226. result.x = this.x * scale;
  1227. result.y = this.y * scale;
  1228. result.z = this.z * scale;
  1229. result.w = this.w * scale;
  1230. };
  1231. Vector4.prototype.equals = function (otherVector) {
  1232. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1233. };
  1234. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1235. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1236. return otherVector
  1237. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1238. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1239. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1240. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1241. };
  1242. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1243. return this.x === x && this.y === y && this.z === z && this.w === w;
  1244. };
  1245. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1246. this.x *= otherVector.x;
  1247. this.y *= otherVector.y;
  1248. this.z *= otherVector.z;
  1249. this.w *= otherVector.w;
  1250. return this;
  1251. };
  1252. Vector4.prototype.multiply = function (otherVector) {
  1253. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1254. };
  1255. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1256. result.x = this.x * otherVector.x;
  1257. result.y = this.y * otherVector.y;
  1258. result.z = this.z * otherVector.z;
  1259. result.w = this.w * otherVector.w;
  1260. return this;
  1261. };
  1262. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1263. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1264. };
  1265. Vector4.prototype.divide = function (otherVector) {
  1266. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1267. };
  1268. Vector4.prototype.divideToRef = function (otherVector, result) {
  1269. result.x = this.x / otherVector.x;
  1270. result.y = this.y / otherVector.y;
  1271. result.z = this.z / otherVector.z;
  1272. result.w = this.w / otherVector.w;
  1273. return this;
  1274. };
  1275. Vector4.prototype.MinimizeInPlace = function (other) {
  1276. if (other.x < this.x)
  1277. this.x = other.x;
  1278. if (other.y < this.y)
  1279. this.y = other.y;
  1280. if (other.z < this.z)
  1281. this.z = other.z;
  1282. if (other.w < this.w)
  1283. this.w = other.w;
  1284. return this;
  1285. };
  1286. Vector4.prototype.MaximizeInPlace = function (other) {
  1287. if (other.x > this.x)
  1288. this.x = other.x;
  1289. if (other.y > this.y)
  1290. this.y = other.y;
  1291. if (other.z > this.z)
  1292. this.z = other.z;
  1293. if (other.w > this.w)
  1294. this.w = other.w;
  1295. return this;
  1296. };
  1297. // Properties
  1298. Vector4.prototype.length = function () {
  1299. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1300. };
  1301. Vector4.prototype.lengthSquared = function () {
  1302. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1303. };
  1304. // Methods
  1305. Vector4.prototype.normalize = function () {
  1306. var len = this.length();
  1307. if (len === 0)
  1308. return this;
  1309. var num = 1.0 / len;
  1310. this.x *= num;
  1311. this.y *= num;
  1312. this.z *= num;
  1313. this.w *= num;
  1314. return this;
  1315. };
  1316. Vector4.prototype.toVector3 = function () {
  1317. return new Vector3(this.x, this.y, this.z);
  1318. };
  1319. Vector4.prototype.clone = function () {
  1320. return new Vector4(this.x, this.y, this.z, this.w);
  1321. };
  1322. Vector4.prototype.copyFrom = function (source) {
  1323. this.x = source.x;
  1324. this.y = source.y;
  1325. this.z = source.z;
  1326. this.w = source.w;
  1327. return this;
  1328. };
  1329. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1330. this.x = x;
  1331. this.y = y;
  1332. this.z = z;
  1333. this.w = w;
  1334. return this;
  1335. };
  1336. // Statics
  1337. Vector4.FromArray = function (array, offset) {
  1338. if (!offset) {
  1339. offset = 0;
  1340. }
  1341. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1342. };
  1343. Vector4.FromArrayToRef = function (array, offset, result) {
  1344. result.x = array[offset];
  1345. result.y = array[offset + 1];
  1346. result.z = array[offset + 2];
  1347. result.w = array[offset + 3];
  1348. };
  1349. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1350. result.x = array[offset];
  1351. result.y = array[offset + 1];
  1352. result.z = array[offset + 2];
  1353. result.w = array[offset + 3];
  1354. };
  1355. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1356. result.x = x;
  1357. result.y = y;
  1358. result.z = z;
  1359. result.w = w;
  1360. };
  1361. Vector4.Zero = function () {
  1362. return new Vector4(0, 0, 0, 0);
  1363. };
  1364. Vector4.Normalize = function (vector) {
  1365. var result = Vector4.Zero();
  1366. Vector4.NormalizeToRef(vector, result);
  1367. return result;
  1368. };
  1369. Vector4.NormalizeToRef = function (vector, result) {
  1370. result.copyFrom(vector);
  1371. result.normalize();
  1372. };
  1373. Vector4.Minimize = function (left, right) {
  1374. var min = left.clone();
  1375. min.MinimizeInPlace(right);
  1376. return min;
  1377. };
  1378. Vector4.Maximize = function (left, right) {
  1379. var max = left.clone();
  1380. max.MaximizeInPlace(right);
  1381. return max;
  1382. };
  1383. Vector4.Distance = function (value1, value2) {
  1384. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1385. };
  1386. Vector4.DistanceSquared = function (value1, value2) {
  1387. var x = value1.x - value2.x;
  1388. var y = value1.y - value2.y;
  1389. var z = value1.z - value2.z;
  1390. var w = value1.w - value2.w;
  1391. return (x * x) + (y * y) + (z * z) + (w * w);
  1392. };
  1393. Vector4.Center = function (value1, value2) {
  1394. var center = value1.add(value2);
  1395. center.scaleInPlace(0.5);
  1396. return center;
  1397. };
  1398. return Vector4;
  1399. }());
  1400. BABYLON.Vector4 = Vector4;
  1401. var Size = (function () {
  1402. function Size(width, height) {
  1403. this.width = width;
  1404. this.height = height;
  1405. }
  1406. Size.prototype.toString = function () {
  1407. return "{W: " + this.width + ", H: " + this.height + "}";
  1408. };
  1409. Size.prototype.getClassName = function () {
  1410. return "Size";
  1411. };
  1412. Size.prototype.getHashCode = function () {
  1413. var hash = this.width || 0;
  1414. hash = (hash * 397) ^ (this.height || 0);
  1415. return hash;
  1416. };
  1417. Size.prototype.copyFrom = function (src) {
  1418. this.width = src.width;
  1419. this.height = src.height;
  1420. };
  1421. Size.prototype.copyFromFloats = function (width, height) {
  1422. this.width = width;
  1423. this.height = height;
  1424. };
  1425. Size.prototype.multiplyByFloats = function (w, h) {
  1426. return new Size(this.width * w, this.height * h);
  1427. };
  1428. Size.prototype.clone = function () {
  1429. return new Size(this.width, this.height);
  1430. };
  1431. Size.prototype.equals = function (other) {
  1432. if (!other) {
  1433. return false;
  1434. }
  1435. return (this.width === other.width) && (this.height === other.height);
  1436. };
  1437. Object.defineProperty(Size.prototype, "surface", {
  1438. get: function () {
  1439. return this.width * this.height;
  1440. },
  1441. enumerable: true,
  1442. configurable: true
  1443. });
  1444. Size.Zero = function () {
  1445. return new Size(0, 0);
  1446. };
  1447. Size.prototype.add = function (otherSize) {
  1448. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1449. return r;
  1450. };
  1451. Size.prototype.substract = function (otherSize) {
  1452. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1453. return r;
  1454. };
  1455. Size.Lerp = function (start, end, amount) {
  1456. var w = start.width + ((end.width - start.width) * amount);
  1457. var h = start.height + ((end.height - start.height) * amount);
  1458. return new Size(w, h);
  1459. };
  1460. return Size;
  1461. }());
  1462. BABYLON.Size = Size;
  1463. var Quaternion = (function () {
  1464. function Quaternion(x, y, z, w) {
  1465. if (x === void 0) { x = 0; }
  1466. if (y === void 0) { y = 0; }
  1467. if (z === void 0) { z = 0; }
  1468. if (w === void 0) { w = 1; }
  1469. this.x = x;
  1470. this.y = y;
  1471. this.z = z;
  1472. this.w = w;
  1473. }
  1474. Quaternion.prototype.toString = function () {
  1475. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1476. };
  1477. Quaternion.prototype.getClassName = function () {
  1478. return "Quaternion";
  1479. };
  1480. Quaternion.prototype.getHashCode = function () {
  1481. var hash = this.x || 0;
  1482. hash = (hash * 397) ^ (this.y || 0);
  1483. hash = (hash * 397) ^ (this.z || 0);
  1484. hash = (hash * 397) ^ (this.w || 0);
  1485. return hash;
  1486. };
  1487. Quaternion.prototype.asArray = function () {
  1488. return [this.x, this.y, this.z, this.w];
  1489. };
  1490. Quaternion.prototype.equals = function (otherQuaternion) {
  1491. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1492. };
  1493. Quaternion.prototype.clone = function () {
  1494. return new Quaternion(this.x, this.y, this.z, this.w);
  1495. };
  1496. Quaternion.prototype.copyFrom = function (other) {
  1497. this.x = other.x;
  1498. this.y = other.y;
  1499. this.z = other.z;
  1500. this.w = other.w;
  1501. return this;
  1502. };
  1503. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1504. this.x = x;
  1505. this.y = y;
  1506. this.z = z;
  1507. this.w = w;
  1508. return this;
  1509. };
  1510. Quaternion.prototype.add = function (other) {
  1511. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1512. };
  1513. Quaternion.prototype.subtract = function (other) {
  1514. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1515. };
  1516. Quaternion.prototype.scale = function (value) {
  1517. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1518. };
  1519. Quaternion.prototype.multiply = function (q1) {
  1520. var result = new Quaternion(0, 0, 0, 1.0);
  1521. this.multiplyToRef(q1, result);
  1522. return result;
  1523. };
  1524. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1525. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1526. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1527. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1528. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1529. result.copyFromFloats(x, y, z, w);
  1530. return this;
  1531. };
  1532. Quaternion.prototype.multiplyInPlace = function (q1) {
  1533. this.multiplyToRef(q1, this);
  1534. return this;
  1535. };
  1536. Quaternion.prototype.conjugateToRef = function (ref) {
  1537. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1538. return this;
  1539. };
  1540. Quaternion.prototype.conjugateInPlace = function () {
  1541. this.x *= -1;
  1542. this.y *= -1;
  1543. this.z *= -1;
  1544. return this;
  1545. };
  1546. Quaternion.prototype.conjugate = function () {
  1547. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1548. return result;
  1549. };
  1550. Quaternion.prototype.length = function () {
  1551. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1552. };
  1553. Quaternion.prototype.normalize = function () {
  1554. var length = 1.0 / this.length();
  1555. this.x *= length;
  1556. this.y *= length;
  1557. this.z *= length;
  1558. this.w *= length;
  1559. return this;
  1560. };
  1561. Quaternion.prototype.toEulerAngles = function (order) {
  1562. if (order === void 0) { order = "YZX"; }
  1563. var result = Vector3.Zero();
  1564. this.toEulerAnglesToRef(result, order);
  1565. return result;
  1566. };
  1567. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1568. if (order === void 0) { order = "YZX"; }
  1569. var qx = this.x;
  1570. var qy = this.y;
  1571. var qz = this.z;
  1572. var qw = this.w;
  1573. var xsqr = qx * qx;
  1574. var t0 = -2.0 * (xsqr + qy * qy) + 1.0;
  1575. var t1 = 2.0 * (qz * qx + qw * qy);
  1576. var t2 = -2.0 * (qz * qy - qw * qx);
  1577. var t3 = 2.0 * (qx * qy + qw * qz);
  1578. var t4 = -2.0 * (qz * qz + xsqr) + 1.0;
  1579. t2 = t2 > 1.0 ? 1.0 : t2;
  1580. t2 = t2 < -1.0 ? -1.0 : t2;
  1581. result.x = Math.asin(t2);
  1582. result.z = Math.atan2(t3, t4);
  1583. result.y = Math.atan2(t1, t0);
  1584. return this;
  1585. };
  1586. ;
  1587. Quaternion.prototype.toRotationMatrix = function (result) {
  1588. var xx = this.x * this.x;
  1589. var yy = this.y * this.y;
  1590. var zz = this.z * this.z;
  1591. var xy = this.x * this.y;
  1592. var zw = this.z * this.w;
  1593. var zx = this.z * this.x;
  1594. var yw = this.y * this.w;
  1595. var yz = this.y * this.z;
  1596. var xw = this.x * this.w;
  1597. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1598. result.m[1] = 2.0 * (xy + zw);
  1599. result.m[2] = 2.0 * (zx - yw);
  1600. result.m[3] = 0;
  1601. result.m[4] = 2.0 * (xy - zw);
  1602. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1603. result.m[6] = 2.0 * (yz + xw);
  1604. result.m[7] = 0;
  1605. result.m[8] = 2.0 * (zx + yw);
  1606. result.m[9] = 2.0 * (yz - xw);
  1607. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1608. result.m[11] = 0;
  1609. result.m[12] = 0;
  1610. result.m[13] = 0;
  1611. result.m[14] = 0;
  1612. result.m[15] = 1.0;
  1613. return this;
  1614. };
  1615. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1616. Quaternion.FromRotationMatrixToRef(matrix, this);
  1617. return this;
  1618. };
  1619. // Statics
  1620. Quaternion.FromRotationMatrix = function (matrix) {
  1621. var result = new Quaternion();
  1622. Quaternion.FromRotationMatrixToRef(matrix, result);
  1623. return result;
  1624. };
  1625. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1626. var data = matrix.m;
  1627. var m11 = data[0], m12 = data[4], m13 = data[8];
  1628. var m21 = data[1], m22 = data[5], m23 = data[9];
  1629. var m31 = data[2], m32 = data[6], m33 = data[10];
  1630. var trace = m11 + m22 + m33;
  1631. var s;
  1632. if (trace > 0) {
  1633. s = 0.5 / Math.sqrt(trace + 1.0);
  1634. result.w = 0.25 / s;
  1635. result.x = (m32 - m23) * s;
  1636. result.y = (m13 - m31) * s;
  1637. result.z = (m21 - m12) * s;
  1638. }
  1639. else if (m11 > m22 && m11 > m33) {
  1640. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1641. result.w = (m32 - m23) / s;
  1642. result.x = 0.25 * s;
  1643. result.y = (m12 + m21) / s;
  1644. result.z = (m13 + m31) / s;
  1645. }
  1646. else if (m22 > m33) {
  1647. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1648. result.w = (m13 - m31) / s;
  1649. result.x = (m12 + m21) / s;
  1650. result.y = 0.25 * s;
  1651. result.z = (m23 + m32) / s;
  1652. }
  1653. else {
  1654. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1655. result.w = (m21 - m12) / s;
  1656. result.x = (m13 + m31) / s;
  1657. result.y = (m23 + m32) / s;
  1658. result.z = 0.25 * s;
  1659. }
  1660. };
  1661. Quaternion.Inverse = function (q) {
  1662. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1663. };
  1664. Quaternion.Identity = function () {
  1665. return new Quaternion(0, 0, 0, 1);
  1666. };
  1667. Quaternion.RotationAxis = function (axis, angle) {
  1668. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1669. };
  1670. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1671. var sin = Math.sin(angle / 2);
  1672. axis.normalize();
  1673. result.w = Math.cos(angle / 2);
  1674. result.x = axis.x * sin;
  1675. result.y = axis.y * sin;
  1676. result.z = axis.z * sin;
  1677. return result;
  1678. };
  1679. Quaternion.FromArray = function (array, offset) {
  1680. if (!offset) {
  1681. offset = 0;
  1682. }
  1683. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1684. };
  1685. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1686. var q = new Quaternion();
  1687. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1688. return q;
  1689. };
  1690. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1691. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1692. var halfRoll = roll * 0.5;
  1693. var halfPitch = pitch * 0.5;
  1694. var halfYaw = yaw * 0.5;
  1695. var sinRoll = Math.sin(halfRoll);
  1696. var cosRoll = Math.cos(halfRoll);
  1697. var sinPitch = Math.sin(halfPitch);
  1698. var cosPitch = Math.cos(halfPitch);
  1699. var sinYaw = Math.sin(halfYaw);
  1700. var cosYaw = Math.cos(halfYaw);
  1701. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1702. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1703. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1704. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1705. };
  1706. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1707. var result = new Quaternion();
  1708. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1709. return result;
  1710. };
  1711. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1712. // Produces a quaternion from Euler angles in the z-x-z orientation
  1713. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1714. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1715. var halfBeta = beta * 0.5;
  1716. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1717. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1718. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1719. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1720. };
  1721. Quaternion.Slerp = function (left, right, amount) {
  1722. var num2;
  1723. var num3;
  1724. var num = amount;
  1725. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1726. var flag = false;
  1727. if (num4 < 0) {
  1728. flag = true;
  1729. num4 = -num4;
  1730. }
  1731. if (num4 > 0.999999) {
  1732. num3 = 1 - num;
  1733. num2 = flag ? -num : num;
  1734. }
  1735. else {
  1736. var num5 = Math.acos(num4);
  1737. var num6 = (1.0 / Math.sin(num5));
  1738. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1739. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1740. }
  1741. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1742. };
  1743. return Quaternion;
  1744. }());
  1745. BABYLON.Quaternion = Quaternion;
  1746. var Matrix = (function () {
  1747. function Matrix() {
  1748. this.m = new Float32Array(16);
  1749. }
  1750. // Properties
  1751. Matrix.prototype.isIdentity = function () {
  1752. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1753. return false;
  1754. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1755. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1756. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1757. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1758. return false;
  1759. return true;
  1760. };
  1761. Matrix.prototype.determinant = function () {
  1762. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1763. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1764. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1765. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1766. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1767. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1768. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1769. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1770. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1771. };
  1772. // Methods
  1773. Matrix.prototype.toArray = function () {
  1774. return this.m;
  1775. };
  1776. Matrix.prototype.asArray = function () {
  1777. return this.toArray();
  1778. };
  1779. Matrix.prototype.invert = function () {
  1780. this.invertToRef(this);
  1781. return this;
  1782. };
  1783. Matrix.prototype.reset = function () {
  1784. for (var index = 0; index < 16; index++) {
  1785. this.m[index] = 0;
  1786. }
  1787. return this;
  1788. };
  1789. Matrix.prototype.add = function (other) {
  1790. var result = new Matrix();
  1791. this.addToRef(other, result);
  1792. return result;
  1793. };
  1794. Matrix.prototype.addToRef = function (other, result) {
  1795. for (var index = 0; index < 16; index++) {
  1796. result.m[index] = this.m[index] + other.m[index];
  1797. }
  1798. return this;
  1799. };
  1800. Matrix.prototype.addToSelf = function (other) {
  1801. for (var index = 0; index < 16; index++) {
  1802. this.m[index] += other.m[index];
  1803. }
  1804. return this;
  1805. };
  1806. Matrix.prototype.invertToRef = function (other) {
  1807. var l1 = this.m[0];
  1808. var l2 = this.m[1];
  1809. var l3 = this.m[2];
  1810. var l4 = this.m[3];
  1811. var l5 = this.m[4];
  1812. var l6 = this.m[5];
  1813. var l7 = this.m[6];
  1814. var l8 = this.m[7];
  1815. var l9 = this.m[8];
  1816. var l10 = this.m[9];
  1817. var l11 = this.m[10];
  1818. var l12 = this.m[11];
  1819. var l13 = this.m[12];
  1820. var l14 = this.m[13];
  1821. var l15 = this.m[14];
  1822. var l16 = this.m[15];
  1823. var l17 = (l11 * l16) - (l12 * l15);
  1824. var l18 = (l10 * l16) - (l12 * l14);
  1825. var l19 = (l10 * l15) - (l11 * l14);
  1826. var l20 = (l9 * l16) - (l12 * l13);
  1827. var l21 = (l9 * l15) - (l11 * l13);
  1828. var l22 = (l9 * l14) - (l10 * l13);
  1829. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1830. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1831. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1832. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1833. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1834. var l28 = (l7 * l16) - (l8 * l15);
  1835. var l29 = (l6 * l16) - (l8 * l14);
  1836. var l30 = (l6 * l15) - (l7 * l14);
  1837. var l31 = (l5 * l16) - (l8 * l13);
  1838. var l32 = (l5 * l15) - (l7 * l13);
  1839. var l33 = (l5 * l14) - (l6 * l13);
  1840. var l34 = (l7 * l12) - (l8 * l11);
  1841. var l35 = (l6 * l12) - (l8 * l10);
  1842. var l36 = (l6 * l11) - (l7 * l10);
  1843. var l37 = (l5 * l12) - (l8 * l9);
  1844. var l38 = (l5 * l11) - (l7 * l9);
  1845. var l39 = (l5 * l10) - (l6 * l9);
  1846. other.m[0] = l23 * l27;
  1847. other.m[4] = l24 * l27;
  1848. other.m[8] = l25 * l27;
  1849. other.m[12] = l26 * l27;
  1850. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1851. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1852. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1853. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1854. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1855. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1856. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1857. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1858. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1859. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1860. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1861. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1862. return this;
  1863. };
  1864. Matrix.prototype.setTranslation = function (vector3) {
  1865. this.m[12] = vector3.x;
  1866. this.m[13] = vector3.y;
  1867. this.m[14] = vector3.z;
  1868. return this;
  1869. };
  1870. Matrix.prototype.getTranslation = function () {
  1871. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1872. };
  1873. Matrix.prototype.multiply = function (other) {
  1874. var result = new Matrix();
  1875. this.multiplyToRef(other, result);
  1876. return result;
  1877. };
  1878. Matrix.prototype.copyFrom = function (other) {
  1879. for (var index = 0; index < 16; index++) {
  1880. this.m[index] = other.m[index];
  1881. }
  1882. return this;
  1883. };
  1884. Matrix.prototype.copyToArray = function (array, offset) {
  1885. if (offset === void 0) { offset = 0; }
  1886. for (var index = 0; index < 16; index++) {
  1887. array[offset + index] = this.m[index];
  1888. }
  1889. return this;
  1890. };
  1891. Matrix.prototype.multiplyToRef = function (other, result) {
  1892. this.multiplyToArray(other, result.m, 0);
  1893. return this;
  1894. };
  1895. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1896. var tm0 = this.m[0];
  1897. var tm1 = this.m[1];
  1898. var tm2 = this.m[2];
  1899. var tm3 = this.m[3];
  1900. var tm4 = this.m[4];
  1901. var tm5 = this.m[5];
  1902. var tm6 = this.m[6];
  1903. var tm7 = this.m[7];
  1904. var tm8 = this.m[8];
  1905. var tm9 = this.m[9];
  1906. var tm10 = this.m[10];
  1907. var tm11 = this.m[11];
  1908. var tm12 = this.m[12];
  1909. var tm13 = this.m[13];
  1910. var tm14 = this.m[14];
  1911. var tm15 = this.m[15];
  1912. var om0 = other.m[0];
  1913. var om1 = other.m[1];
  1914. var om2 = other.m[2];
  1915. var om3 = other.m[3];
  1916. var om4 = other.m[4];
  1917. var om5 = other.m[5];
  1918. var om6 = other.m[6];
  1919. var om7 = other.m[7];
  1920. var om8 = other.m[8];
  1921. var om9 = other.m[9];
  1922. var om10 = other.m[10];
  1923. var om11 = other.m[11];
  1924. var om12 = other.m[12];
  1925. var om13 = other.m[13];
  1926. var om14 = other.m[14];
  1927. var om15 = other.m[15];
  1928. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1929. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1930. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1931. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1932. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1933. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1934. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1935. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1936. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1937. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1938. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1939. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1940. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1941. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1942. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1943. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1944. return this;
  1945. };
  1946. Matrix.prototype.equals = function (value) {
  1947. return value &&
  1948. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1949. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1950. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1951. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1952. };
  1953. Matrix.prototype.clone = function () {
  1954. 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]);
  1955. };
  1956. Matrix.prototype.getClassName = function () {
  1957. return "Matrix";
  1958. };
  1959. Matrix.prototype.getHashCode = function () {
  1960. var hash = this.m[0] || 0;
  1961. for (var i = 1; i < 16; i++) {
  1962. hash = (hash * 397) ^ (this.m[i] || 0);
  1963. }
  1964. return hash;
  1965. };
  1966. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1967. translation.x = this.m[12];
  1968. translation.y = this.m[13];
  1969. translation.z = this.m[14];
  1970. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1971. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1972. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1973. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1974. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1975. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1976. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1977. rotation.x = 0;
  1978. rotation.y = 0;
  1979. rotation.z = 0;
  1980. rotation.w = 1;
  1981. return false;
  1982. }
  1983. 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]);
  1984. Quaternion.FromRotationMatrixToRef(Tmp.Matrix[0], rotation);
  1985. return true;
  1986. };
  1987. // Statics
  1988. Matrix.FromArray = function (array, offset) {
  1989. var result = new Matrix();
  1990. if (!offset) {
  1991. offset = 0;
  1992. }
  1993. Matrix.FromArrayToRef(array, offset, result);
  1994. return result;
  1995. };
  1996. Matrix.FromArrayToRef = function (array, offset, result) {
  1997. for (var index = 0; index < 16; index++) {
  1998. result.m[index] = array[index + offset];
  1999. }
  2000. };
  2001. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2002. for (var index = 0; index < 16; index++) {
  2003. result.m[index] = array[index + offset] * scale;
  2004. }
  2005. };
  2006. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2007. result.m[0] = initialM11;
  2008. result.m[1] = initialM12;
  2009. result.m[2] = initialM13;
  2010. result.m[3] = initialM14;
  2011. result.m[4] = initialM21;
  2012. result.m[5] = initialM22;
  2013. result.m[6] = initialM23;
  2014. result.m[7] = initialM24;
  2015. result.m[8] = initialM31;
  2016. result.m[9] = initialM32;
  2017. result.m[10] = initialM33;
  2018. result.m[11] = initialM34;
  2019. result.m[12] = initialM41;
  2020. result.m[13] = initialM42;
  2021. result.m[14] = initialM43;
  2022. result.m[15] = initialM44;
  2023. };
  2024. Matrix.prototype.getRow = function (index) {
  2025. if (index < 0 || index > 3) {
  2026. return null;
  2027. }
  2028. var i = index * 4;
  2029. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2030. };
  2031. Matrix.prototype.setRow = function (index, row) {
  2032. if (index < 0 || index > 3) {
  2033. return this;
  2034. }
  2035. var i = index * 4;
  2036. this.m[i + 0] = row.x;
  2037. this.m[i + 1] = row.y;
  2038. this.m[i + 2] = row.z;
  2039. this.m[i + 3] = row.w;
  2040. return this;
  2041. };
  2042. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2043. var result = new Matrix();
  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. return result;
  2061. };
  2062. Matrix.Compose = function (scale, rotation, translation) {
  2063. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2064. var rotationMatrix = Matrix.Identity();
  2065. rotation.toRotationMatrix(rotationMatrix);
  2066. result = result.multiply(rotationMatrix);
  2067. result.setTranslation(translation);
  2068. return result;
  2069. };
  2070. Matrix.Identity = function () {
  2071. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2072. };
  2073. Matrix.IdentityToRef = function (result) {
  2074. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2075. };
  2076. Matrix.Zero = function () {
  2077. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2078. };
  2079. Matrix.RotationX = function (angle) {
  2080. var result = new Matrix();
  2081. Matrix.RotationXToRef(angle, result);
  2082. return result;
  2083. };
  2084. Matrix.Invert = function (source) {
  2085. var result = new Matrix();
  2086. source.invertToRef(result);
  2087. return result;
  2088. };
  2089. Matrix.RotationXToRef = function (angle, result) {
  2090. var s = Math.sin(angle);
  2091. var c = Math.cos(angle);
  2092. result.m[0] = 1.0;
  2093. result.m[15] = 1.0;
  2094. result.m[5] = c;
  2095. result.m[10] = c;
  2096. result.m[9] = -s;
  2097. result.m[6] = s;
  2098. result.m[1] = 0;
  2099. result.m[2] = 0;
  2100. result.m[3] = 0;
  2101. result.m[4] = 0;
  2102. result.m[7] = 0;
  2103. result.m[8] = 0;
  2104. result.m[11] = 0;
  2105. result.m[12] = 0;
  2106. result.m[13] = 0;
  2107. result.m[14] = 0;
  2108. };
  2109. Matrix.RotationY = function (angle) {
  2110. var result = new Matrix();
  2111. Matrix.RotationYToRef(angle, result);
  2112. return result;
  2113. };
  2114. Matrix.RotationYToRef = function (angle, result) {
  2115. var s = Math.sin(angle);
  2116. var c = Math.cos(angle);
  2117. result.m[5] = 1.0;
  2118. result.m[15] = 1.0;
  2119. result.m[0] = c;
  2120. result.m[2] = -s;
  2121. result.m[8] = s;
  2122. result.m[10] = c;
  2123. result.m[1] = 0;
  2124. result.m[3] = 0;
  2125. result.m[4] = 0;
  2126. result.m[6] = 0;
  2127. result.m[7] = 0;
  2128. result.m[9] = 0;
  2129. result.m[11] = 0;
  2130. result.m[12] = 0;
  2131. result.m[13] = 0;
  2132. result.m[14] = 0;
  2133. };
  2134. Matrix.RotationZ = function (angle) {
  2135. var result = new Matrix();
  2136. Matrix.RotationZToRef(angle, result);
  2137. return result;
  2138. };
  2139. Matrix.RotationZToRef = function (angle, result) {
  2140. var s = Math.sin(angle);
  2141. var c = Math.cos(angle);
  2142. result.m[10] = 1.0;
  2143. result.m[15] = 1.0;
  2144. result.m[0] = c;
  2145. result.m[1] = s;
  2146. result.m[4] = -s;
  2147. result.m[5] = c;
  2148. result.m[2] = 0;
  2149. result.m[3] = 0;
  2150. result.m[6] = 0;
  2151. result.m[7] = 0;
  2152. result.m[8] = 0;
  2153. result.m[9] = 0;
  2154. result.m[11] = 0;
  2155. result.m[12] = 0;
  2156. result.m[13] = 0;
  2157. result.m[14] = 0;
  2158. };
  2159. Matrix.RotationAxis = function (axis, angle) {
  2160. var result = Matrix.Zero();
  2161. Matrix.RotationAxisToRef(axis, angle, result);
  2162. return result;
  2163. };
  2164. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2165. var s = Math.sin(-angle);
  2166. var c = Math.cos(-angle);
  2167. var c1 = 1 - c;
  2168. axis.normalize();
  2169. result.m[0] = (axis.x * axis.x) * c1 + c;
  2170. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2171. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2172. result.m[3] = 0.0;
  2173. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2174. result.m[5] = (axis.y * axis.y) * c1 + c;
  2175. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2176. result.m[7] = 0.0;
  2177. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2178. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2179. result.m[10] = (axis.z * axis.z) * c1 + c;
  2180. result.m[11] = 0.0;
  2181. result.m[15] = 1.0;
  2182. };
  2183. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2184. var result = new Matrix();
  2185. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2186. return result;
  2187. };
  2188. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2189. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2190. this._tempQuaternion.toRotationMatrix(result);
  2191. };
  2192. Matrix.Scaling = function (x, y, z) {
  2193. var result = Matrix.Zero();
  2194. Matrix.ScalingToRef(x, y, z, result);
  2195. return result;
  2196. };
  2197. Matrix.ScalingToRef = function (x, y, z, result) {
  2198. result.m[0] = x;
  2199. result.m[1] = 0;
  2200. result.m[2] = 0;
  2201. result.m[3] = 0;
  2202. result.m[4] = 0;
  2203. result.m[5] = y;
  2204. result.m[6] = 0;
  2205. result.m[7] = 0;
  2206. result.m[8] = 0;
  2207. result.m[9] = 0;
  2208. result.m[10] = z;
  2209. result.m[11] = 0;
  2210. result.m[12] = 0;
  2211. result.m[13] = 0;
  2212. result.m[14] = 0;
  2213. result.m[15] = 1.0;
  2214. };
  2215. Matrix.Translation = function (x, y, z) {
  2216. var result = Matrix.Identity();
  2217. Matrix.TranslationToRef(x, y, z, result);
  2218. return result;
  2219. };
  2220. Matrix.TranslationToRef = function (x, y, z, result) {
  2221. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2222. };
  2223. Matrix.Lerp = function (startValue, endValue, gradient) {
  2224. var result = Matrix.Zero();
  2225. for (var index = 0; index < 16; index++) {
  2226. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2227. }
  2228. return result;
  2229. };
  2230. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2231. var startScale = new Vector3(0, 0, 0);
  2232. var startRotation = new Quaternion();
  2233. var startTranslation = new Vector3(0, 0, 0);
  2234. startValue.decompose(startScale, startRotation, startTranslation);
  2235. var endScale = new Vector3(0, 0, 0);
  2236. var endRotation = new Quaternion();
  2237. var endTranslation = new Vector3(0, 0, 0);
  2238. endValue.decompose(endScale, endRotation, endTranslation);
  2239. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2240. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2241. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2242. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2243. };
  2244. Matrix.LookAtLH = function (eye, target, up) {
  2245. var result = Matrix.Zero();
  2246. Matrix.LookAtLHToRef(eye, target, up, result);
  2247. return result;
  2248. };
  2249. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2250. // Z axis
  2251. target.subtractToRef(eye, this._zAxis);
  2252. this._zAxis.normalize();
  2253. // X axis
  2254. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2255. if (this._xAxis.lengthSquared() === 0) {
  2256. this._xAxis.x = 1.0;
  2257. }
  2258. else {
  2259. this._xAxis.normalize();
  2260. }
  2261. // Y axis
  2262. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2263. this._yAxis.normalize();
  2264. // Eye angles
  2265. var ex = -Vector3.Dot(this._xAxis, eye);
  2266. var ey = -Vector3.Dot(this._yAxis, eye);
  2267. var ez = -Vector3.Dot(this._zAxis, eye);
  2268. 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);
  2269. };
  2270. Matrix.LookAtRH = function (eye, target, up) {
  2271. var result = Matrix.Zero();
  2272. Matrix.LookAtRHToRef(eye, target, up, result);
  2273. return result;
  2274. };
  2275. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  2276. // Z axis
  2277. eye.subtractToRef(target, this._zAxis);
  2278. this._zAxis.normalize();
  2279. // X axis
  2280. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2281. if (this._xAxis.lengthSquared() === 0) {
  2282. this._xAxis.x = 1.0;
  2283. }
  2284. else {
  2285. this._xAxis.normalize();
  2286. }
  2287. // Y axis
  2288. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2289. this._yAxis.normalize();
  2290. // Eye angles
  2291. var ex = -Vector3.Dot(this._xAxis, eye);
  2292. var ey = -Vector3.Dot(this._yAxis, eye);
  2293. var ez = -Vector3.Dot(this._zAxis, eye);
  2294. 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);
  2295. };
  2296. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2297. var matrix = Matrix.Zero();
  2298. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2299. return matrix;
  2300. };
  2301. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2302. var hw = 2.0 / width;
  2303. var hh = 2.0 / height;
  2304. var id = 1.0 / (zfar - znear);
  2305. var nid = znear / (znear - zfar);
  2306. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2307. };
  2308. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2309. var matrix = Matrix.Zero();
  2310. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2311. return matrix;
  2312. };
  2313. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2314. result.m[0] = 2.0 / (right - left);
  2315. result.m[1] = result.m[2] = result.m[3] = 0;
  2316. result.m[5] = 2.0 / (top - bottom);
  2317. result.m[4] = result.m[6] = result.m[7] = 0;
  2318. result.m[10] = 1.0 / (zfar - znear);
  2319. result.m[8] = result.m[9] = result.m[11] = 0;
  2320. result.m[12] = (left + right) / (left - right);
  2321. result.m[13] = (top + bottom) / (bottom - top);
  2322. result.m[14] = -znear / (zfar - znear);
  2323. result.m[15] = 1.0;
  2324. };
  2325. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  2326. var matrix = Matrix.Zero();
  2327. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  2328. return matrix;
  2329. };
  2330. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2331. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  2332. result.m[10] *= -1.0;
  2333. };
  2334. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2335. var matrix = Matrix.Zero();
  2336. matrix.m[0] = (2.0 * znear) / width;
  2337. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2338. matrix.m[5] = (2.0 * znear) / height;
  2339. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2340. matrix.m[10] = -zfar / (znear - zfar);
  2341. matrix.m[8] = matrix.m[9] = 0.0;
  2342. matrix.m[11] = 1.0;
  2343. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2344. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2345. return matrix;
  2346. };
  2347. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2348. var matrix = Matrix.Zero();
  2349. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2350. return matrix;
  2351. };
  2352. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2353. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2354. var tan = 1.0 / (Math.tan(fov * 0.5));
  2355. if (isVerticalFovFixed) {
  2356. result.m[0] = tan / aspect;
  2357. }
  2358. else {
  2359. result.m[0] = tan;
  2360. }
  2361. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2362. if (isVerticalFovFixed) {
  2363. result.m[5] = tan;
  2364. }
  2365. else {
  2366. result.m[5] = tan * aspect;
  2367. }
  2368. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2369. result.m[8] = result.m[9] = 0.0;
  2370. result.m[10] = zfar / (zfar - znear);
  2371. result.m[11] = 1.0;
  2372. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2373. result.m[14] = -(znear * zfar) / (zfar - znear);
  2374. };
  2375. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  2376. var matrix = Matrix.Zero();
  2377. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  2378. return matrix;
  2379. };
  2380. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2381. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2382. var tan = 1.0 / (Math.tan(fov * 0.5));
  2383. if (isVerticalFovFixed) {
  2384. result.m[0] = tan / aspect;
  2385. }
  2386. else {
  2387. result.m[0] = tan;
  2388. }
  2389. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2390. if (isVerticalFovFixed) {
  2391. result.m[5] = tan;
  2392. }
  2393. else {
  2394. result.m[5] = tan * aspect;
  2395. }
  2396. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2397. result.m[8] = result.m[9] = 0.0;
  2398. result.m[10] = zfar / (znear - zfar);
  2399. result.m[11] = -1.0;
  2400. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2401. result.m[14] = (znear * zfar) / (znear - zfar);
  2402. };
  2403. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
  2404. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2405. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  2406. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  2407. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  2408. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  2409. var xScale = 2.0 / (leftTan + rightTan);
  2410. var yScale = 2.0 / (upTan + downTan);
  2411. result.m[0] = xScale;
  2412. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  2413. result.m[5] = yScale;
  2414. result.m[6] = result.m[7] = 0.0;
  2415. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  2416. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  2417. //result.m[10] = -(znear + zfar) / (zfar - znear);
  2418. result.m[10] = -zfar / (znear - zfar);
  2419. result.m[11] = 1.0;
  2420. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2421. //result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  2422. result.m[14] = (znear * zfar) / (znear - zfar);
  2423. };
  2424. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2425. var cw = viewport.width;
  2426. var ch = viewport.height;
  2427. var cx = viewport.x;
  2428. var cy = viewport.y;
  2429. 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);
  2430. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2431. };
  2432. Matrix.GetAsMatrix2x2 = function (matrix) {
  2433. return new Float32Array([
  2434. matrix.m[0], matrix.m[1],
  2435. matrix.m[4], matrix.m[5]
  2436. ]);
  2437. };
  2438. Matrix.GetAsMatrix3x3 = function (matrix) {
  2439. return new Float32Array([
  2440. matrix.m[0], matrix.m[1], matrix.m[2],
  2441. matrix.m[4], matrix.m[5], matrix.m[6],
  2442. matrix.m[8], matrix.m[9], matrix.m[10]
  2443. ]);
  2444. };
  2445. Matrix.Transpose = function (matrix) {
  2446. var result = new Matrix();
  2447. result.m[0] = matrix.m[0];
  2448. result.m[1] = matrix.m[4];
  2449. result.m[2] = matrix.m[8];
  2450. result.m[3] = matrix.m[12];
  2451. result.m[4] = matrix.m[1];
  2452. result.m[5] = matrix.m[5];
  2453. result.m[6] = matrix.m[9];
  2454. result.m[7] = matrix.m[13];
  2455. result.m[8] = matrix.m[2];
  2456. result.m[9] = matrix.m[6];
  2457. result.m[10] = matrix.m[10];
  2458. result.m[11] = matrix.m[14];
  2459. result.m[12] = matrix.m[3];
  2460. result.m[13] = matrix.m[7];
  2461. result.m[14] = matrix.m[11];
  2462. result.m[15] = matrix.m[15];
  2463. return result;
  2464. };
  2465. Matrix.Reflection = function (plane) {
  2466. var matrix = new Matrix();
  2467. Matrix.ReflectionToRef(plane, matrix);
  2468. return matrix;
  2469. };
  2470. Matrix.ReflectionToRef = function (plane, result) {
  2471. plane.normalize();
  2472. var x = plane.normal.x;
  2473. var y = plane.normal.y;
  2474. var z = plane.normal.z;
  2475. var temp = -2 * x;
  2476. var temp2 = -2 * y;
  2477. var temp3 = -2 * z;
  2478. result.m[0] = (temp * x) + 1;
  2479. result.m[1] = temp2 * x;
  2480. result.m[2] = temp3 * x;
  2481. result.m[3] = 0.0;
  2482. result.m[4] = temp * y;
  2483. result.m[5] = (temp2 * y) + 1;
  2484. result.m[6] = temp3 * y;
  2485. result.m[7] = 0.0;
  2486. result.m[8] = temp * z;
  2487. result.m[9] = temp2 * z;
  2488. result.m[10] = (temp3 * z) + 1;
  2489. result.m[11] = 0.0;
  2490. result.m[12] = temp * plane.d;
  2491. result.m[13] = temp2 * plane.d;
  2492. result.m[14] = temp3 * plane.d;
  2493. result.m[15] = 1.0;
  2494. };
  2495. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, mat) {
  2496. mat.m[0] = xaxis.x;
  2497. mat.m[1] = xaxis.y;
  2498. mat.m[2] = xaxis.z;
  2499. mat.m[3] = 0;
  2500. mat.m[4] = yaxis.x;
  2501. mat.m[5] = yaxis.y;
  2502. mat.m[6] = yaxis.z;
  2503. mat.m[7] = 0;
  2504. mat.m[8] = zaxis.x;
  2505. mat.m[9] = zaxis.y;
  2506. mat.m[10] = zaxis.z;
  2507. mat.m[11] = 0;
  2508. mat.m[12] = 0;
  2509. mat.m[13] = 0;
  2510. mat.m[14] = 0;
  2511. mat.m[15] = 1;
  2512. };
  2513. Matrix._tempQuaternion = new Quaternion();
  2514. Matrix._xAxis = Vector3.Zero();
  2515. Matrix._yAxis = Vector3.Zero();
  2516. Matrix._zAxis = Vector3.Zero();
  2517. return Matrix;
  2518. }());
  2519. BABYLON.Matrix = Matrix;
  2520. var Plane = (function () {
  2521. function Plane(a, b, c, d) {
  2522. this.normal = new Vector3(a, b, c);
  2523. this.d = d;
  2524. }
  2525. Plane.prototype.asArray = function () {
  2526. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2527. };
  2528. // Methods
  2529. Plane.prototype.clone = function () {
  2530. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2531. };
  2532. Plane.prototype.getClassName = function () {
  2533. return "Plane";
  2534. };
  2535. Plane.prototype.getHashCode = function () {
  2536. var hash = this.normal.getHashCode();
  2537. hash = (hash * 397) ^ (this.d || 0);
  2538. return hash;
  2539. };
  2540. Plane.prototype.normalize = function () {
  2541. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2542. var magnitude = 0;
  2543. if (norm !== 0) {
  2544. magnitude = 1.0 / norm;
  2545. }
  2546. this.normal.x *= magnitude;
  2547. this.normal.y *= magnitude;
  2548. this.normal.z *= magnitude;
  2549. this.d *= magnitude;
  2550. return this;
  2551. };
  2552. Plane.prototype.transform = function (transformation) {
  2553. var transposedMatrix = Matrix.Transpose(transformation);
  2554. var x = this.normal.x;
  2555. var y = this.normal.y;
  2556. var z = this.normal.z;
  2557. var d = this.d;
  2558. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2559. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2560. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2561. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2562. return new Plane(normalX, normalY, normalZ, finalD);
  2563. };
  2564. Plane.prototype.dotCoordinate = function (point) {
  2565. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2566. };
  2567. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2568. var x1 = point2.x - point1.x;
  2569. var y1 = point2.y - point1.y;
  2570. var z1 = point2.z - point1.z;
  2571. var x2 = point3.x - point1.x;
  2572. var y2 = point3.y - point1.y;
  2573. var z2 = point3.z - point1.z;
  2574. var yz = (y1 * z2) - (z1 * y2);
  2575. var xz = (z1 * x2) - (x1 * z2);
  2576. var xy = (x1 * y2) - (y1 * x2);
  2577. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2578. var invPyth;
  2579. if (pyth !== 0) {
  2580. invPyth = 1.0 / pyth;
  2581. }
  2582. else {
  2583. invPyth = 0;
  2584. }
  2585. this.normal.x = yz * invPyth;
  2586. this.normal.y = xz * invPyth;
  2587. this.normal.z = xy * invPyth;
  2588. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2589. return this;
  2590. };
  2591. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2592. var dot = Vector3.Dot(this.normal, direction);
  2593. return (dot <= epsilon);
  2594. };
  2595. Plane.prototype.signedDistanceTo = function (point) {
  2596. return Vector3.Dot(point, this.normal) + this.d;
  2597. };
  2598. // Statics
  2599. Plane.FromArray = function (array) {
  2600. return new Plane(array[0], array[1], array[2], array[3]);
  2601. };
  2602. Plane.FromPoints = function (point1, point2, point3) {
  2603. var result = new Plane(0, 0, 0, 0);
  2604. result.copyFromPoints(point1, point2, point3);
  2605. return result;
  2606. };
  2607. Plane.FromPositionAndNormal = function (origin, normal) {
  2608. var result = new Plane(0, 0, 0, 0);
  2609. normal.normalize();
  2610. result.normal = normal;
  2611. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2612. return result;
  2613. };
  2614. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2615. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2616. return Vector3.Dot(point, normal) + d;
  2617. };
  2618. return Plane;
  2619. }());
  2620. BABYLON.Plane = Plane;
  2621. var Viewport = (function () {
  2622. function Viewport(x, y, width, height) {
  2623. this.x = x;
  2624. this.y = y;
  2625. this.width = width;
  2626. this.height = height;
  2627. }
  2628. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2629. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2630. };
  2631. return Viewport;
  2632. }());
  2633. BABYLON.Viewport = Viewport;
  2634. var Frustum = (function () {
  2635. function Frustum() {
  2636. }
  2637. Frustum.GetPlanes = function (transform) {
  2638. var frustumPlanes = [];
  2639. for (var index = 0; index < 6; index++) {
  2640. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2641. }
  2642. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2643. return frustumPlanes;
  2644. };
  2645. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2646. // Near
  2647. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2648. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2649. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2650. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2651. frustumPlanes[0].normalize();
  2652. // Far
  2653. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2654. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2655. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2656. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2657. frustumPlanes[1].normalize();
  2658. // Left
  2659. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2660. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2661. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2662. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2663. frustumPlanes[2].normalize();
  2664. // Right
  2665. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2666. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2667. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2668. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2669. frustumPlanes[3].normalize();
  2670. // Top
  2671. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2672. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2673. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2674. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2675. frustumPlanes[4].normalize();
  2676. // Bottom
  2677. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2678. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2679. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2680. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2681. frustumPlanes[5].normalize();
  2682. };
  2683. return Frustum;
  2684. }());
  2685. BABYLON.Frustum = Frustum;
  2686. (function (Space) {
  2687. Space[Space["LOCAL"] = 0] = "LOCAL";
  2688. Space[Space["WORLD"] = 1] = "WORLD";
  2689. })(BABYLON.Space || (BABYLON.Space = {}));
  2690. var Space = BABYLON.Space;
  2691. var Axis = (function () {
  2692. function Axis() {
  2693. }
  2694. Axis.X = new Vector3(1, 0, 0);
  2695. Axis.Y = new Vector3(0, 1, 0);
  2696. Axis.Z = new Vector3(0, 0, 1);
  2697. return Axis;
  2698. }());
  2699. BABYLON.Axis = Axis;
  2700. ;
  2701. var BezierCurve = (function () {
  2702. function BezierCurve() {
  2703. }
  2704. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2705. // Extract X (which is equal to time here)
  2706. var f0 = 1 - 3 * x2 + 3 * x1;
  2707. var f1 = 3 * x2 - 6 * x1;
  2708. var f2 = 3 * x1;
  2709. var refinedT = t;
  2710. for (var i = 0; i < 5; i++) {
  2711. var refinedT2 = refinedT * refinedT;
  2712. var refinedT3 = refinedT2 * refinedT;
  2713. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2714. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2715. refinedT -= (x - t) * slope;
  2716. refinedT = Math.min(1, Math.max(0, refinedT));
  2717. }
  2718. // Resolve cubic bezier for the given x
  2719. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2720. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2721. Math.pow(refinedT, 3);
  2722. };
  2723. return BezierCurve;
  2724. }());
  2725. BABYLON.BezierCurve = BezierCurve;
  2726. (function (Orientation) {
  2727. Orientation[Orientation["CW"] = 0] = "CW";
  2728. Orientation[Orientation["CCW"] = 1] = "CCW";
  2729. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2730. var Orientation = BABYLON.Orientation;
  2731. var Angle = (function () {
  2732. function Angle(radians) {
  2733. var _this = this;
  2734. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2735. this.radians = function () { return _this._radians; };
  2736. this._radians = radians;
  2737. if (this._radians < 0)
  2738. this._radians += (2 * Math.PI);
  2739. }
  2740. Angle.BetweenTwoPoints = function (a, b) {
  2741. var delta = b.subtract(a);
  2742. var theta = Math.atan2(delta.y, delta.x);
  2743. return new Angle(theta);
  2744. };
  2745. Angle.FromRadians = function (radians) {
  2746. return new Angle(radians);
  2747. };
  2748. Angle.FromDegrees = function (degrees) {
  2749. return new Angle(degrees * Math.PI / 180);
  2750. };
  2751. return Angle;
  2752. }());
  2753. BABYLON.Angle = Angle;
  2754. var Arc2 = (function () {
  2755. function Arc2(startPoint, midPoint, endPoint) {
  2756. this.startPoint = startPoint;
  2757. this.midPoint = midPoint;
  2758. this.endPoint = endPoint;
  2759. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2760. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2761. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2762. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2763. 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);
  2764. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2765. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2766. var a1 = this.startAngle.degrees();
  2767. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2768. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2769. // angles correction
  2770. if (a2 - a1 > +180.0)
  2771. a2 -= 360.0;
  2772. if (a2 - a1 < -180.0)
  2773. a2 += 360.0;
  2774. if (a3 - a2 > +180.0)
  2775. a3 -= 360.0;
  2776. if (a3 - a2 < -180.0)
  2777. a3 += 360.0;
  2778. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2779. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2780. }
  2781. return Arc2;
  2782. }());
  2783. BABYLON.Arc2 = Arc2;
  2784. var Path2 = (function () {
  2785. function Path2(x, y) {
  2786. this._points = new Array();
  2787. this._length = 0;
  2788. this.closed = false;
  2789. this._points.push(new Vector2(x, y));
  2790. }
  2791. Path2.prototype.addLineTo = function (x, y) {
  2792. if (closed) {
  2793. //Tools.Error("cannot add lines to closed paths");
  2794. return this;
  2795. }
  2796. var newPoint = new Vector2(x, y);
  2797. var previousPoint = this._points[this._points.length - 1];
  2798. this._points.push(newPoint);
  2799. this._length += newPoint.subtract(previousPoint).length();
  2800. return this;
  2801. };
  2802. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2803. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2804. if (closed) {
  2805. //Tools.Error("cannot add arcs to closed paths");
  2806. return this;
  2807. }
  2808. var startPoint = this._points[this._points.length - 1];
  2809. var midPoint = new Vector2(midX, midY);
  2810. var endPoint = new Vector2(endX, endY);
  2811. var arc = new Arc2(startPoint, midPoint, endPoint);
  2812. var increment = arc.angle.radians() / numberOfSegments;
  2813. if (arc.orientation === Orientation.CW)
  2814. increment *= -1;
  2815. var currentAngle = arc.startAngle.radians() + increment;
  2816. for (var i = 0; i < numberOfSegments; i++) {
  2817. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2818. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2819. this.addLineTo(x, y);
  2820. currentAngle += increment;
  2821. }
  2822. return this;
  2823. };
  2824. Path2.prototype.close = function () {
  2825. this.closed = true;
  2826. return this;
  2827. };
  2828. Path2.prototype.length = function () {
  2829. var result = this._length;
  2830. if (!this.closed) {
  2831. var lastPoint = this._points[this._points.length - 1];
  2832. var firstPoint = this._points[0];
  2833. result += (firstPoint.subtract(lastPoint).length());
  2834. }
  2835. return result;
  2836. };
  2837. Path2.prototype.getPoints = function () {
  2838. return this._points;
  2839. };
  2840. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2841. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2842. //Tools.Error("normalized length position should be between 0 and 1.");
  2843. return Vector2.Zero();
  2844. }
  2845. var lengthPosition = normalizedLengthPosition * this.length();
  2846. var previousOffset = 0;
  2847. for (var i = 0; i < this._points.length; i++) {
  2848. var j = (i + 1) % this._points.length;
  2849. var a = this._points[i];
  2850. var b = this._points[j];
  2851. var bToA = b.subtract(a);
  2852. var nextOffset = (bToA.length() + previousOffset);
  2853. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2854. var dir = bToA.normalize();
  2855. var localOffset = lengthPosition - previousOffset;
  2856. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2857. }
  2858. previousOffset = nextOffset;
  2859. }
  2860. //Tools.Error("internal error");
  2861. return Vector2.Zero();
  2862. };
  2863. Path2.StartingAt = function (x, y) {
  2864. return new Path2(x, y);
  2865. };
  2866. return Path2;
  2867. }());
  2868. BABYLON.Path2 = Path2;
  2869. var Path3D = (function () {
  2870. /**
  2871. * new Path3D(path, normal, raw)
  2872. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2873. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2874. * path : an array of Vector3, the curve axis of the Path3D
  2875. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2876. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2877. */
  2878. function Path3D(path, firstNormal, raw) {
  2879. this.path = path;
  2880. this._curve = new Array();
  2881. this._distances = new Array();
  2882. this._tangents = new Array();
  2883. this._normals = new Array();
  2884. this._binormals = new Array();
  2885. for (var p = 0; p < path.length; p++) {
  2886. this._curve[p] = path[p].clone(); // hard copy
  2887. }
  2888. this._raw = raw || false;
  2889. this._compute(firstNormal);
  2890. }
  2891. /**
  2892. * Returns the Path3D array of successive Vector3 designing its curve.
  2893. */
  2894. Path3D.prototype.getCurve = function () {
  2895. return this._curve;
  2896. };
  2897. /**
  2898. * Returns an array populated with tangent vectors on each Path3D curve point.
  2899. */
  2900. Path3D.prototype.getTangents = function () {
  2901. return this._tangents;
  2902. };
  2903. /**
  2904. * Returns an array populated with normal vectors on each Path3D curve point.
  2905. */
  2906. Path3D.prototype.getNormals = function () {
  2907. return this._normals;
  2908. };
  2909. /**
  2910. * Returns an array populated with binormal vectors on each Path3D curve point.
  2911. */
  2912. Path3D.prototype.getBinormals = function () {
  2913. return this._binormals;
  2914. };
  2915. /**
  2916. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2917. */
  2918. Path3D.prototype.getDistances = function () {
  2919. return this._distances;
  2920. };
  2921. /**
  2922. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2923. * Returns the same object updated.
  2924. */
  2925. Path3D.prototype.update = function (path, firstNormal) {
  2926. for (var p = 0; p < path.length; p++) {
  2927. this._curve[p].x = path[p].x;
  2928. this._curve[p].y = path[p].y;
  2929. this._curve[p].z = path[p].z;
  2930. }
  2931. this._compute(firstNormal);
  2932. return this;
  2933. };
  2934. // private function compute() : computes tangents, normals and binormals
  2935. Path3D.prototype._compute = function (firstNormal) {
  2936. var l = this._curve.length;
  2937. // first and last tangents
  2938. this._tangents[0] = this._getFirstNonNullVector(0);
  2939. if (!this._raw) {
  2940. this._tangents[0].normalize();
  2941. }
  2942. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2943. if (!this._raw) {
  2944. this._tangents[l - 1].normalize();
  2945. }
  2946. // normals and binormals at first point : arbitrary vector with _normalVector()
  2947. var tg0 = this._tangents[0];
  2948. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2949. this._normals[0] = pp0;
  2950. if (!this._raw) {
  2951. this._normals[0].normalize();
  2952. }
  2953. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2954. if (!this._raw) {
  2955. this._binormals[0].normalize();
  2956. }
  2957. this._distances[0] = 0.0;
  2958. // normals and binormals : next points
  2959. var prev; // previous vector (segment)
  2960. var cur; // current vector (segment)
  2961. var curTang; // current tangent
  2962. // previous normal
  2963. var prevBinor; // previous binormal
  2964. for (var i = 1; i < l; i++) {
  2965. // tangents
  2966. prev = this._getLastNonNullVector(i);
  2967. if (i < l - 1) {
  2968. cur = this._getFirstNonNullVector(i);
  2969. this._tangents[i] = prev.add(cur);
  2970. this._tangents[i].normalize();
  2971. }
  2972. this._distances[i] = this._distances[i - 1] + prev.length();
  2973. // normals and binormals
  2974. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2975. curTang = this._tangents[i];
  2976. prevBinor = this._binormals[i - 1];
  2977. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2978. if (!this._raw) {
  2979. this._normals[i].normalize();
  2980. }
  2981. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2982. if (!this._raw) {
  2983. this._binormals[i].normalize();
  2984. }
  2985. }
  2986. };
  2987. // private function getFirstNonNullVector(index)
  2988. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2989. Path3D.prototype._getFirstNonNullVector = function (index) {
  2990. var i = 1;
  2991. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2992. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2993. i++;
  2994. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2995. }
  2996. return nNVector;
  2997. };
  2998. // private function getLastNonNullVector(index)
  2999. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  3000. Path3D.prototype._getLastNonNullVector = function (index) {
  3001. var i = 1;
  3002. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  3003. while (nLVector.length() === 0 && index > i + 1) {
  3004. i++;
  3005. nLVector = this._curve[index].subtract(this._curve[index - i]);
  3006. }
  3007. return nLVector;
  3008. };
  3009. // private function normalVector(v0, vt, va) :
  3010. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  3011. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  3012. Path3D.prototype._normalVector = function (v0, vt, va) {
  3013. var normal0;
  3014. var tgl = vt.length();
  3015. if (tgl === 0.0) {
  3016. tgl = 1.0;
  3017. }
  3018. if (va === undefined || va === null) {
  3019. var point;
  3020. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  3021. point = new Vector3(0.0, -1.0, 0.0);
  3022. }
  3023. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  3024. point = new Vector3(1.0, 0.0, 0.0);
  3025. }
  3026. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  3027. point = new Vector3(0.0, 0.0, 1.0);
  3028. }
  3029. normal0 = Vector3.Cross(vt, point);
  3030. }
  3031. else {
  3032. normal0 = Vector3.Cross(vt, va);
  3033. Vector3.CrossToRef(normal0, vt, normal0);
  3034. }
  3035. normal0.normalize();
  3036. return normal0;
  3037. };
  3038. return Path3D;
  3039. }());
  3040. BABYLON.Path3D = Path3D;
  3041. var Curve3 = (function () {
  3042. /**
  3043. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  3044. * A Curve3 is designed from a series of successive Vector3.
  3045. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  3046. */
  3047. function Curve3(points) {
  3048. this._length = 0.0;
  3049. this._points = points;
  3050. this._length = this._computeLength(points);
  3051. }
  3052. /**
  3053. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  3054. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  3055. * @param v1 (Vector3) the control point
  3056. * @param v2 (Vector3) the end point of the Quadratic Bezier
  3057. * @param nbPoints (integer) the wanted number of points in the curve
  3058. */
  3059. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  3060. nbPoints = nbPoints > 2 ? nbPoints : 3;
  3061. var bez = new Array();
  3062. var equation = function (t, val0, val1, val2) {
  3063. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  3064. return res;
  3065. };
  3066. for (var i = 0; i <= nbPoints; i++) {
  3067. 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)));
  3068. }
  3069. return new Curve3(bez);
  3070. };
  3071. /**
  3072. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  3073. * @param v0 (Vector3) the origin point of the Cubic Bezier
  3074. * @param v1 (Vector3) the first control point
  3075. * @param v2 (Vector3) the second control point
  3076. * @param v3 (Vector3) the end point of the Cubic Bezier
  3077. * @param nbPoints (integer) the wanted number of points in the curve
  3078. */
  3079. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3080. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3081. var bez = new Array();
  3082. var equation = function (t, val0, val1, val2, val3) {
  3083. 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;
  3084. return res;
  3085. };
  3086. for (var i = 0; i <= nbPoints; i++) {
  3087. 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)));
  3088. }
  3089. return new Curve3(bez);
  3090. };
  3091. /**
  3092. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  3093. * @param p1 (Vector3) the origin point of the Hermite Spline
  3094. * @param t1 (Vector3) the tangent vector at the origin point
  3095. * @param p2 (Vector3) the end point of the Hermite Spline
  3096. * @param t2 (Vector3) the tangent vector at the end point
  3097. * @param nbPoints (integer) the wanted number of points in the curve
  3098. */
  3099. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3100. var hermite = new Array();
  3101. var step = 1.0 / nbPoints;
  3102. for (var i = 0; i <= nbPoints; i++) {
  3103. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3104. }
  3105. return new Curve3(hermite);
  3106. };
  3107. /**
  3108. * Returns the Curve3 stored array of successive Vector3
  3109. */
  3110. Curve3.prototype.getPoints = function () {
  3111. return this._points;
  3112. };
  3113. /**
  3114. * Returns the computed length (float) of the curve.
  3115. */
  3116. Curve3.prototype.length = function () {
  3117. return this._length;
  3118. };
  3119. /**
  3120. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3121. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3122. * curveA and curveB keep unchanged.
  3123. */
  3124. Curve3.prototype.continue = function (curve) {
  3125. var lastPoint = this._points[this._points.length - 1];
  3126. var continuedPoints = this._points.slice();
  3127. var curvePoints = curve.getPoints();
  3128. for (var i = 1; i < curvePoints.length; i++) {
  3129. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3130. }
  3131. var continuedCurve = new Curve3(continuedPoints);
  3132. return continuedCurve;
  3133. };
  3134. Curve3.prototype._computeLength = function (path) {
  3135. var l = 0;
  3136. for (var i = 1; i < path.length; i++) {
  3137. l += (path[i].subtract(path[i - 1])).length();
  3138. }
  3139. return l;
  3140. };
  3141. return Curve3;
  3142. }());
  3143. BABYLON.Curve3 = Curve3;
  3144. // SphericalHarmonics
  3145. var SphericalHarmonics = (function () {
  3146. function SphericalHarmonics() {
  3147. this.L00 = Vector3.Zero();
  3148. this.L1_1 = Vector3.Zero();
  3149. this.L10 = Vector3.Zero();
  3150. this.L11 = Vector3.Zero();
  3151. this.L2_2 = Vector3.Zero();
  3152. this.L2_1 = Vector3.Zero();
  3153. this.L20 = Vector3.Zero();
  3154. this.L21 = Vector3.Zero();
  3155. this.L22 = Vector3.Zero();
  3156. }
  3157. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3158. var colorVector = new Vector3(color.r, color.g, color.b);
  3159. var c = colorVector.scale(deltaSolidAngle);
  3160. this.L00 = this.L00.add(c.scale(0.282095));
  3161. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3162. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3163. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3164. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3165. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3166. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3167. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3168. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3169. };
  3170. SphericalHarmonics.prototype.scale = function (scale) {
  3171. this.L00 = this.L00.scale(scale);
  3172. this.L1_1 = this.L1_1.scale(scale);
  3173. this.L10 = this.L10.scale(scale);
  3174. this.L11 = this.L11.scale(scale);
  3175. this.L2_2 = this.L2_2.scale(scale);
  3176. this.L2_1 = this.L2_1.scale(scale);
  3177. this.L20 = this.L20.scale(scale);
  3178. this.L21 = this.L21.scale(scale);
  3179. this.L22 = this.L22.scale(scale);
  3180. };
  3181. return SphericalHarmonics;
  3182. }());
  3183. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3184. // SphericalPolynomial
  3185. var SphericalPolynomial = (function () {
  3186. function SphericalPolynomial() {
  3187. this.x = Vector3.Zero();
  3188. this.y = Vector3.Zero();
  3189. this.z = Vector3.Zero();
  3190. this.xx = Vector3.Zero();
  3191. this.yy = Vector3.Zero();
  3192. this.zz = Vector3.Zero();
  3193. this.xy = Vector3.Zero();
  3194. this.yz = Vector3.Zero();
  3195. this.zx = Vector3.Zero();
  3196. }
  3197. SphericalPolynomial.prototype.addAmbient = function (color) {
  3198. var colorVector = new Vector3(color.r, color.g, color.b);
  3199. this.xx = this.xx.add(colorVector);
  3200. this.yy = this.yy.add(colorVector);
  3201. this.zz = this.zz.add(colorVector);
  3202. };
  3203. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3204. var result = new SphericalPolynomial();
  3205. result.x = harmonics.L11.scale(1.02333);
  3206. result.y = harmonics.L1_1.scale(1.02333);
  3207. result.z = harmonics.L10.scale(1.02333);
  3208. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3209. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3210. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3211. result.yz = harmonics.L2_1.scale(0.858086);
  3212. result.zx = harmonics.L21.scale(0.858086);
  3213. result.xy = harmonics.L2_2.scale(0.858086);
  3214. return result;
  3215. };
  3216. return SphericalPolynomial;
  3217. }());
  3218. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3219. // Vertex formats
  3220. var PositionNormalVertex = (function () {
  3221. function PositionNormalVertex(position, normal) {
  3222. if (position === void 0) { position = Vector3.Zero(); }
  3223. if (normal === void 0) { normal = Vector3.Up(); }
  3224. this.position = position;
  3225. this.normal = normal;
  3226. }
  3227. PositionNormalVertex.prototype.clone = function () {
  3228. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3229. };
  3230. return PositionNormalVertex;
  3231. }());
  3232. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3233. var PositionNormalTextureVertex = (function () {
  3234. function PositionNormalTextureVertex(position, normal, uv) {
  3235. if (position === void 0) { position = Vector3.Zero(); }
  3236. if (normal === void 0) { normal = Vector3.Up(); }
  3237. if (uv === void 0) { uv = Vector2.Zero(); }
  3238. this.position = position;
  3239. this.normal = normal;
  3240. this.uv = uv;
  3241. }
  3242. PositionNormalTextureVertex.prototype.clone = function () {
  3243. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3244. };
  3245. return PositionNormalTextureVertex;
  3246. }());
  3247. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3248. // Temporary pre-allocated objects for engine internal use
  3249. // usage in any internal function :
  3250. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3251. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3252. var Tmp = (function () {
  3253. function Tmp() {
  3254. }
  3255. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3256. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3257. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3258. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3259. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3260. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3261. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3262. Matrix.Zero(), Matrix.Zero(),
  3263. Matrix.Zero(), Matrix.Zero(),
  3264. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3265. return Tmp;
  3266. }());
  3267. BABYLON.Tmp = Tmp;
  3268. })(BABYLON || (BABYLON = {}));
  3269. var BABYLON;
  3270. (function (BABYLON) {
  3271. function generateSerializableMember(type, sourceName) {
  3272. return function (target, propertyKey) {
  3273. if (!target.__serializableMembers) {
  3274. target.__serializableMembers = {};
  3275. }
  3276. if (!target.__serializableMembers[propertyKey]) {
  3277. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3278. }
  3279. };
  3280. }
  3281. function serialize(sourceName) {
  3282. return generateSerializableMember(0, sourceName); // value member
  3283. }
  3284. BABYLON.serialize = serialize;
  3285. function serializeAsTexture(sourceName) {
  3286. return generateSerializableMember(1, sourceName); // texture member
  3287. }
  3288. BABYLON.serializeAsTexture = serializeAsTexture;
  3289. function serializeAsColor3(sourceName) {
  3290. return generateSerializableMember(2, sourceName); // color3 member
  3291. }
  3292. BABYLON.serializeAsColor3 = serializeAsColor3;
  3293. function serializeAsFresnelParameters(sourceName) {
  3294. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3295. }
  3296. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3297. function serializeAsVector2(sourceName) {
  3298. return generateSerializableMember(4, sourceName); // vector2 member
  3299. }
  3300. BABYLON.serializeAsVector2 = serializeAsVector2;
  3301. function serializeAsVector3(sourceName) {
  3302. return generateSerializableMember(5, sourceName); // vector3 member
  3303. }
  3304. BABYLON.serializeAsVector3 = serializeAsVector3;
  3305. function serializeAsMeshReference(sourceName) {
  3306. return generateSerializableMember(6, sourceName); // mesh reference member
  3307. }
  3308. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3309. function serializeAsColorCurves(sourceName) {
  3310. return generateSerializableMember(7, sourceName); // color curves
  3311. }
  3312. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3313. var SerializationHelper = (function () {
  3314. function SerializationHelper() {
  3315. }
  3316. SerializationHelper.Serialize = function (entity, serializationObject) {
  3317. if (!serializationObject) {
  3318. serializationObject = {};
  3319. }
  3320. // Tags
  3321. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3322. // Properties
  3323. for (var property in entity.__serializableMembers) {
  3324. var propertyDescriptor = entity.__serializableMembers[property];
  3325. var targetPropertyName = propertyDescriptor.sourceName || property;
  3326. var propertyType = propertyDescriptor.type;
  3327. var sourceProperty = entity[property];
  3328. if (sourceProperty !== undefined && sourceProperty !== null) {
  3329. switch (propertyType) {
  3330. case 0:
  3331. serializationObject[targetPropertyName] = sourceProperty;
  3332. break;
  3333. case 1:
  3334. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3335. break;
  3336. case 2:
  3337. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3338. break;
  3339. case 3:
  3340. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3341. break;
  3342. case 4:
  3343. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3344. break;
  3345. case 5:
  3346. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3347. break;
  3348. case 6:
  3349. serializationObject[targetPropertyName] = sourceProperty.id;
  3350. break;
  3351. case 7:
  3352. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3353. break;
  3354. }
  3355. }
  3356. }
  3357. return serializationObject;
  3358. };
  3359. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3360. var destination = creationFunction();
  3361. // Tags
  3362. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3363. // Properties
  3364. for (var property in destination.__serializableMembers) {
  3365. var propertyDescriptor = destination.__serializableMembers[property];
  3366. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3367. var propertyType = propertyDescriptor.type;
  3368. if (sourceProperty !== undefined && sourceProperty !== null) {
  3369. switch (propertyType) {
  3370. case 0:
  3371. destination[property] = sourceProperty;
  3372. break;
  3373. case 1:
  3374. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3375. break;
  3376. case 2:
  3377. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3378. break;
  3379. case 3:
  3380. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3381. break;
  3382. case 4:
  3383. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3384. break;
  3385. case 5:
  3386. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3387. break;
  3388. case 6:
  3389. destination[property] = scene.getLastMeshByID(sourceProperty);
  3390. break;
  3391. case 7:
  3392. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3393. break;
  3394. }
  3395. }
  3396. }
  3397. return destination;
  3398. };
  3399. SerializationHelper.Clone = function (creationFunction, source) {
  3400. var destination = creationFunction();
  3401. // Tags
  3402. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3403. // Properties
  3404. for (var property in destination.__serializableMembers) {
  3405. var propertyDescriptor = destination.__serializableMembers[property];
  3406. var sourceProperty = source[property];
  3407. var propertyType = propertyDescriptor.type;
  3408. if (sourceProperty !== undefined && sourceProperty !== null) {
  3409. switch (propertyType) {
  3410. case 0: // Value
  3411. case 6:
  3412. destination[property] = sourceProperty;
  3413. break;
  3414. case 1: // Texture
  3415. case 2: // Color3
  3416. case 3: // FresnelParameters
  3417. case 4: // Vector2
  3418. case 5: // Vector3
  3419. case 7:
  3420. destination[property] = sourceProperty.clone();
  3421. break;
  3422. }
  3423. }
  3424. }
  3425. return destination;
  3426. };
  3427. return SerializationHelper;
  3428. }());
  3429. BABYLON.SerializationHelper = SerializationHelper;
  3430. })(BABYLON || (BABYLON = {}));
  3431. var BABYLON;
  3432. (function (BABYLON) {
  3433. /**
  3434. * A class serves as a medium between the observable and its observers
  3435. */
  3436. var EventState = (function () {
  3437. /**
  3438. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3439. */
  3440. function EventState(mask, skipNextObservers) {
  3441. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3442. this.initalize(mask, skipNextObservers);
  3443. }
  3444. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3445. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3446. this.mask = mask;
  3447. this.skipNextObservers = skipNextObservers;
  3448. return this;
  3449. };
  3450. return EventState;
  3451. }());
  3452. BABYLON.EventState = EventState;
  3453. /**
  3454. * Represent an Observer registered to a given Observable object.
  3455. */
  3456. var Observer = (function () {
  3457. function Observer(callback, mask) {
  3458. this.callback = callback;
  3459. this.mask = mask;
  3460. }
  3461. return Observer;
  3462. }());
  3463. BABYLON.Observer = Observer;
  3464. /**
  3465. * The Observable class is a simple implementation of the Observable pattern.
  3466. * 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.
  3467. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3468. * 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).
  3469. * 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.
  3470. */
  3471. var Observable = (function () {
  3472. function Observable() {
  3473. this._observers = new Array();
  3474. this._eventState = new EventState(0);
  3475. }
  3476. /**
  3477. * Create a new Observer with the specified callback
  3478. * @param callback the callback that will be executed for that Observer
  3479. * @param mask the mask used to filter observers
  3480. * @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.
  3481. */
  3482. Observable.prototype.add = function (callback, mask, insertFirst) {
  3483. if (mask === void 0) { mask = -1; }
  3484. if (insertFirst === void 0) { insertFirst = false; }
  3485. if (!callback) {
  3486. return null;
  3487. }
  3488. var observer = new Observer(callback, mask);
  3489. if (insertFirst) {
  3490. this._observers.unshift(observer);
  3491. }
  3492. else {
  3493. this._observers.push(observer);
  3494. }
  3495. return observer;
  3496. };
  3497. /**
  3498. * Remove an Observer from the Observable object
  3499. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3500. */
  3501. Observable.prototype.remove = function (observer) {
  3502. var index = this._observers.indexOf(observer);
  3503. if (index !== -1) {
  3504. this._observers.splice(index, 1);
  3505. return true;
  3506. }
  3507. return false;
  3508. };
  3509. /**
  3510. * Remove a callback from the Observable object
  3511. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3512. */
  3513. Observable.prototype.removeCallback = function (callback) {
  3514. for (var index = 0; index < this._observers.length; index++) {
  3515. if (this._observers[index].callback === callback) {
  3516. this._observers.splice(index, 1);
  3517. return true;
  3518. }
  3519. }
  3520. return false;
  3521. };
  3522. /**
  3523. * Notify all Observers by calling their respective callback with the given data
  3524. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  3525. * @param eventData
  3526. * @param mask
  3527. */
  3528. Observable.prototype.notifyObservers = function (eventData, mask) {
  3529. if (mask === void 0) { mask = -1; }
  3530. var state = this._eventState;
  3531. state.mask = mask;
  3532. state.skipNextObservers = false;
  3533. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3534. var obs = _a[_i];
  3535. if (obs.mask & mask) {
  3536. obs.callback(eventData, state);
  3537. }
  3538. if (state.skipNextObservers) {
  3539. return false;
  3540. }
  3541. }
  3542. return true;
  3543. };
  3544. /**
  3545. * return true is the Observable has at least one Observer registered
  3546. */
  3547. Observable.prototype.hasObservers = function () {
  3548. return this._observers.length > 0;
  3549. };
  3550. /**
  3551. * Clear the list of observers
  3552. */
  3553. Observable.prototype.clear = function () {
  3554. this._observers = new Array();
  3555. };
  3556. /**
  3557. * Clone the current observable
  3558. */
  3559. Observable.prototype.clone = function () {
  3560. var result = new Observable();
  3561. result._observers = this._observers.slice(0);
  3562. return result;
  3563. };
  3564. return Observable;
  3565. }());
  3566. BABYLON.Observable = Observable;
  3567. })(BABYLON || (BABYLON = {}));
  3568. var BABYLON;
  3569. (function (BABYLON) {
  3570. var Database = (function () {
  3571. function Database(urlToScene, callbackManifestChecked) {
  3572. // Handling various flavors of prefixed version of IndexedDB
  3573. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3574. this.callbackManifestChecked = callbackManifestChecked;
  3575. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3576. this.db = null;
  3577. this.enableSceneOffline = false;
  3578. this.enableTexturesOffline = false;
  3579. this.manifestVersionFound = 0;
  3580. this.mustUpdateRessources = false;
  3581. this.hasReachedQuota = false;
  3582. if (!Database.IDBStorageEnabled) {
  3583. this.callbackManifestChecked(true);
  3584. }
  3585. else {
  3586. this.checkManifestFile();
  3587. }
  3588. }
  3589. Database.prototype.checkManifestFile = function () {
  3590. var _this = this;
  3591. function noManifestFile() {
  3592. that.enableSceneOffline = false;
  3593. that.enableTexturesOffline = false;
  3594. that.callbackManifestChecked(false);
  3595. }
  3596. var that = this;
  3597. var timeStampUsed = false;
  3598. var manifestURL = this.currentSceneUrl + ".manifest";
  3599. var xhr = new XMLHttpRequest();
  3600. if (navigator.onLine) {
  3601. // Adding a timestamp to by-pass browsers' cache
  3602. timeStampUsed = true;
  3603. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3604. }
  3605. xhr.open("GET", manifestURL, true);
  3606. xhr.addEventListener("load", function () {
  3607. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3608. try {
  3609. var manifestFile = JSON.parse(xhr.response);
  3610. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3611. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3612. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3613. _this.manifestVersionFound = manifestFile.version;
  3614. }
  3615. if (_this.callbackManifestChecked) {
  3616. _this.callbackManifestChecked(true);
  3617. }
  3618. }
  3619. catch (ex) {
  3620. noManifestFile();
  3621. }
  3622. }
  3623. else {
  3624. noManifestFile();
  3625. }
  3626. }, false);
  3627. xhr.addEventListener("error", function (event) {
  3628. if (timeStampUsed) {
  3629. timeStampUsed = false;
  3630. // Let's retry without the timeStamp
  3631. // It could fail when coupled with HTML5 Offline API
  3632. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3633. xhr.open("GET", retryManifestURL, true);
  3634. xhr.send();
  3635. }
  3636. else {
  3637. noManifestFile();
  3638. }
  3639. }, false);
  3640. try {
  3641. xhr.send();
  3642. }
  3643. catch (ex) {
  3644. BABYLON.Tools.Error("Error on XHR send request.");
  3645. that.callbackManifestChecked(false);
  3646. }
  3647. };
  3648. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3649. var _this = this;
  3650. function handleError() {
  3651. that.isSupported = false;
  3652. if (errorCallback)
  3653. errorCallback();
  3654. }
  3655. var that = this;
  3656. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3657. // Your browser doesn't support IndexedDB
  3658. this.isSupported = false;
  3659. if (errorCallback)
  3660. errorCallback();
  3661. }
  3662. else {
  3663. // If the DB hasn't been opened or created yet
  3664. if (!this.db) {
  3665. this.hasReachedQuota = false;
  3666. this.isSupported = true;
  3667. var request = this.idbFactory.open("babylonjs", 1);
  3668. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3669. request.onerror = function (event) {
  3670. handleError();
  3671. };
  3672. // executes when a version change transaction cannot complete due to other active transactions
  3673. request.onblocked = function (event) {
  3674. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3675. handleError();
  3676. };
  3677. // DB has been opened successfully
  3678. request.onsuccess = function (event) {
  3679. _this.db = request.result;
  3680. successCallback();
  3681. };
  3682. // Initialization of the DB. Creating Scenes & Textures stores
  3683. request.onupgradeneeded = function (event) {
  3684. _this.db = (event.target).result;
  3685. try {
  3686. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3687. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3688. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3689. }
  3690. catch (ex) {
  3691. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3692. handleError();
  3693. }
  3694. };
  3695. }
  3696. else {
  3697. if (successCallback)
  3698. successCallback();
  3699. }
  3700. }
  3701. };
  3702. Database.prototype.loadImageFromDB = function (url, image) {
  3703. var _this = this;
  3704. var completeURL = Database.ReturnFullUrlLocation(url);
  3705. var saveAndLoadImage = function () {
  3706. if (!_this.hasReachedQuota && _this.db !== null) {
  3707. // the texture is not yet in the DB, let's try to save it
  3708. _this._saveImageIntoDBAsync(completeURL, image);
  3709. }
  3710. else {
  3711. image.src = url;
  3712. }
  3713. };
  3714. if (!this.mustUpdateRessources) {
  3715. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3716. }
  3717. else {
  3718. saveAndLoadImage();
  3719. }
  3720. };
  3721. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3722. if (this.isSupported && this.db !== null) {
  3723. var texture;
  3724. var transaction = this.db.transaction(["textures"]);
  3725. transaction.onabort = function (event) {
  3726. image.src = url;
  3727. };
  3728. transaction.oncomplete = function (event) {
  3729. var blobTextureURL;
  3730. if (texture) {
  3731. var URL = window.URL || window.webkitURL;
  3732. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3733. image.onerror = function () {
  3734. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3735. image.src = url;
  3736. };
  3737. image.src = blobTextureURL;
  3738. }
  3739. else {
  3740. notInDBCallback();
  3741. }
  3742. };
  3743. var getRequest = transaction.objectStore("textures").get(url);
  3744. getRequest.onsuccess = function (event) {
  3745. texture = (event.target).result;
  3746. };
  3747. getRequest.onerror = function (event) {
  3748. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3749. image.src = url;
  3750. };
  3751. }
  3752. else {
  3753. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3754. image.src = url;
  3755. }
  3756. };
  3757. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3758. var _this = this;
  3759. if (this.isSupported) {
  3760. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3761. var generateBlobUrl = function () {
  3762. var blobTextureURL;
  3763. if (blob) {
  3764. var URL = window.URL || window.webkitURL;
  3765. try {
  3766. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3767. }
  3768. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3769. catch (ex) {
  3770. blobTextureURL = URL.createObjectURL(blob);
  3771. }
  3772. }
  3773. image.src = blobTextureURL;
  3774. };
  3775. if (Database.IsUASupportingBlobStorage) {
  3776. var xhr = new XMLHttpRequest(), blob;
  3777. xhr.open("GET", url, true);
  3778. xhr.responseType = "blob";
  3779. xhr.addEventListener("load", function () {
  3780. if (xhr.status === 200) {
  3781. // Blob as response (XHR2)
  3782. blob = xhr.response;
  3783. var transaction = _this.db.transaction(["textures"], "readwrite");
  3784. // the transaction could abort because of a QuotaExceededError error
  3785. transaction.onabort = function (event) {
  3786. try {
  3787. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3788. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3789. _this.hasReachedQuota = true;
  3790. }
  3791. }
  3792. catch (ex) { }
  3793. generateBlobUrl();
  3794. };
  3795. transaction.oncomplete = function (event) {
  3796. generateBlobUrl();
  3797. };
  3798. var newTexture = { textureUrl: url, data: blob };
  3799. try {
  3800. // Put the blob into the dabase
  3801. var addRequest = transaction.objectStore("textures").put(newTexture);
  3802. addRequest.onsuccess = function (event) {
  3803. };
  3804. addRequest.onerror = function (event) {
  3805. generateBlobUrl();
  3806. };
  3807. }
  3808. catch (ex) {
  3809. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3810. if (ex.code === 25) {
  3811. Database.IsUASupportingBlobStorage = false;
  3812. }
  3813. image.src = url;
  3814. }
  3815. }
  3816. else {
  3817. image.src = url;
  3818. }
  3819. }, false);
  3820. xhr.addEventListener("error", function (event) {
  3821. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3822. image.src = url;
  3823. }, false);
  3824. xhr.send();
  3825. }
  3826. else {
  3827. image.src = url;
  3828. }
  3829. }
  3830. else {
  3831. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3832. image.src = url;
  3833. }
  3834. };
  3835. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3836. var _this = this;
  3837. var updateVersion = function (event) {
  3838. // the version is not yet in the DB or we need to update it
  3839. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3840. };
  3841. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3842. };
  3843. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3844. var _this = this;
  3845. if (this.isSupported) {
  3846. var version;
  3847. try {
  3848. var transaction = this.db.transaction(["versions"]);
  3849. transaction.oncomplete = function (event) {
  3850. if (version) {
  3851. // If the version in the JSON file is > than the version in DB
  3852. if (_this.manifestVersionFound > version.data) {
  3853. _this.mustUpdateRessources = true;
  3854. updateInDBCallback();
  3855. }
  3856. else {
  3857. callback(version.data);
  3858. }
  3859. }
  3860. else {
  3861. _this.mustUpdateRessources = true;
  3862. updateInDBCallback();
  3863. }
  3864. };
  3865. transaction.onabort = function (event) {
  3866. callback(-1);
  3867. };
  3868. var getRequest = transaction.objectStore("versions").get(url);
  3869. getRequest.onsuccess = function (event) {
  3870. version = (event.target).result;
  3871. };
  3872. getRequest.onerror = function (event) {
  3873. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3874. callback(-1);
  3875. };
  3876. }
  3877. catch (ex) {
  3878. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3879. callback(-1);
  3880. }
  3881. }
  3882. else {
  3883. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3884. callback(-1);
  3885. }
  3886. };
  3887. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3888. var _this = this;
  3889. if (this.isSupported && !this.hasReachedQuota) {
  3890. try {
  3891. // Open a transaction to the database
  3892. var transaction = this.db.transaction(["versions"], "readwrite");
  3893. // the transaction could abort because of a QuotaExceededError error
  3894. transaction.onabort = function (event) {
  3895. try {
  3896. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3897. _this.hasReachedQuota = true;
  3898. }
  3899. }
  3900. catch (ex) { }
  3901. callback(-1);
  3902. };
  3903. transaction.oncomplete = function (event) {
  3904. callback(_this.manifestVersionFound);
  3905. };
  3906. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3907. // Put the scene into the database
  3908. var addRequest = transaction.objectStore("versions").put(newVersion);
  3909. addRequest.onsuccess = function (event) {
  3910. };
  3911. addRequest.onerror = function (event) {
  3912. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3913. };
  3914. }
  3915. catch (ex) {
  3916. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3917. callback(-1);
  3918. }
  3919. }
  3920. else {
  3921. callback(-1);
  3922. }
  3923. };
  3924. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3925. var _this = this;
  3926. var completeUrl = Database.ReturnFullUrlLocation(url);
  3927. var saveAndLoadFile = function (event) {
  3928. // the scene is not yet in the DB, let's try to save it
  3929. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3930. };
  3931. this._checkVersionFromDB(completeUrl, function (version) {
  3932. if (version !== -1) {
  3933. if (!_this.mustUpdateRessources) {
  3934. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3935. }
  3936. else {
  3937. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3938. }
  3939. }
  3940. else {
  3941. errorCallback();
  3942. }
  3943. });
  3944. };
  3945. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3946. if (this.isSupported) {
  3947. var targetStore;
  3948. if (url.indexOf(".babylon") !== -1) {
  3949. targetStore = "scenes";
  3950. }
  3951. else {
  3952. targetStore = "textures";
  3953. }
  3954. var file;
  3955. var transaction = this.db.transaction([targetStore]);
  3956. transaction.oncomplete = function (event) {
  3957. if (file) {
  3958. callback(file.data);
  3959. }
  3960. else {
  3961. notInDBCallback();
  3962. }
  3963. };
  3964. transaction.onabort = function (event) {
  3965. notInDBCallback();
  3966. };
  3967. var getRequest = transaction.objectStore(targetStore).get(url);
  3968. getRequest.onsuccess = function (event) {
  3969. file = (event.target).result;
  3970. };
  3971. getRequest.onerror = function (event) {
  3972. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3973. notInDBCallback();
  3974. };
  3975. }
  3976. else {
  3977. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3978. callback();
  3979. }
  3980. };
  3981. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3982. var _this = this;
  3983. if (this.isSupported) {
  3984. var targetStore;
  3985. if (url.indexOf(".babylon") !== -1) {
  3986. targetStore = "scenes";
  3987. }
  3988. else {
  3989. targetStore = "textures";
  3990. }
  3991. // Create XHR
  3992. var xhr = new XMLHttpRequest(), fileData;
  3993. xhr.open("GET", url, true);
  3994. if (useArrayBuffer) {
  3995. xhr.responseType = "arraybuffer";
  3996. }
  3997. xhr.onprogress = progressCallback;
  3998. xhr.addEventListener("load", function () {
  3999. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  4000. // Blob as response (XHR2)
  4001. //fileData = xhr.responseText;
  4002. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  4003. if (!_this.hasReachedQuota) {
  4004. // Open a transaction to the database
  4005. var transaction = _this.db.transaction([targetStore], "readwrite");
  4006. // the transaction could abort because of a QuotaExceededError error
  4007. transaction.onabort = function (event) {
  4008. try {
  4009. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  4010. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  4011. _this.hasReachedQuota = true;
  4012. }
  4013. }
  4014. catch (ex) { }
  4015. callback(fileData);
  4016. };
  4017. transaction.oncomplete = function (event) {
  4018. callback(fileData);
  4019. };
  4020. var newFile;
  4021. if (targetStore === "scenes") {
  4022. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  4023. }
  4024. else {
  4025. newFile = { textureUrl: url, data: fileData };
  4026. }
  4027. try {
  4028. // Put the scene into the database
  4029. var addRequest = transaction.objectStore(targetStore).put(newFile);
  4030. addRequest.onsuccess = function (event) {
  4031. };
  4032. addRequest.onerror = function (event) {
  4033. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  4034. };
  4035. }
  4036. catch (ex) {
  4037. callback(fileData);
  4038. }
  4039. }
  4040. else {
  4041. callback(fileData);
  4042. }
  4043. }
  4044. else {
  4045. callback();
  4046. }
  4047. }, false);
  4048. xhr.addEventListener("error", function (event) {
  4049. BABYLON.Tools.Error("error on XHR request.");
  4050. callback();
  4051. }, false);
  4052. xhr.send();
  4053. }
  4054. else {
  4055. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4056. callback();
  4057. }
  4058. };
  4059. Database.IsUASupportingBlobStorage = true;
  4060. Database.IDBStorageEnabled = true;
  4061. Database.parseURL = function (url) {
  4062. var a = document.createElement('a');
  4063. a.href = url;
  4064. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  4065. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  4066. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  4067. return absLocation;
  4068. };
  4069. Database.ReturnFullUrlLocation = function (url) {
  4070. if (url.indexOf("http:/") === -1) {
  4071. return (Database.parseURL(window.location.href) + url);
  4072. }
  4073. else {
  4074. return url;
  4075. }
  4076. };
  4077. return Database;
  4078. }());
  4079. BABYLON.Database = Database;
  4080. })(BABYLON || (BABYLON = {}));
  4081. var BABYLON;
  4082. (function (BABYLON) {
  4083. var Internals;
  4084. (function (Internals) {
  4085. /*
  4086. * Based on jsTGALoader - Javascript loader for TGA file
  4087. * By Vincent Thibault
  4088. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  4089. */
  4090. var TGATools = (function () {
  4091. function TGATools() {
  4092. }
  4093. TGATools.GetTGAHeader = function (data) {
  4094. var offset = 0;
  4095. var header = {
  4096. id_length: data[offset++],
  4097. colormap_type: data[offset++],
  4098. image_type: data[offset++],
  4099. colormap_index: data[offset++] | data[offset++] << 8,
  4100. colormap_length: data[offset++] | data[offset++] << 8,
  4101. colormap_size: data[offset++],
  4102. origin: [
  4103. data[offset++] | data[offset++] << 8,
  4104. data[offset++] | data[offset++] << 8
  4105. ],
  4106. width: data[offset++] | data[offset++] << 8,
  4107. height: data[offset++] | data[offset++] << 8,
  4108. pixel_size: data[offset++],
  4109. flags: data[offset++]
  4110. };
  4111. return header;
  4112. };
  4113. TGATools.UploadContent = function (gl, data) {
  4114. // Not enough data to contain header ?
  4115. if (data.length < 19) {
  4116. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4117. return;
  4118. }
  4119. // Read Header
  4120. var offset = 18;
  4121. var header = TGATools.GetTGAHeader(data);
  4122. // Assume it's a valid Targa file.
  4123. if (header.id_length + offset > data.length) {
  4124. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4125. return;
  4126. }
  4127. // Skip not needed data
  4128. offset += header.id_length;
  4129. var use_rle = false;
  4130. var use_pal = false;
  4131. var use_rgb = false;
  4132. var use_grey = false;
  4133. // Get some informations.
  4134. switch (header.image_type) {
  4135. case TGATools._TYPE_RLE_INDEXED:
  4136. use_rle = true;
  4137. case TGATools._TYPE_INDEXED:
  4138. use_pal = true;
  4139. break;
  4140. case TGATools._TYPE_RLE_RGB:
  4141. use_rle = true;
  4142. case TGATools._TYPE_RGB:
  4143. use_rgb = true;
  4144. break;
  4145. case TGATools._TYPE_RLE_GREY:
  4146. use_rle = true;
  4147. case TGATools._TYPE_GREY:
  4148. use_grey = true;
  4149. break;
  4150. }
  4151. var pixel_data;
  4152. var numAlphaBits = header.flags & 0xf;
  4153. var pixel_size = header.pixel_size >> 3;
  4154. var pixel_total = header.width * header.height * pixel_size;
  4155. // Read palettes
  4156. var palettes;
  4157. if (use_pal) {
  4158. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4159. }
  4160. // Read LRE
  4161. if (use_rle) {
  4162. pixel_data = new Uint8Array(pixel_total);
  4163. var c, count, i;
  4164. var localOffset = 0;
  4165. var pixels = new Uint8Array(pixel_size);
  4166. while (offset < pixel_total && localOffset < pixel_total) {
  4167. c = data[offset++];
  4168. count = (c & 0x7f) + 1;
  4169. // RLE pixels
  4170. if (c & 0x80) {
  4171. // Bind pixel tmp array
  4172. for (i = 0; i < pixel_size; ++i) {
  4173. pixels[i] = data[offset++];
  4174. }
  4175. // Copy pixel array
  4176. for (i = 0; i < count; ++i) {
  4177. pixel_data.set(pixels, localOffset + i * pixel_size);
  4178. }
  4179. localOffset += pixel_size * count;
  4180. }
  4181. else {
  4182. count *= pixel_size;
  4183. for (i = 0; i < count; ++i) {
  4184. pixel_data[localOffset + i] = data[offset++];
  4185. }
  4186. localOffset += count;
  4187. }
  4188. }
  4189. }
  4190. else {
  4191. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4192. }
  4193. // Load to texture
  4194. var x_start, y_start, x_step, y_step, y_end, x_end;
  4195. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4196. default:
  4197. case TGATools._ORIGIN_UL:
  4198. x_start = 0;
  4199. x_step = 1;
  4200. x_end = header.width;
  4201. y_start = 0;
  4202. y_step = 1;
  4203. y_end = header.height;
  4204. break;
  4205. case TGATools._ORIGIN_BL:
  4206. x_start = 0;
  4207. x_step = 1;
  4208. x_end = header.width;
  4209. y_start = header.height - 1;
  4210. y_step = -1;
  4211. y_end = -1;
  4212. break;
  4213. case TGATools._ORIGIN_UR:
  4214. x_start = header.width - 1;
  4215. x_step = -1;
  4216. x_end = -1;
  4217. y_start = 0;
  4218. y_step = 1;
  4219. y_end = header.height;
  4220. break;
  4221. case TGATools._ORIGIN_BR:
  4222. x_start = header.width - 1;
  4223. x_step = -1;
  4224. x_end = -1;
  4225. y_start = header.height - 1;
  4226. y_step = -1;
  4227. y_end = -1;
  4228. break;
  4229. }
  4230. // Load the specify method
  4231. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4232. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4233. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4234. };
  4235. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4236. var image = pixel_data, colormap = palettes;
  4237. var width = header.width, height = header.height;
  4238. var color, i = 0, x, y;
  4239. var imageData = new Uint8Array(width * height * 4);
  4240. for (y = y_start; y !== y_end; y += y_step) {
  4241. for (x = x_start; x !== x_end; x += x_step, i++) {
  4242. color = image[i];
  4243. imageData[(x + width * y) * 4 + 3] = 255;
  4244. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4245. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4246. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4247. }
  4248. }
  4249. return imageData;
  4250. };
  4251. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4252. var image = pixel_data;
  4253. var width = header.width, height = header.height;
  4254. var color, i = 0, x, y;
  4255. var imageData = new Uint8Array(width * height * 4);
  4256. for (y = y_start; y !== y_end; y += y_step) {
  4257. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4258. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4259. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4260. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4261. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4262. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4263. }
  4264. }
  4265. return imageData;
  4266. };
  4267. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4268. var image = pixel_data;
  4269. var width = header.width, height = header.height;
  4270. var i = 0, x, y;
  4271. var imageData = new Uint8Array(width * height * 4);
  4272. for (y = y_start; y !== y_end; y += y_step) {
  4273. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4274. imageData[(x + width * y) * 4 + 3] = 255;
  4275. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4276. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4277. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4278. }
  4279. }
  4280. return imageData;
  4281. };
  4282. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4283. var image = pixel_data;
  4284. var width = header.width, height = header.height;
  4285. var i = 0, x, y;
  4286. var imageData = new Uint8Array(width * height * 4);
  4287. for (y = y_start; y !== y_end; y += y_step) {
  4288. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4289. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4290. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4291. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4292. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4293. }
  4294. }
  4295. return imageData;
  4296. };
  4297. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4298. var image = pixel_data;
  4299. var width = header.width, height = header.height;
  4300. var color, i = 0, x, y;
  4301. var imageData = new Uint8Array(width * height * 4);
  4302. for (y = y_start; y !== y_end; y += y_step) {
  4303. for (x = x_start; x !== x_end; x += x_step, i++) {
  4304. color = image[i];
  4305. imageData[(x + width * y) * 4 + 0] = color;
  4306. imageData[(x + width * y) * 4 + 1] = color;
  4307. imageData[(x + width * y) * 4 + 2] = color;
  4308. imageData[(x + width * y) * 4 + 3] = 255;
  4309. }
  4310. }
  4311. return imageData;
  4312. };
  4313. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4314. var image = pixel_data;
  4315. var width = header.width, height = header.height;
  4316. var i = 0, x, y;
  4317. var imageData = new Uint8Array(width * height * 4);
  4318. for (y = y_start; y !== y_end; y += y_step) {
  4319. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4320. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4321. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4322. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4323. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4324. }
  4325. }
  4326. return imageData;
  4327. };
  4328. TGATools._TYPE_NO_DATA = 0;
  4329. TGATools._TYPE_INDEXED = 1;
  4330. TGATools._TYPE_RGB = 2;
  4331. TGATools._TYPE_GREY = 3;
  4332. TGATools._TYPE_RLE_INDEXED = 9;
  4333. TGATools._TYPE_RLE_RGB = 10;
  4334. TGATools._TYPE_RLE_GREY = 11;
  4335. TGATools._ORIGIN_MASK = 0x30;
  4336. TGATools._ORIGIN_SHIFT = 0x04;
  4337. TGATools._ORIGIN_BL = 0x00;
  4338. TGATools._ORIGIN_BR = 0x01;
  4339. TGATools._ORIGIN_UL = 0x02;
  4340. TGATools._ORIGIN_UR = 0x03;
  4341. return TGATools;
  4342. }());
  4343. Internals.TGATools = TGATools;
  4344. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4345. })(BABYLON || (BABYLON = {}));
  4346. var BABYLON;
  4347. (function (BABYLON) {
  4348. var SmartArray = (function () {
  4349. function SmartArray(capacity) {
  4350. this.length = 0;
  4351. this._duplicateId = 0;
  4352. this.data = new Array(capacity);
  4353. this._id = SmartArray._GlobalId++;
  4354. }
  4355. SmartArray.prototype.push = function (value) {
  4356. this.data[this.length++] = value;
  4357. if (this.length > this.data.length) {
  4358. this.data.length *= 2;
  4359. }
  4360. if (!value.__smartArrayFlags) {
  4361. value.__smartArrayFlags = {};
  4362. }
  4363. value.__smartArrayFlags[this._id] = this._duplicateId;
  4364. };
  4365. SmartArray.prototype.pushNoDuplicate = function (value) {
  4366. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4367. return false;
  4368. }
  4369. this.push(value);
  4370. return true;
  4371. };
  4372. SmartArray.prototype.sort = function (compareFn) {
  4373. this.data.sort(compareFn);
  4374. };
  4375. SmartArray.prototype.reset = function () {
  4376. this.length = 0;
  4377. this._duplicateId++;
  4378. };
  4379. SmartArray.prototype.concat = function (array) {
  4380. if (array.length === 0) {
  4381. return;
  4382. }
  4383. if (this.length + array.length > this.data.length) {
  4384. this.data.length = (this.length + array.length) * 2;
  4385. }
  4386. for (var index = 0; index < array.length; index++) {
  4387. this.data[this.length++] = (array.data || array)[index];
  4388. }
  4389. };
  4390. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4391. if (array.length === 0) {
  4392. return;
  4393. }
  4394. if (this.length + array.length > this.data.length) {
  4395. this.data.length = (this.length + array.length) * 2;
  4396. }
  4397. for (var index = 0; index < array.length; index++) {
  4398. var item = (array.data || array)[index];
  4399. this.pushNoDuplicate(item);
  4400. }
  4401. };
  4402. SmartArray.prototype.indexOf = function (value) {
  4403. var position = this.data.indexOf(value);
  4404. if (position >= this.length) {
  4405. return -1;
  4406. }
  4407. return position;
  4408. };
  4409. // Statics
  4410. SmartArray._GlobalId = 0;
  4411. return SmartArray;
  4412. }());
  4413. BABYLON.SmartArray = SmartArray;
  4414. })(BABYLON || (BABYLON = {}));
  4415. var BABYLON;
  4416. (function (BABYLON) {
  4417. /**
  4418. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4419. * The underlying implementation relies on an associative array to ensure the best performances.
  4420. * The value can be anything including 'null' but except 'undefined'
  4421. */
  4422. var StringDictionary = (function () {
  4423. function StringDictionary() {
  4424. this._count = 0;
  4425. this._data = {};
  4426. }
  4427. /**
  4428. * This will clear this dictionary and copy the content from the 'source' one.
  4429. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  4430. * @param source the dictionary to take the content from and copy to this dictionary
  4431. */
  4432. StringDictionary.prototype.copyFrom = function (source) {
  4433. var _this = this;
  4434. this.clear();
  4435. source.forEach(function (t, v) { return _this.add(t, v); });
  4436. };
  4437. /**
  4438. * Get a value based from its key
  4439. * @param key the given key to get the matching value from
  4440. * @return the value if found, otherwise undefined is returned
  4441. */
  4442. StringDictionary.prototype.get = function (key) {
  4443. var val = this._data[key];
  4444. if (val !== undefined) {
  4445. return val;
  4446. }
  4447. return undefined;
  4448. };
  4449. /**
  4450. * Get a value from its key or add it if it doesn't exist.
  4451. * This method will ensure you that a given key/data will be present in the dictionary.
  4452. * @param key the given key to get the matching value from
  4453. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4454. * The factory will only be invoked if there's no data for the given key.
  4455. * @return the value corresponding to the key.
  4456. */
  4457. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4458. var val = this.get(key);
  4459. if (val !== undefined) {
  4460. return val;
  4461. }
  4462. val = factory(key);
  4463. if (val) {
  4464. this.add(key, val);
  4465. }
  4466. return val;
  4467. };
  4468. /**
  4469. * Get a value from its key if present in the dictionary otherwise add it
  4470. * @param key the key to get the value from
  4471. * @param val if there's no such key/value pair in the dictionary add it with this value
  4472. * @return the value corresponding to the key
  4473. */
  4474. StringDictionary.prototype.getOrAdd = function (key, val) {
  4475. var curVal = this.get(key);
  4476. if (curVal !== undefined) {
  4477. return curVal;
  4478. }
  4479. this.add(key, val);
  4480. return val;
  4481. };
  4482. /**
  4483. * Check if there's a given key in the dictionary
  4484. * @param key the key to check for
  4485. * @return true if the key is present, false otherwise
  4486. */
  4487. StringDictionary.prototype.contains = function (key) {
  4488. return this._data[key] !== undefined;
  4489. };
  4490. /**
  4491. * Add a new key and its corresponding value
  4492. * @param key the key to add
  4493. * @param value the value corresponding to the key
  4494. * @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
  4495. */
  4496. StringDictionary.prototype.add = function (key, value) {
  4497. if (this._data[key] !== undefined) {
  4498. return false;
  4499. }
  4500. this._data[key] = value;
  4501. ++this._count;
  4502. return true;
  4503. };
  4504. StringDictionary.prototype.set = function (key, value) {
  4505. if (this._data[key] === undefined) {
  4506. return false;
  4507. }
  4508. this._data[key] = value;
  4509. return true;
  4510. };
  4511. /**
  4512. * Get the element of the given key and remove it from the dictionary
  4513. * @param key
  4514. */
  4515. StringDictionary.prototype.getAndRemove = function (key) {
  4516. var val = this.get(key);
  4517. if (val !== undefined) {
  4518. delete this._data[key];
  4519. --this._count;
  4520. return val;
  4521. }
  4522. return null;
  4523. };
  4524. /**
  4525. * Remove a key/value from the dictionary.
  4526. * @param key the key to remove
  4527. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4528. */
  4529. StringDictionary.prototype.remove = function (key) {
  4530. if (this.contains(key)) {
  4531. delete this._data[key];
  4532. --this._count;
  4533. return true;
  4534. }
  4535. return false;
  4536. };
  4537. /**
  4538. * Clear the whole content of the dictionary
  4539. */
  4540. StringDictionary.prototype.clear = function () {
  4541. this._data = {};
  4542. this._count = 0;
  4543. };
  4544. Object.defineProperty(StringDictionary.prototype, "count", {
  4545. get: function () {
  4546. return this._count;
  4547. },
  4548. enumerable: true,
  4549. configurable: true
  4550. });
  4551. /**
  4552. * Execute a callback on each key/val of the dictionary.
  4553. * Note that you can remove any element in this dictionary in the callback implementation
  4554. * @param callback the callback to execute on a given key/value pair
  4555. */
  4556. StringDictionary.prototype.forEach = function (callback) {
  4557. for (var cur in this._data) {
  4558. var val = this._data[cur];
  4559. callback(cur, val);
  4560. }
  4561. };
  4562. /**
  4563. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4564. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4565. * Note that you can remove any element in this dictionary in the callback implementation
  4566. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4567. */
  4568. StringDictionary.prototype.first = function (callback) {
  4569. for (var cur in this._data) {
  4570. var val = this._data[cur];
  4571. var res = callback(cur, val);
  4572. if (res) {
  4573. return res;
  4574. }
  4575. }
  4576. return null;
  4577. };
  4578. return StringDictionary;
  4579. }());
  4580. BABYLON.StringDictionary = StringDictionary;
  4581. })(BABYLON || (BABYLON = {}));
  4582. var BABYLON;
  4583. (function (BABYLON) {
  4584. // Screenshots
  4585. var screenshotCanvas;
  4586. var cloneValue = function (source, destinationObject) {
  4587. if (!source)
  4588. return null;
  4589. if (source instanceof BABYLON.Mesh) {
  4590. return null;
  4591. }
  4592. if (source instanceof BABYLON.SubMesh) {
  4593. return source.clone(destinationObject);
  4594. }
  4595. else if (source.clone) {
  4596. return source.clone();
  4597. }
  4598. return null;
  4599. };
  4600. var Tools = (function () {
  4601. function Tools() {
  4602. }
  4603. Tools.Instantiate = function (className) {
  4604. var arr = className.split(".");
  4605. var fn = (window || this);
  4606. for (var i = 0, len = arr.length; i < len; i++) {
  4607. fn = fn[arr[i]];
  4608. }
  4609. if (typeof fn !== "function") {
  4610. return null;
  4611. }
  4612. return fn;
  4613. };
  4614. Tools.SetImmediate = function (action) {
  4615. if (window.setImmediate) {
  4616. window.setImmediate(action);
  4617. }
  4618. else {
  4619. setTimeout(action, 1);
  4620. }
  4621. };
  4622. Tools.IsExponentOfTwo = function (value) {
  4623. var count = 1;
  4624. do {
  4625. count *= 2;
  4626. } while (count < value);
  4627. return count === value;
  4628. };
  4629. Tools.GetExponentOfTwo = function (value, max) {
  4630. var count = 1;
  4631. do {
  4632. count *= 2;
  4633. } while (count < value);
  4634. if (count > max)
  4635. count = max;
  4636. return count;
  4637. };
  4638. Tools.GetFilename = function (path) {
  4639. var index = path.lastIndexOf("/");
  4640. if (index < 0)
  4641. return path;
  4642. return path.substring(index + 1);
  4643. };
  4644. Tools.GetDOMTextContent = function (element) {
  4645. var result = "";
  4646. var child = element.firstChild;
  4647. while (child) {
  4648. if (child.nodeType === 3) {
  4649. result += child.textContent;
  4650. }
  4651. child = child.nextSibling;
  4652. }
  4653. return result;
  4654. };
  4655. Tools.ToDegrees = function (angle) {
  4656. return angle * 180 / Math.PI;
  4657. };
  4658. Tools.ToRadians = function (angle) {
  4659. return angle * Math.PI / 180;
  4660. };
  4661. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4662. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4663. var output = "";
  4664. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4665. var i = 0;
  4666. var bytes = new Uint8Array(buffer);
  4667. while (i < bytes.length) {
  4668. chr1 = bytes[i++];
  4669. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4670. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4671. enc1 = chr1 >> 2;
  4672. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4673. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4674. enc4 = chr3 & 63;
  4675. if (isNaN(chr2)) {
  4676. enc3 = enc4 = 64;
  4677. }
  4678. else if (isNaN(chr3)) {
  4679. enc4 = 64;
  4680. }
  4681. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4682. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4683. }
  4684. return "data:image/png;base64," + output;
  4685. };
  4686. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4687. if (bias === void 0) { bias = null; }
  4688. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4689. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4690. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4691. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4692. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4693. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4694. }
  4695. if (bias) {
  4696. minimum.x -= minimum.x * bias.x + bias.y;
  4697. minimum.y -= minimum.y * bias.x + bias.y;
  4698. minimum.z -= minimum.z * bias.x + bias.y;
  4699. maximum.x += maximum.x * bias.x + bias.y;
  4700. maximum.y += maximum.y * bias.x + bias.y;
  4701. maximum.z += maximum.z * bias.x + bias.y;
  4702. }
  4703. return {
  4704. minimum: minimum,
  4705. maximum: maximum
  4706. };
  4707. };
  4708. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4709. if (bias === void 0) { bias = null; }
  4710. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4711. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4712. if (!stride) {
  4713. stride = 3;
  4714. }
  4715. for (var index = start; index < start + count; index++) {
  4716. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4717. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4718. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4719. }
  4720. if (bias) {
  4721. minimum.x -= minimum.x * bias.x + bias.y;
  4722. minimum.y -= minimum.y * bias.x + bias.y;
  4723. minimum.z -= minimum.z * bias.x + bias.y;
  4724. maximum.x += maximum.x * bias.x + bias.y;
  4725. maximum.y += maximum.y * bias.x + bias.y;
  4726. maximum.z += maximum.z * bias.x + bias.y;
  4727. }
  4728. return {
  4729. minimum: minimum,
  4730. maximum: maximum
  4731. };
  4732. };
  4733. Tools.Vector2ArrayFeeder = function (array) {
  4734. return function (index) {
  4735. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4736. var length = isFloatArray ? array.length / 2 : array.length;
  4737. if (index >= length) {
  4738. return null;
  4739. }
  4740. if (isFloatArray) {
  4741. var fa = array;
  4742. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4743. }
  4744. var a = array;
  4745. return a[index];
  4746. };
  4747. };
  4748. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4749. if (bias === void 0) { bias = null; }
  4750. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4751. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4752. var i = 0;
  4753. var cur = feeder(i++);
  4754. while (cur) {
  4755. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4756. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4757. cur = feeder(i++);
  4758. }
  4759. if (bias) {
  4760. minimum.x -= minimum.x * bias.x + bias.y;
  4761. minimum.y -= minimum.y * bias.x + bias.y;
  4762. maximum.x += maximum.x * bias.x + bias.y;
  4763. maximum.y += maximum.y * bias.x + bias.y;
  4764. }
  4765. return {
  4766. minimum: minimum,
  4767. maximum: maximum
  4768. };
  4769. };
  4770. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4771. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4772. return undefined;
  4773. return Array.isArray(obj) ? obj : [obj];
  4774. };
  4775. // Misc.
  4776. Tools.GetPointerPrefix = function () {
  4777. var eventPrefix = "pointer";
  4778. // Check if pointer events are supported
  4779. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4780. eventPrefix = "mouse";
  4781. }
  4782. return eventPrefix;
  4783. };
  4784. /**
  4785. * @param func - the function to be called
  4786. * @param requester - the object that will request the next frame. Falls back to window.
  4787. */
  4788. Tools.QueueNewFrame = function (func, requester) {
  4789. if (requester === void 0) { requester = window; }
  4790. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  4791. /*if(requester.isPresenting) {
  4792. return;
  4793. } else*/ if (requester.requestAnimationFrame)
  4794. requester.requestAnimationFrame(func);
  4795. else if (requester.msRequestAnimationFrame)
  4796. requester.msRequestAnimationFrame(func);
  4797. else if (requester.webkitRequestAnimationFrame)
  4798. requester.webkitRequestAnimationFrame(func);
  4799. else if (requester.mozRequestAnimationFrame)
  4800. requester.mozRequestAnimationFrame(func);
  4801. else if (requester.oRequestAnimationFrame)
  4802. requester.oRequestAnimationFrame(func);
  4803. else {
  4804. window.setTimeout(func, 16);
  4805. }
  4806. };
  4807. Tools.RequestFullscreen = function (element) {
  4808. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4809. if (!requestFunction)
  4810. return;
  4811. requestFunction.call(element);
  4812. };
  4813. Tools.ExitFullscreen = function () {
  4814. if (document.exitFullscreen) {
  4815. document.exitFullscreen();
  4816. }
  4817. else if (document.mozCancelFullScreen) {
  4818. document.mozCancelFullScreen();
  4819. }
  4820. else if (document.webkitCancelFullScreen) {
  4821. document.webkitCancelFullScreen();
  4822. }
  4823. else if (document.msCancelFullScreen) {
  4824. document.msCancelFullScreen();
  4825. }
  4826. };
  4827. Tools.SetCorsBehavior = function (url, img) {
  4828. if (Tools.CorsBehavior) {
  4829. switch (typeof (Tools.CorsBehavior)) {
  4830. case "function":
  4831. var result = Tools.CorsBehavior(url);
  4832. if (result) {
  4833. return result;
  4834. }
  4835. break;
  4836. case "string":
  4837. default:
  4838. img.crossOrigin = Tools.CorsBehavior;
  4839. break;
  4840. }
  4841. }
  4842. };
  4843. // External files
  4844. Tools.CleanUrl = function (url) {
  4845. url = url.replace(/#/mg, "%23");
  4846. return url;
  4847. };
  4848. Tools.LoadImage = function (url, onload, onerror, database) {
  4849. if (url instanceof ArrayBuffer) {
  4850. url = Tools.EncodeArrayBufferTobase64(url);
  4851. }
  4852. url = Tools.CleanUrl(url);
  4853. var img = new Image();
  4854. if (url.substr(0, 5) !== "data:") {
  4855. Tools.SetCorsBehavior(url, img);
  4856. }
  4857. img.onload = function () {
  4858. onload(img);
  4859. };
  4860. img.onerror = function (err) {
  4861. Tools.Error("Error while trying to load texture: " + url);
  4862. if (Tools.UseFallbackTexture) {
  4863. 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";
  4864. onload(img);
  4865. }
  4866. else {
  4867. onerror();
  4868. }
  4869. };
  4870. var noIndexedDB = function () {
  4871. img.src = url;
  4872. };
  4873. var loadFromIndexedDB = function () {
  4874. database.loadImageFromDB(url, img);
  4875. };
  4876. //ANY database to do!
  4877. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4878. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4879. }
  4880. else {
  4881. if (url.indexOf("file:") === -1) {
  4882. noIndexedDB();
  4883. }
  4884. else {
  4885. try {
  4886. var textureName = url.substring(5).toLowerCase();
  4887. var blobURL;
  4888. try {
  4889. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4890. }
  4891. catch (ex) {
  4892. // Chrome doesn't support oneTimeOnly parameter
  4893. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4894. }
  4895. img.src = blobURL;
  4896. }
  4897. catch (e) {
  4898. img.src = null;
  4899. }
  4900. }
  4901. }
  4902. return img;
  4903. };
  4904. //ANY
  4905. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4906. url = Tools.CleanUrl(url);
  4907. var noIndexedDB = function () {
  4908. var request = new XMLHttpRequest();
  4909. var loadUrl = Tools.BaseUrl + url;
  4910. request.open('GET', loadUrl, true);
  4911. if (useArrayBuffer) {
  4912. request.responseType = "arraybuffer";
  4913. }
  4914. request.onprogress = progressCallBack;
  4915. request.onreadystatechange = function () {
  4916. if (request.readyState === 4) {
  4917. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  4918. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  4919. callback(!useArrayBuffer ? request.responseText : request.response);
  4920. }
  4921. else {
  4922. if (onError) {
  4923. onError();
  4924. }
  4925. else {
  4926. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4927. }
  4928. }
  4929. }
  4930. };
  4931. request.send(null);
  4932. };
  4933. var loadFromIndexedDB = function () {
  4934. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4935. };
  4936. if (url.indexOf("file:") !== -1) {
  4937. var fileName = url.substring(5).toLowerCase();
  4938. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4939. }
  4940. else {
  4941. // Caching all files
  4942. if (database && database.enableSceneOffline) {
  4943. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4944. }
  4945. else {
  4946. noIndexedDB();
  4947. }
  4948. }
  4949. };
  4950. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4951. var reader = new FileReader();
  4952. reader.onload = function (e) {
  4953. //target doesn't have result from ts 1.3
  4954. callback(e.target['result']);
  4955. };
  4956. reader.onprogress = progressCallback;
  4957. reader.readAsDataURL(fileToLoad);
  4958. };
  4959. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4960. var reader = new FileReader();
  4961. reader.onerror = function (e) {
  4962. Tools.Log("Error while reading file: " + fileToLoad.name);
  4963. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4964. };
  4965. reader.onload = function (e) {
  4966. //target doesn't have result from ts 1.3
  4967. callback(e.target['result']);
  4968. };
  4969. reader.onprogress = progressCallBack;
  4970. if (!useArrayBuffer) {
  4971. // Asynchronous read
  4972. reader.readAsText(fileToLoad);
  4973. }
  4974. else {
  4975. reader.readAsArrayBuffer(fileToLoad);
  4976. }
  4977. };
  4978. //returns a downloadable url to a file content.
  4979. Tools.FileAsURL = function (content) {
  4980. var fileBlob = new Blob([content]);
  4981. var url = window.URL || window.webkitURL;
  4982. var link = url.createObjectURL(fileBlob);
  4983. return link;
  4984. };
  4985. // Misc.
  4986. Tools.Format = function (value, decimals) {
  4987. if (decimals === void 0) { decimals = 2; }
  4988. return value.toFixed(decimals);
  4989. };
  4990. Tools.CheckExtends = function (v, min, max) {
  4991. if (v.x < min.x)
  4992. min.x = v.x;
  4993. if (v.y < min.y)
  4994. min.y = v.y;
  4995. if (v.z < min.z)
  4996. min.z = v.z;
  4997. if (v.x > max.x)
  4998. max.x = v.x;
  4999. if (v.y > max.y)
  5000. max.y = v.y;
  5001. if (v.z > max.z)
  5002. max.z = v.z;
  5003. };
  5004. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5005. for (var prop in source) {
  5006. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5007. continue;
  5008. }
  5009. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5010. continue;
  5011. }
  5012. var sourceValue = source[prop];
  5013. var typeOfSourceValue = typeof sourceValue;
  5014. if (typeOfSourceValue === "function") {
  5015. continue;
  5016. }
  5017. if (typeOfSourceValue === "object") {
  5018. if (sourceValue instanceof Array) {
  5019. destination[prop] = [];
  5020. if (sourceValue.length > 0) {
  5021. if (typeof sourceValue[0] == "object") {
  5022. for (var index = 0; index < sourceValue.length; index++) {
  5023. var clonedValue = cloneValue(sourceValue[index], destination);
  5024. if (destination[prop].indexOf(clonedValue) === -1) {
  5025. destination[prop].push(clonedValue);
  5026. }
  5027. }
  5028. }
  5029. else {
  5030. destination[prop] = sourceValue.slice(0);
  5031. }
  5032. }
  5033. }
  5034. else {
  5035. destination[prop] = cloneValue(sourceValue, destination);
  5036. }
  5037. }
  5038. else {
  5039. destination[prop] = sourceValue;
  5040. }
  5041. }
  5042. };
  5043. Tools.IsEmpty = function (obj) {
  5044. for (var i in obj) {
  5045. return false;
  5046. }
  5047. return true;
  5048. };
  5049. Tools.RegisterTopRootEvents = function (events) {
  5050. for (var index = 0; index < events.length; index++) {
  5051. var event = events[index];
  5052. window.addEventListener(event.name, event.handler, false);
  5053. try {
  5054. if (window.parent) {
  5055. window.parent.addEventListener(event.name, event.handler, false);
  5056. }
  5057. }
  5058. catch (e) {
  5059. }
  5060. }
  5061. };
  5062. Tools.UnregisterTopRootEvents = function (events) {
  5063. for (var index = 0; index < events.length; index++) {
  5064. var event = events[index];
  5065. window.removeEventListener(event.name, event.handler);
  5066. try {
  5067. if (window.parent) {
  5068. window.parent.removeEventListener(event.name, event.handler);
  5069. }
  5070. }
  5071. catch (e) {
  5072. }
  5073. }
  5074. };
  5075. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5076. if (mimeType === void 0) { mimeType = "image/png"; }
  5077. // Read the contents of the framebuffer
  5078. var numberOfChannelsByLine = width * 4;
  5079. var halfHeight = height / 2;
  5080. //Reading datas from WebGL
  5081. var data = engine.readPixels(0, 0, width, height);
  5082. //To flip image on Y axis.
  5083. for (var i = 0; i < halfHeight; i++) {
  5084. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5085. var currentCell = j + i * numberOfChannelsByLine;
  5086. var targetLine = height - i - 1;
  5087. var targetCell = j + targetLine * numberOfChannelsByLine;
  5088. var temp = data[currentCell];
  5089. data[currentCell] = data[targetCell];
  5090. data[targetCell] = temp;
  5091. }
  5092. }
  5093. // Create a 2D canvas to store the result
  5094. if (!screenshotCanvas) {
  5095. screenshotCanvas = document.createElement('canvas');
  5096. }
  5097. screenshotCanvas.width = width;
  5098. screenshotCanvas.height = height;
  5099. var context = screenshotCanvas.getContext('2d');
  5100. // Copy the pixels to a 2D canvas
  5101. var imageData = context.createImageData(width, height);
  5102. var castData = (imageData.data);
  5103. castData.set(data);
  5104. context.putImageData(imageData, 0, 0);
  5105. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5106. };
  5107. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5108. if (mimeType === void 0) { mimeType = "image/png"; }
  5109. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5110. if (successCallback) {
  5111. successCallback(base64Image);
  5112. }
  5113. else {
  5114. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5115. if (("download" in document.createElement("a"))) {
  5116. var a = window.document.createElement("a");
  5117. a.href = base64Image;
  5118. var date = new Date();
  5119. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5120. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5121. window.document.body.appendChild(a);
  5122. a.addEventListener("click", function () {
  5123. a.parentElement.removeChild(a);
  5124. });
  5125. a.click();
  5126. }
  5127. else {
  5128. var newWindow = window.open("");
  5129. var img = newWindow.document.createElement("img");
  5130. img.src = base64Image;
  5131. newWindow.document.body.appendChild(img);
  5132. }
  5133. }
  5134. };
  5135. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5136. if (mimeType === void 0) { mimeType = "image/png"; }
  5137. var width;
  5138. var height;
  5139. // If a precision value is specified
  5140. if (size.precision) {
  5141. width = Math.round(engine.getRenderWidth() * size.precision);
  5142. height = Math.round(width / engine.getAspectRatio(camera));
  5143. }
  5144. else if (size.width && size.height) {
  5145. width = size.width;
  5146. height = size.height;
  5147. }
  5148. else if (size.width && !size.height) {
  5149. width = size.width;
  5150. height = Math.round(width / engine.getAspectRatio(camera));
  5151. }
  5152. else if (size.height && !size.width) {
  5153. height = size.height;
  5154. width = Math.round(height * engine.getAspectRatio(camera));
  5155. }
  5156. else if (!isNaN(size)) {
  5157. height = size;
  5158. width = size;
  5159. }
  5160. else {
  5161. Tools.Error("Invalid 'size' parameter !");
  5162. return;
  5163. }
  5164. if (!screenshotCanvas) {
  5165. screenshotCanvas = document.createElement('canvas');
  5166. }
  5167. screenshotCanvas.width = width;
  5168. screenshotCanvas.height = height;
  5169. var renderContext = screenshotCanvas.getContext("2d");
  5170. renderContext.drawImage(engine.getRenderingCanvas(), 0, 0, width, height);
  5171. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5172. };
  5173. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  5174. if (mimeType === void 0) { mimeType = "image/png"; }
  5175. var width;
  5176. var height;
  5177. //If a precision value is specified
  5178. if (size.precision) {
  5179. width = Math.round(engine.getRenderWidth() * size.precision);
  5180. height = Math.round(width / engine.getAspectRatio(camera));
  5181. size = { width: width, height: height };
  5182. }
  5183. else if (size.width && size.height) {
  5184. width = size.width;
  5185. height = size.height;
  5186. }
  5187. else if (size.width && !size.height) {
  5188. width = size.width;
  5189. height = Math.round(width / engine.getAspectRatio(camera));
  5190. size = { width: width, height: height };
  5191. }
  5192. else if (size.height && !size.width) {
  5193. height = size.height;
  5194. width = Math.round(height * engine.getAspectRatio(camera));
  5195. size = { width: width, height: height };
  5196. }
  5197. else if (!isNaN(size)) {
  5198. height = size;
  5199. width = size;
  5200. }
  5201. else {
  5202. Tools.Error("Invalid 'size' parameter !");
  5203. return;
  5204. }
  5205. var scene = camera.getScene();
  5206. var previousCamera = null;
  5207. if (scene.activeCamera !== camera) {
  5208. previousCamera = scene.activeCamera;
  5209. scene.activeCamera = camera;
  5210. }
  5211. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5212. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  5213. texture.renderList = scene.meshes;
  5214. texture.onAfterRenderObservable.add(function () {
  5215. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5216. });
  5217. scene.incrementRenderId();
  5218. scene.resetCachedMaterial();
  5219. texture.render(true);
  5220. texture.dispose();
  5221. if (previousCamera) {
  5222. scene.activeCamera = previousCamera;
  5223. }
  5224. camera.getProjectionMatrix(true); // Force cache refresh;
  5225. };
  5226. // XHR response validator for local file scenario
  5227. Tools.ValidateXHRData = function (xhr, dataType) {
  5228. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5229. if (dataType === void 0) { dataType = 7; }
  5230. try {
  5231. if (dataType & 1) {
  5232. if (xhr.responseText && xhr.responseText.length > 0) {
  5233. return true;
  5234. }
  5235. else if (dataType === 1) {
  5236. return false;
  5237. }
  5238. }
  5239. if (dataType & 2) {
  5240. // Check header width and height since there is no "TGA" magic number
  5241. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5242. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5243. return true;
  5244. }
  5245. else if (dataType === 2) {
  5246. return false;
  5247. }
  5248. }
  5249. if (dataType & 4) {
  5250. // Check for the "DDS" magic number
  5251. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5252. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5253. return true;
  5254. }
  5255. else {
  5256. return false;
  5257. }
  5258. }
  5259. }
  5260. catch (e) {
  5261. }
  5262. return false;
  5263. };
  5264. /**
  5265. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5266. * Be aware Math.random() could cause collisions, but:
  5267. * "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"
  5268. */
  5269. Tools.RandomId = function () {
  5270. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5271. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5272. return v.toString(16);
  5273. });
  5274. };
  5275. Object.defineProperty(Tools, "NoneLogLevel", {
  5276. get: function () {
  5277. return Tools._NoneLogLevel;
  5278. },
  5279. enumerable: true,
  5280. configurable: true
  5281. });
  5282. Object.defineProperty(Tools, "MessageLogLevel", {
  5283. get: function () {
  5284. return Tools._MessageLogLevel;
  5285. },
  5286. enumerable: true,
  5287. configurable: true
  5288. });
  5289. Object.defineProperty(Tools, "WarningLogLevel", {
  5290. get: function () {
  5291. return Tools._WarningLogLevel;
  5292. },
  5293. enumerable: true,
  5294. configurable: true
  5295. });
  5296. Object.defineProperty(Tools, "ErrorLogLevel", {
  5297. get: function () {
  5298. return Tools._ErrorLogLevel;
  5299. },
  5300. enumerable: true,
  5301. configurable: true
  5302. });
  5303. Object.defineProperty(Tools, "AllLogLevel", {
  5304. get: function () {
  5305. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5306. },
  5307. enumerable: true,
  5308. configurable: true
  5309. });
  5310. Tools._AddLogEntry = function (entry) {
  5311. Tools._LogCache = entry + Tools._LogCache;
  5312. if (Tools.OnNewCacheEntry) {
  5313. Tools.OnNewCacheEntry(entry);
  5314. }
  5315. };
  5316. Tools._FormatMessage = function (message) {
  5317. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5318. var date = new Date();
  5319. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5320. };
  5321. Tools._LogDisabled = function (message) {
  5322. // nothing to do
  5323. };
  5324. Tools._LogEnabled = function (message) {
  5325. var formattedMessage = Tools._FormatMessage(message);
  5326. console.log("BJS - " + formattedMessage);
  5327. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5328. Tools._AddLogEntry(entry);
  5329. };
  5330. Tools._WarnDisabled = function (message) {
  5331. // nothing to do
  5332. };
  5333. Tools._WarnEnabled = function (message) {
  5334. var formattedMessage = Tools._FormatMessage(message);
  5335. console.warn("BJS - " + formattedMessage);
  5336. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5337. Tools._AddLogEntry(entry);
  5338. };
  5339. Tools._ErrorDisabled = function (message) {
  5340. // nothing to do
  5341. };
  5342. Tools._ErrorEnabled = function (message) {
  5343. Tools.errorsCount++;
  5344. var formattedMessage = Tools._FormatMessage(message);
  5345. console.error("BJS - " + formattedMessage);
  5346. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5347. Tools._AddLogEntry(entry);
  5348. };
  5349. Object.defineProperty(Tools, "LogCache", {
  5350. get: function () {
  5351. return Tools._LogCache;
  5352. },
  5353. enumerable: true,
  5354. configurable: true
  5355. });
  5356. Tools.ClearLogCache = function () {
  5357. Tools._LogCache = "";
  5358. Tools.errorsCount = 0;
  5359. };
  5360. Object.defineProperty(Tools, "LogLevels", {
  5361. set: function (level) {
  5362. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5363. Tools.Log = Tools._LogEnabled;
  5364. }
  5365. else {
  5366. Tools.Log = Tools._LogDisabled;
  5367. }
  5368. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5369. Tools.Warn = Tools._WarnEnabled;
  5370. }
  5371. else {
  5372. Tools.Warn = Tools._WarnDisabled;
  5373. }
  5374. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5375. Tools.Error = Tools._ErrorEnabled;
  5376. }
  5377. else {
  5378. Tools.Error = Tools._ErrorDisabled;
  5379. }
  5380. },
  5381. enumerable: true,
  5382. configurable: true
  5383. });
  5384. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5385. get: function () {
  5386. return Tools._PerformanceNoneLogLevel;
  5387. },
  5388. enumerable: true,
  5389. configurable: true
  5390. });
  5391. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5392. get: function () {
  5393. return Tools._PerformanceUserMarkLogLevel;
  5394. },
  5395. enumerable: true,
  5396. configurable: true
  5397. });
  5398. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5399. get: function () {
  5400. return Tools._PerformanceConsoleLogLevel;
  5401. },
  5402. enumerable: true,
  5403. configurable: true
  5404. });
  5405. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5406. set: function (level) {
  5407. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5408. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5409. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5410. return;
  5411. }
  5412. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5413. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5414. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5415. return;
  5416. }
  5417. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5418. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5419. },
  5420. enumerable: true,
  5421. configurable: true
  5422. });
  5423. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5424. };
  5425. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5426. };
  5427. Tools._StartUserMark = function (counterName, condition) {
  5428. if (condition === void 0) { condition = true; }
  5429. if (!condition || !Tools._performance.mark) {
  5430. return;
  5431. }
  5432. Tools._performance.mark(counterName + "-Begin");
  5433. };
  5434. Tools._EndUserMark = function (counterName, condition) {
  5435. if (condition === void 0) { condition = true; }
  5436. if (!condition || !Tools._performance.mark) {
  5437. return;
  5438. }
  5439. Tools._performance.mark(counterName + "-End");
  5440. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5441. };
  5442. Tools._StartPerformanceConsole = function (counterName, condition) {
  5443. if (condition === void 0) { condition = true; }
  5444. if (!condition) {
  5445. return;
  5446. }
  5447. Tools._StartUserMark(counterName, condition);
  5448. if (console.time) {
  5449. console.time(counterName);
  5450. }
  5451. };
  5452. Tools._EndPerformanceConsole = function (counterName, condition) {
  5453. if (condition === void 0) { condition = true; }
  5454. if (!condition) {
  5455. return;
  5456. }
  5457. Tools._EndUserMark(counterName, condition);
  5458. if (console.time) {
  5459. console.timeEnd(counterName);
  5460. }
  5461. };
  5462. Object.defineProperty(Tools, "Now", {
  5463. get: function () {
  5464. if (window.performance && window.performance.now) {
  5465. return window.performance.now();
  5466. }
  5467. return new Date().getTime();
  5468. },
  5469. enumerable: true,
  5470. configurable: true
  5471. });
  5472. /**
  5473. * This method will return the name of the class used to create the instance of the given object.
  5474. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5475. * @param object the object to get the class name from
  5476. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5477. */
  5478. Tools.getClassName = function (object, isType) {
  5479. if (isType === void 0) { isType = false; }
  5480. var name = null;
  5481. if (!isType && object.getClassName) {
  5482. name = object.getClassName();
  5483. }
  5484. else {
  5485. if (object instanceof Object) {
  5486. var classObj = isType ? object : Object.getPrototypeOf(object);
  5487. name = classObj.constructor["__bjsclassName__"];
  5488. }
  5489. if (!name) {
  5490. name = typeof object;
  5491. }
  5492. }
  5493. return name;
  5494. };
  5495. Tools.first = function (array, predicate) {
  5496. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  5497. var el = array_1[_i];
  5498. if (predicate(el)) {
  5499. return el;
  5500. }
  5501. }
  5502. };
  5503. /**
  5504. * This method will return the name of the full name of the class, including its owning module (if any).
  5505. * 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).
  5506. * @param object the object to get the class name from
  5507. * @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.
  5508. */
  5509. Tools.getFullClassName = function (object, isType) {
  5510. if (isType === void 0) { isType = false; }
  5511. var className = null;
  5512. var moduleName = null;
  5513. if (!isType && object.getClassName) {
  5514. className = object.getClassName();
  5515. }
  5516. else {
  5517. if (object instanceof Object) {
  5518. var classObj = isType ? object : Object.getPrototypeOf(object);
  5519. className = classObj.constructor["__bjsclassName__"];
  5520. moduleName = classObj.constructor["__bjsmoduleName__"];
  5521. }
  5522. if (!className) {
  5523. className = typeof object;
  5524. }
  5525. }
  5526. if (!className) {
  5527. return null;
  5528. }
  5529. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  5530. };
  5531. /**
  5532. * 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.
  5533. * @param array
  5534. */
  5535. Tools.arrayOrStringFeeder = function (array) {
  5536. return function (index) {
  5537. if (index >= array.length) {
  5538. return null;
  5539. }
  5540. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5541. if (val && val.getHashCode) {
  5542. val = val.getHashCode();
  5543. }
  5544. if (typeof val === "string") {
  5545. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5546. }
  5547. return val;
  5548. };
  5549. };
  5550. /**
  5551. * Compute the hashCode of a stream of number
  5552. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5553. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5554. * @return the hash code computed
  5555. */
  5556. Tools.hashCodeFromStream = function (feeder) {
  5557. // Based from here: http://stackoverflow.com/a/7616484/802124
  5558. var hash = 0;
  5559. var index = 0;
  5560. var chr = feeder(index++);
  5561. while (chr != null) {
  5562. hash = ((hash << 5) - hash) + chr;
  5563. hash |= 0; // Convert to 32bit integer
  5564. chr = feeder(index++);
  5565. }
  5566. return hash;
  5567. };
  5568. Tools.BaseUrl = "";
  5569. Tools.CorsBehavior = "anonymous";
  5570. Tools.UseFallbackTexture = true;
  5571. // Logs
  5572. Tools._NoneLogLevel = 0;
  5573. Tools._MessageLogLevel = 1;
  5574. Tools._WarningLogLevel = 2;
  5575. Tools._ErrorLogLevel = 4;
  5576. Tools._LogCache = "";
  5577. Tools.errorsCount = 0;
  5578. Tools.Log = Tools._LogEnabled;
  5579. Tools.Warn = Tools._WarnEnabled;
  5580. Tools.Error = Tools._ErrorEnabled;
  5581. // Performances
  5582. Tools._PerformanceNoneLogLevel = 0;
  5583. Tools._PerformanceUserMarkLogLevel = 1;
  5584. Tools._PerformanceConsoleLogLevel = 2;
  5585. Tools._performance = window.performance;
  5586. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5587. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5588. return Tools;
  5589. }());
  5590. BABYLON.Tools = Tools;
  5591. /**
  5592. * This class is used to track a performance counter which is number based.
  5593. * The user has access to many properties which give statistics of different nature
  5594. *
  5595. * The implementer can track two kinds of Performance Counter: time and count
  5596. * 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.
  5597. * 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.
  5598. */
  5599. var PerfCounter = (function () {
  5600. function PerfCounter() {
  5601. this._startMonitoringTime = 0;
  5602. this._min = 0;
  5603. this._max = 0;
  5604. this._average = 0;
  5605. this._lastSecAverage = 0;
  5606. this._current = 0;
  5607. this._totalValueCount = 0;
  5608. this._totalAccumulated = 0;
  5609. this._lastSecAccumulated = 0;
  5610. this._lastSecTime = 0;
  5611. this._lastSecValueCount = 0;
  5612. }
  5613. Object.defineProperty(PerfCounter.prototype, "min", {
  5614. /**
  5615. * Returns the smallest value ever
  5616. */
  5617. get: function () {
  5618. return this._min;
  5619. },
  5620. enumerable: true,
  5621. configurable: true
  5622. });
  5623. Object.defineProperty(PerfCounter.prototype, "max", {
  5624. /**
  5625. * Returns the biggest value ever
  5626. */
  5627. get: function () {
  5628. return this._max;
  5629. },
  5630. enumerable: true,
  5631. configurable: true
  5632. });
  5633. Object.defineProperty(PerfCounter.prototype, "average", {
  5634. /**
  5635. * Returns the average value since the performance counter is running
  5636. */
  5637. get: function () {
  5638. return this._average;
  5639. },
  5640. enumerable: true,
  5641. configurable: true
  5642. });
  5643. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5644. /**
  5645. * Returns the average value of the last second the counter was monitored
  5646. */
  5647. get: function () {
  5648. return this._lastSecAverage;
  5649. },
  5650. enumerable: true,
  5651. configurable: true
  5652. });
  5653. Object.defineProperty(PerfCounter.prototype, "current", {
  5654. /**
  5655. * Returns the current value
  5656. */
  5657. get: function () {
  5658. return this._current;
  5659. },
  5660. enumerable: true,
  5661. configurable: true
  5662. });
  5663. Object.defineProperty(PerfCounter.prototype, "total", {
  5664. get: function () {
  5665. return this._totalAccumulated;
  5666. },
  5667. enumerable: true,
  5668. configurable: true
  5669. });
  5670. /**
  5671. * Call this method to start monitoring a new frame.
  5672. * 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.
  5673. */
  5674. PerfCounter.prototype.fetchNewFrame = function () {
  5675. this._totalValueCount++;
  5676. this._current = 0;
  5677. this._lastSecValueCount++;
  5678. };
  5679. /**
  5680. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5681. * @param newCount the count value to add to the monitored count
  5682. * @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.
  5683. */
  5684. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5685. this._current += newCount;
  5686. if (fetchResult) {
  5687. this._fetchResult();
  5688. }
  5689. };
  5690. /**
  5691. * Start monitoring this performance counter
  5692. */
  5693. PerfCounter.prototype.beginMonitoring = function () {
  5694. this._startMonitoringTime = Tools.Now;
  5695. };
  5696. /**
  5697. * Compute the time lapsed since the previous beginMonitoring() call.
  5698. * @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
  5699. */
  5700. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5701. if (newFrame === void 0) { newFrame = true; }
  5702. if (newFrame) {
  5703. this.fetchNewFrame();
  5704. }
  5705. var currentTime = Tools.Now;
  5706. this._current = currentTime - this._startMonitoringTime;
  5707. if (newFrame) {
  5708. this._fetchResult();
  5709. }
  5710. };
  5711. PerfCounter.prototype._fetchResult = function () {
  5712. this._totalAccumulated += this._current;
  5713. this._lastSecAccumulated += this._current;
  5714. // Min/Max update
  5715. this._min = Math.min(this._min, this._current);
  5716. this._max = Math.max(this._max, this._current);
  5717. this._average = this._totalAccumulated / this._totalValueCount;
  5718. // Reset last sec?
  5719. var now = Tools.Now;
  5720. if ((now - this._lastSecTime) > 1000) {
  5721. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5722. this._lastSecTime = now;
  5723. this._lastSecAccumulated = 0;
  5724. this._lastSecValueCount = 0;
  5725. }
  5726. };
  5727. return PerfCounter;
  5728. }());
  5729. BABYLON.PerfCounter = PerfCounter;
  5730. /**
  5731. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  5732. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5733. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5734. * @param name The name of the class, case should be preserved
  5735. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  5736. */
  5737. function className(name, module) {
  5738. return function (target) {
  5739. target["__bjsclassName__"] = name;
  5740. target["__bjsmoduleName__"] = (module != null) ? module : null;
  5741. };
  5742. }
  5743. BABYLON.className = className;
  5744. /**
  5745. * An implementation of a loop for asynchronous functions.
  5746. */
  5747. var AsyncLoop = (function () {
  5748. /**
  5749. * Constroctor.
  5750. * @param iterations the number of iterations.
  5751. * @param _fn the function to run each iteration
  5752. * @param _successCallback the callback that will be called upon succesful execution
  5753. * @param offset starting offset.
  5754. */
  5755. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5756. if (offset === void 0) { offset = 0; }
  5757. this.iterations = iterations;
  5758. this._fn = _fn;
  5759. this._successCallback = _successCallback;
  5760. this.index = offset - 1;
  5761. this._done = false;
  5762. }
  5763. /**
  5764. * Execute the next iteration. Must be called after the last iteration was finished.
  5765. */
  5766. AsyncLoop.prototype.executeNext = function () {
  5767. if (!this._done) {
  5768. if (this.index + 1 < this.iterations) {
  5769. ++this.index;
  5770. this._fn(this);
  5771. }
  5772. else {
  5773. this.breakLoop();
  5774. }
  5775. }
  5776. };
  5777. /**
  5778. * Break the loop and run the success callback.
  5779. */
  5780. AsyncLoop.prototype.breakLoop = function () {
  5781. this._done = true;
  5782. this._successCallback();
  5783. };
  5784. /**
  5785. * Helper function
  5786. */
  5787. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5788. if (offset === void 0) { offset = 0; }
  5789. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5790. loop.executeNext();
  5791. return loop;
  5792. };
  5793. /**
  5794. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5795. * @param iterations total number of iterations
  5796. * @param syncedIterations number of synchronous iterations in each async iteration.
  5797. * @param fn the function to call each iteration.
  5798. * @param callback a success call back that will be called when iterating stops.
  5799. * @param breakFunction a break condition (optional)
  5800. * @param timeout timeout settings for the setTimeout function. default - 0.
  5801. * @constructor
  5802. */
  5803. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5804. if (timeout === void 0) { timeout = 0; }
  5805. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5806. if (breakFunction && breakFunction())
  5807. loop.breakLoop();
  5808. else {
  5809. setTimeout(function () {
  5810. for (var i = 0; i < syncedIterations; ++i) {
  5811. var iteration = (loop.index * syncedIterations) + i;
  5812. if (iteration >= iterations)
  5813. break;
  5814. fn(iteration);
  5815. if (breakFunction && breakFunction()) {
  5816. loop.breakLoop();
  5817. break;
  5818. }
  5819. }
  5820. loop.executeNext();
  5821. }, timeout);
  5822. }
  5823. }, callback);
  5824. };
  5825. return AsyncLoop;
  5826. }());
  5827. BABYLON.AsyncLoop = AsyncLoop;
  5828. })(BABYLON || (BABYLON = {}));
  5829. var BABYLON;
  5830. (function (BABYLON) {
  5831. var Internals;
  5832. (function (Internals) {
  5833. var _AlphaState = (function () {
  5834. /**
  5835. * Initializes the state.
  5836. */
  5837. function _AlphaState() {
  5838. this._isAlphaBlendDirty = false;
  5839. this._isBlendFunctionParametersDirty = false;
  5840. this._alphaBlend = false;
  5841. this._blendFunctionParameters = new Array(4);
  5842. this.reset();
  5843. }
  5844. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5845. get: function () {
  5846. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5847. },
  5848. enumerable: true,
  5849. configurable: true
  5850. });
  5851. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5852. get: function () {
  5853. return this._alphaBlend;
  5854. },
  5855. set: function (value) {
  5856. if (this._alphaBlend === value) {
  5857. return;
  5858. }
  5859. this._alphaBlend = value;
  5860. this._isAlphaBlendDirty = true;
  5861. },
  5862. enumerable: true,
  5863. configurable: true
  5864. });
  5865. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5866. if (this._blendFunctionParameters[0] === value0 &&
  5867. this._blendFunctionParameters[1] === value1 &&
  5868. this._blendFunctionParameters[2] === value2 &&
  5869. this._blendFunctionParameters[3] === value3) {
  5870. return;
  5871. }
  5872. this._blendFunctionParameters[0] = value0;
  5873. this._blendFunctionParameters[1] = value1;
  5874. this._blendFunctionParameters[2] = value2;
  5875. this._blendFunctionParameters[3] = value3;
  5876. this._isBlendFunctionParametersDirty = true;
  5877. };
  5878. _AlphaState.prototype.reset = function () {
  5879. this._alphaBlend = false;
  5880. this._blendFunctionParameters[0] = null;
  5881. this._blendFunctionParameters[1] = null;
  5882. this._blendFunctionParameters[2] = null;
  5883. this._blendFunctionParameters[3] = null;
  5884. this._isAlphaBlendDirty = true;
  5885. this._isBlendFunctionParametersDirty = false;
  5886. };
  5887. _AlphaState.prototype.apply = function (gl) {
  5888. if (!this.isDirty) {
  5889. return;
  5890. }
  5891. // Alpha blend
  5892. if (this._isAlphaBlendDirty) {
  5893. if (this._alphaBlend) {
  5894. gl.enable(gl.BLEND);
  5895. }
  5896. else {
  5897. gl.disable(gl.BLEND);
  5898. }
  5899. this._isAlphaBlendDirty = false;
  5900. }
  5901. // Alpha function
  5902. if (this._isBlendFunctionParametersDirty) {
  5903. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5904. this._isBlendFunctionParametersDirty = false;
  5905. }
  5906. };
  5907. return _AlphaState;
  5908. }());
  5909. Internals._AlphaState = _AlphaState;
  5910. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5911. })(BABYLON || (BABYLON = {}));
  5912. var BABYLON;
  5913. (function (BABYLON) {
  5914. var Internals;
  5915. (function (Internals) {
  5916. var _DepthCullingState = (function () {
  5917. /**
  5918. * Initializes the state.
  5919. */
  5920. function _DepthCullingState() {
  5921. this._isDepthTestDirty = false;
  5922. this._isDepthMaskDirty = false;
  5923. this._isDepthFuncDirty = false;
  5924. this._isCullFaceDirty = false;
  5925. this._isCullDirty = false;
  5926. this._isZOffsetDirty = false;
  5927. this.reset();
  5928. }
  5929. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5930. get: function () {
  5931. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5932. },
  5933. enumerable: true,
  5934. configurable: true
  5935. });
  5936. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5937. get: function () {
  5938. return this._zOffset;
  5939. },
  5940. set: function (value) {
  5941. if (this._zOffset === value) {
  5942. return;
  5943. }
  5944. this._zOffset = value;
  5945. this._isZOffsetDirty = true;
  5946. },
  5947. enumerable: true,
  5948. configurable: true
  5949. });
  5950. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5951. get: function () {
  5952. return this._cullFace;
  5953. },
  5954. set: function (value) {
  5955. if (this._cullFace === value) {
  5956. return;
  5957. }
  5958. this._cullFace = value;
  5959. this._isCullFaceDirty = true;
  5960. },
  5961. enumerable: true,
  5962. configurable: true
  5963. });
  5964. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5965. get: function () {
  5966. return this._cull;
  5967. },
  5968. set: function (value) {
  5969. if (this._cull === value) {
  5970. return;
  5971. }
  5972. this._cull = value;
  5973. this._isCullDirty = true;
  5974. },
  5975. enumerable: true,
  5976. configurable: true
  5977. });
  5978. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5979. get: function () {
  5980. return this._depthFunc;
  5981. },
  5982. set: function (value) {
  5983. if (this._depthFunc === value) {
  5984. return;
  5985. }
  5986. this._depthFunc = value;
  5987. this._isDepthFuncDirty = true;
  5988. },
  5989. enumerable: true,
  5990. configurable: true
  5991. });
  5992. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5993. get: function () {
  5994. return this._depthMask;
  5995. },
  5996. set: function (value) {
  5997. if (this._depthMask === value) {
  5998. return;
  5999. }
  6000. this._depthMask = value;
  6001. this._isDepthMaskDirty = true;
  6002. },
  6003. enumerable: true,
  6004. configurable: true
  6005. });
  6006. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6007. get: function () {
  6008. return this._depthTest;
  6009. },
  6010. set: function (value) {
  6011. if (this._depthTest === value) {
  6012. return;
  6013. }
  6014. this._depthTest = value;
  6015. this._isDepthTestDirty = true;
  6016. },
  6017. enumerable: true,
  6018. configurable: true
  6019. });
  6020. _DepthCullingState.prototype.reset = function () {
  6021. this._depthMask = true;
  6022. this._depthTest = true;
  6023. this._depthFunc = null;
  6024. this._cullFace = null;
  6025. this._cull = null;
  6026. this._zOffset = 0;
  6027. this._isDepthTestDirty = true;
  6028. this._isDepthMaskDirty = true;
  6029. this._isDepthFuncDirty = false;
  6030. this._isCullFaceDirty = false;
  6031. this._isCullDirty = false;
  6032. this._isZOffsetDirty = false;
  6033. };
  6034. _DepthCullingState.prototype.apply = function (gl) {
  6035. if (!this.isDirty) {
  6036. return;
  6037. }
  6038. // Cull
  6039. if (this._isCullDirty) {
  6040. if (this.cull) {
  6041. gl.enable(gl.CULL_FACE);
  6042. }
  6043. else {
  6044. gl.disable(gl.CULL_FACE);
  6045. }
  6046. this._isCullDirty = false;
  6047. }
  6048. // Cull face
  6049. if (this._isCullFaceDirty) {
  6050. gl.cullFace(this.cullFace);
  6051. this._isCullFaceDirty = false;
  6052. }
  6053. // Depth mask
  6054. if (this._isDepthMaskDirty) {
  6055. gl.depthMask(this.depthMask);
  6056. this._isDepthMaskDirty = false;
  6057. }
  6058. // Depth test
  6059. if (this._isDepthTestDirty) {
  6060. if (this.depthTest) {
  6061. gl.enable(gl.DEPTH_TEST);
  6062. }
  6063. else {
  6064. gl.disable(gl.DEPTH_TEST);
  6065. }
  6066. this._isDepthTestDirty = false;
  6067. }
  6068. // Depth func
  6069. if (this._isDepthFuncDirty) {
  6070. gl.depthFunc(this.depthFunc);
  6071. this._isDepthFuncDirty = false;
  6072. }
  6073. // zOffset
  6074. if (this._isZOffsetDirty) {
  6075. if (this.zOffset) {
  6076. gl.enable(gl.POLYGON_OFFSET_FILL);
  6077. gl.polygonOffset(this.zOffset, 0);
  6078. }
  6079. else {
  6080. gl.disable(gl.POLYGON_OFFSET_FILL);
  6081. }
  6082. this._isZOffsetDirty = false;
  6083. }
  6084. };
  6085. return _DepthCullingState;
  6086. }());
  6087. Internals._DepthCullingState = _DepthCullingState;
  6088. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6089. })(BABYLON || (BABYLON = {}));
  6090. var BABYLON;
  6091. (function (BABYLON) {
  6092. var Internals;
  6093. (function (Internals) {
  6094. var _StencilState = (function () {
  6095. function _StencilState() {
  6096. this._isStencilTestDirty = false;
  6097. this._isStencilMaskDirty = false;
  6098. this._isStencilFuncDirty = false;
  6099. this._isStencilOpDirty = false;
  6100. this.reset();
  6101. }
  6102. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6103. get: function () {
  6104. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6105. },
  6106. enumerable: true,
  6107. configurable: true
  6108. });
  6109. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6110. get: function () {
  6111. return this._stencilFunc;
  6112. },
  6113. set: function (value) {
  6114. if (this._stencilFunc === value) {
  6115. return;
  6116. }
  6117. this._stencilFunc = value;
  6118. this._isStencilFuncDirty = true;
  6119. },
  6120. enumerable: true,
  6121. configurable: true
  6122. });
  6123. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6124. get: function () {
  6125. return this._stencilFuncRef;
  6126. },
  6127. set: function (value) {
  6128. if (this._stencilFuncRef === value) {
  6129. return;
  6130. }
  6131. this._stencilFuncRef = value;
  6132. this._isStencilFuncDirty = true;
  6133. },
  6134. enumerable: true,
  6135. configurable: true
  6136. });
  6137. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6138. get: function () {
  6139. return this._stencilFuncMask;
  6140. },
  6141. set: function (value) {
  6142. if (this._stencilFuncMask === value) {
  6143. return;
  6144. }
  6145. this._stencilFuncMask = value;
  6146. this._isStencilFuncDirty = true;
  6147. },
  6148. enumerable: true,
  6149. configurable: true
  6150. });
  6151. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6152. get: function () {
  6153. return this._stencilOpStencilFail;
  6154. },
  6155. set: function (value) {
  6156. if (this._stencilOpStencilFail === value) {
  6157. return;
  6158. }
  6159. this._stencilOpStencilFail = value;
  6160. this._isStencilOpDirty = true;
  6161. },
  6162. enumerable: true,
  6163. configurable: true
  6164. });
  6165. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6166. get: function () {
  6167. return this._stencilOpDepthFail;
  6168. },
  6169. set: function (value) {
  6170. if (this._stencilOpDepthFail === value) {
  6171. return;
  6172. }
  6173. this._stencilOpDepthFail = value;
  6174. this._isStencilOpDirty = true;
  6175. },
  6176. enumerable: true,
  6177. configurable: true
  6178. });
  6179. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6180. get: function () {
  6181. return this._stencilOpStencilDepthPass;
  6182. },
  6183. set: function (value) {
  6184. if (this._stencilOpStencilDepthPass === value) {
  6185. return;
  6186. }
  6187. this._stencilOpStencilDepthPass = value;
  6188. this._isStencilOpDirty = true;
  6189. },
  6190. enumerable: true,
  6191. configurable: true
  6192. });
  6193. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6194. get: function () {
  6195. return this._stencilMask;
  6196. },
  6197. set: function (value) {
  6198. if (this._stencilMask === value) {
  6199. return;
  6200. }
  6201. this._stencilMask = value;
  6202. this._isStencilMaskDirty = true;
  6203. },
  6204. enumerable: true,
  6205. configurable: true
  6206. });
  6207. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6208. get: function () {
  6209. return this._stencilTest;
  6210. },
  6211. set: function (value) {
  6212. if (this._stencilTest === value) {
  6213. return;
  6214. }
  6215. this._stencilTest = value;
  6216. this._isStencilTestDirty = true;
  6217. },
  6218. enumerable: true,
  6219. configurable: true
  6220. });
  6221. _StencilState.prototype.reset = function () {
  6222. this._stencilTest = false;
  6223. this._stencilMask = 0xFF;
  6224. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6225. this._stencilFuncRef = 1;
  6226. this._stencilFuncMask = 0xFF;
  6227. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6228. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6229. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6230. this._isStencilTestDirty = true;
  6231. this._isStencilMaskDirty = true;
  6232. this._isStencilFuncDirty = true;
  6233. this._isStencilOpDirty = true;
  6234. };
  6235. _StencilState.prototype.apply = function (gl) {
  6236. if (!this.isDirty) {
  6237. return;
  6238. }
  6239. // Stencil test
  6240. if (this._isStencilTestDirty) {
  6241. if (this.stencilTest) {
  6242. gl.enable(gl.STENCIL_TEST);
  6243. }
  6244. else {
  6245. gl.disable(gl.STENCIL_TEST);
  6246. }
  6247. this._isStencilTestDirty = false;
  6248. }
  6249. // Stencil mask
  6250. if (this._isStencilMaskDirty) {
  6251. gl.stencilMask(this.stencilMask);
  6252. this._isStencilMaskDirty = false;
  6253. }
  6254. // Stencil func
  6255. if (this._isStencilFuncDirty) {
  6256. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6257. this._isStencilFuncDirty = false;
  6258. }
  6259. // Stencil op
  6260. if (this._isStencilOpDirty) {
  6261. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6262. this._isStencilOpDirty = false;
  6263. }
  6264. };
  6265. return _StencilState;
  6266. }());
  6267. Internals._StencilState = _StencilState;
  6268. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6269. })(BABYLON || (BABYLON = {}));
  6270. var BABYLON;
  6271. (function (BABYLON) {
  6272. var compileShader = function (gl, source, type, defines) {
  6273. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6274. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  6275. gl.compileShader(shader);
  6276. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6277. throw new Error(gl.getShaderInfoLog(shader));
  6278. }
  6279. return shader;
  6280. };
  6281. var HALF_FLOAT_OES = 0x8D61;
  6282. var getWebGLTextureType = function (gl, type) {
  6283. if (type === Engine.TEXTURETYPE_FLOAT) {
  6284. return gl.FLOAT;
  6285. }
  6286. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6287. // Add Half Float Constant.
  6288. return HALF_FLOAT_OES;
  6289. }
  6290. return gl.UNSIGNED_BYTE;
  6291. };
  6292. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6293. var magFilter = gl.NEAREST;
  6294. var minFilter = gl.NEAREST;
  6295. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6296. magFilter = gl.LINEAR;
  6297. if (generateMipMaps) {
  6298. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6299. }
  6300. else {
  6301. minFilter = gl.LINEAR;
  6302. }
  6303. }
  6304. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6305. magFilter = gl.LINEAR;
  6306. if (generateMipMaps) {
  6307. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6308. }
  6309. else {
  6310. minFilter = gl.LINEAR;
  6311. }
  6312. }
  6313. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6314. magFilter = gl.NEAREST;
  6315. if (generateMipMaps) {
  6316. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6317. }
  6318. else {
  6319. minFilter = gl.NEAREST;
  6320. }
  6321. }
  6322. return {
  6323. min: minFilter,
  6324. mag: magFilter
  6325. };
  6326. };
  6327. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6328. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6329. var engine = scene.getEngine();
  6330. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6331. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6332. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6333. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6334. texture._baseWidth = width;
  6335. texture._baseHeight = height;
  6336. texture._width = potWidth;
  6337. texture._height = potHeight;
  6338. texture.isReady = true;
  6339. processFunction(potWidth, potHeight);
  6340. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6341. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6342. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6343. if (!noMipmap && !isCompressed) {
  6344. gl.generateMipmap(gl.TEXTURE_2D);
  6345. }
  6346. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6347. engine.resetTextureCache();
  6348. scene._removePendingData(texture);
  6349. texture.onLoadedCallbacks.forEach(function (callback) {
  6350. callback();
  6351. });
  6352. texture.onLoadedCallbacks = [];
  6353. };
  6354. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6355. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6356. var img;
  6357. var onload = function () {
  6358. loadedImages[index] = img;
  6359. loadedImages._internalCount++;
  6360. scene._removePendingData(img);
  6361. if (loadedImages._internalCount === 6) {
  6362. onfinish(loadedImages);
  6363. }
  6364. };
  6365. var onerror = function () {
  6366. scene._removePendingData(img);
  6367. if (onErrorCallBack) {
  6368. onErrorCallBack();
  6369. }
  6370. };
  6371. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6372. scene._addPendingData(img);
  6373. };
  6374. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  6375. if (onError === void 0) { onError = null; }
  6376. var loadedImages = [];
  6377. loadedImages._internalCount = 0;
  6378. for (var index = 0; index < 6; index++) {
  6379. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  6380. }
  6381. };
  6382. var InstancingAttributeInfo = (function () {
  6383. function InstancingAttributeInfo() {
  6384. }
  6385. return InstancingAttributeInfo;
  6386. }());
  6387. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6388. var EngineCapabilities = (function () {
  6389. function EngineCapabilities() {
  6390. }
  6391. return EngineCapabilities;
  6392. }());
  6393. BABYLON.EngineCapabilities = EngineCapabilities;
  6394. /**
  6395. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6396. */
  6397. var Engine = (function () {
  6398. /**
  6399. * @constructor
  6400. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6401. * @param {boolean} [antialias] - enable antialias
  6402. * @param options - further options to be sent to the getContext function
  6403. */
  6404. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6405. var _this = this;
  6406. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  6407. // Public members
  6408. this.isFullscreen = false;
  6409. this.isPointerLock = false;
  6410. this.cullBackFaces = true;
  6411. this.renderEvenInBackground = true;
  6412. // To enable/disable IDB support and avoid XHR on .manifest
  6413. this.enableOfflineSupport = true;
  6414. this.scenes = new Array();
  6415. this._windowIsBackground = false;
  6416. this._webGLVersion = "1.0";
  6417. this._badOS = false;
  6418. this._drawCalls = new BABYLON.PerfCounter();
  6419. this._renderingQueueLaunched = false;
  6420. this._activeRenderLoops = [];
  6421. // FPS
  6422. this.fpsRange = 60;
  6423. this.previousFramesDuration = [];
  6424. this.fps = 60;
  6425. this.deltaTime = 0;
  6426. // States
  6427. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6428. this._stencilState = new BABYLON.Internals._StencilState();
  6429. this._alphaState = new BABYLON.Internals._AlphaState();
  6430. this._alphaMode = Engine.ALPHA_DISABLE;
  6431. // Cache
  6432. this._loadedTexturesCache = new Array();
  6433. this._maxTextureChannels = 16;
  6434. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6435. this._compiledEffects = {};
  6436. this._vertexAttribArraysEnabled = [];
  6437. this._uintIndicesCurrentlySet = false;
  6438. this._currentBoundBuffer = new Array();
  6439. this._currentBufferPointers = [];
  6440. this._currentInstanceLocations = new Array();
  6441. this._currentInstanceBuffers = new Array();
  6442. this._onVRFullScreenTriggered = function () {
  6443. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  6444. //get the old size before we change
  6445. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  6446. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  6447. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  6448. //But actually, no browser follow the specs...
  6449. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  6450. //get the width and height, change the render size
  6451. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  6452. var width, height;
  6453. _this.setHardwareScalingLevel(1);
  6454. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  6455. }
  6456. else {
  6457. //When the specs are implemented, need to uncomment this.
  6458. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  6459. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  6460. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  6461. _this._vrDisplayEnabled = undefined;
  6462. }
  6463. };
  6464. this._renderingCanvas = canvas;
  6465. this._externalData = new BABYLON.StringDictionary();
  6466. options = options || {};
  6467. if (antialias != null) {
  6468. options.antialias = antialias;
  6469. }
  6470. if (options.preserveDrawingBuffer === undefined) {
  6471. options.preserveDrawingBuffer = false;
  6472. }
  6473. // Checks if some of the format renders first to allow the use of webgl inspector.
  6474. var renderToFullFloat = this._canRenderToFloatTexture();
  6475. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  6476. // GL
  6477. //try {
  6478. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6479. // if (this._gl) {
  6480. // this._webGLVersion = "2.0";
  6481. // }
  6482. //} catch (e) {
  6483. // // Do nothing
  6484. //}
  6485. if (!this._gl) {
  6486. if (!canvas) {
  6487. throw new Error("The provided canvas is null or undefined.");
  6488. }
  6489. try {
  6490. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6491. }
  6492. catch (e) {
  6493. throw new Error("WebGL not supported");
  6494. }
  6495. }
  6496. if (!this._gl) {
  6497. throw new Error("WebGL not supported");
  6498. }
  6499. this._onBlur = function () {
  6500. _this._windowIsBackground = true;
  6501. };
  6502. this._onFocus = function () {
  6503. _this._windowIsBackground = false;
  6504. };
  6505. window.addEventListener("blur", this._onBlur);
  6506. window.addEventListener("focus", this._onFocus);
  6507. // Viewport
  6508. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6509. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6510. this.resize();
  6511. // Caps
  6512. this._isStencilEnable = options.stencil;
  6513. this._caps = new EngineCapabilities();
  6514. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6515. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6516. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6517. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6518. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6519. // Infos
  6520. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6521. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6522. if (rendererInfo != null) {
  6523. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6524. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6525. }
  6526. if (!this._glVendor) {
  6527. this._glVendor = "Unknown vendor";
  6528. }
  6529. if (!this._glRenderer) {
  6530. this._glRenderer = "Unknown renderer";
  6531. }
  6532. // Extensions
  6533. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6534. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6535. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6536. 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');
  6537. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6538. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6539. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6540. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6541. this._caps.highPrecisionShaderSupported = true;
  6542. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6543. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6544. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6545. this._caps.textureFloatRender = renderToFullFloat;
  6546. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6547. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6548. this._caps.textureHalfFloatRender = renderToHalfFloat;
  6549. if (this._gl.getShaderPrecisionFormat) {
  6550. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6551. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6552. }
  6553. // Depth buffer
  6554. this.setDepthBuffer(true);
  6555. this.setDepthFunctionToLessOrEqual();
  6556. this.setDepthWrite(true);
  6557. // Fullscreen
  6558. this._onFullscreenChange = function () {
  6559. if (document.fullscreen !== undefined) {
  6560. _this.isFullscreen = document.fullscreen;
  6561. }
  6562. else if (document.mozFullScreen !== undefined) {
  6563. _this.isFullscreen = document.mozFullScreen;
  6564. }
  6565. else if (document.webkitIsFullScreen !== undefined) {
  6566. _this.isFullscreen = document.webkitIsFullScreen;
  6567. }
  6568. else if (document.msIsFullScreen !== undefined) {
  6569. _this.isFullscreen = document.msIsFullScreen;
  6570. }
  6571. // Pointer lock
  6572. if (_this.isFullscreen && _this._pointerLockRequested) {
  6573. canvas.requestPointerLock = canvas.requestPointerLock ||
  6574. canvas.msRequestPointerLock ||
  6575. canvas.mozRequestPointerLock ||
  6576. canvas.webkitRequestPointerLock;
  6577. if (canvas.requestPointerLock) {
  6578. canvas.requestPointerLock();
  6579. }
  6580. }
  6581. };
  6582. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6583. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6584. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6585. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6586. // Pointer lock
  6587. this._onPointerLockChange = function () {
  6588. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6589. document.webkitPointerLockElement === canvas ||
  6590. document.msPointerLockElement === canvas ||
  6591. document.pointerLockElement === canvas);
  6592. };
  6593. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6594. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6595. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6596. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6597. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6598. Engine.audioEngine = new BABYLON.AudioEngine();
  6599. }
  6600. //default loading screen
  6601. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6602. //Load WebVR Devices
  6603. if (options.autoEnableWebVR) {
  6604. this.initWebVR();
  6605. }
  6606. //Detect if we are running on a faulty buggy OS.
  6607. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  6608. //ua sniffing is the tool of the devil.
  6609. this._badOS = regexp.test(navigator.userAgent);
  6610. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6611. }
  6612. Object.defineProperty(Engine, "NEVER", {
  6613. get: function () {
  6614. return Engine._NEVER;
  6615. },
  6616. enumerable: true,
  6617. configurable: true
  6618. });
  6619. Object.defineProperty(Engine, "ALWAYS", {
  6620. get: function () {
  6621. return Engine._ALWAYS;
  6622. },
  6623. enumerable: true,
  6624. configurable: true
  6625. });
  6626. Object.defineProperty(Engine, "LESS", {
  6627. get: function () {
  6628. return Engine._LESS;
  6629. },
  6630. enumerable: true,
  6631. configurable: true
  6632. });
  6633. Object.defineProperty(Engine, "EQUAL", {
  6634. get: function () {
  6635. return Engine._EQUAL;
  6636. },
  6637. enumerable: true,
  6638. configurable: true
  6639. });
  6640. Object.defineProperty(Engine, "LEQUAL", {
  6641. get: function () {
  6642. return Engine._LEQUAL;
  6643. },
  6644. enumerable: true,
  6645. configurable: true
  6646. });
  6647. Object.defineProperty(Engine, "GREATER", {
  6648. get: function () {
  6649. return Engine._GREATER;
  6650. },
  6651. enumerable: true,
  6652. configurable: true
  6653. });
  6654. Object.defineProperty(Engine, "GEQUAL", {
  6655. get: function () {
  6656. return Engine._GEQUAL;
  6657. },
  6658. enumerable: true,
  6659. configurable: true
  6660. });
  6661. Object.defineProperty(Engine, "NOTEQUAL", {
  6662. get: function () {
  6663. return Engine._NOTEQUAL;
  6664. },
  6665. enumerable: true,
  6666. configurable: true
  6667. });
  6668. Object.defineProperty(Engine, "KEEP", {
  6669. get: function () {
  6670. return Engine._KEEP;
  6671. },
  6672. enumerable: true,
  6673. configurable: true
  6674. });
  6675. Object.defineProperty(Engine, "REPLACE", {
  6676. get: function () {
  6677. return Engine._REPLACE;
  6678. },
  6679. enumerable: true,
  6680. configurable: true
  6681. });
  6682. Object.defineProperty(Engine, "INCR", {
  6683. get: function () {
  6684. return Engine._INCR;
  6685. },
  6686. enumerable: true,
  6687. configurable: true
  6688. });
  6689. Object.defineProperty(Engine, "DECR", {
  6690. get: function () {
  6691. return Engine._DECR;
  6692. },
  6693. enumerable: true,
  6694. configurable: true
  6695. });
  6696. Object.defineProperty(Engine, "INVERT", {
  6697. get: function () {
  6698. return Engine._INVERT;
  6699. },
  6700. enumerable: true,
  6701. configurable: true
  6702. });
  6703. Object.defineProperty(Engine, "INCR_WRAP", {
  6704. get: function () {
  6705. return Engine._INCR_WRAP;
  6706. },
  6707. enumerable: true,
  6708. configurable: true
  6709. });
  6710. Object.defineProperty(Engine, "DECR_WRAP", {
  6711. get: function () {
  6712. return Engine._DECR_WRAP;
  6713. },
  6714. enumerable: true,
  6715. configurable: true
  6716. });
  6717. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6718. get: function () {
  6719. return Engine._ALPHA_DISABLE;
  6720. },
  6721. enumerable: true,
  6722. configurable: true
  6723. });
  6724. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6725. get: function () {
  6726. return Engine._ALPHA_ONEONE;
  6727. },
  6728. enumerable: true,
  6729. configurable: true
  6730. });
  6731. Object.defineProperty(Engine, "ALPHA_ADD", {
  6732. get: function () {
  6733. return Engine._ALPHA_ADD;
  6734. },
  6735. enumerable: true,
  6736. configurable: true
  6737. });
  6738. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6739. get: function () {
  6740. return Engine._ALPHA_COMBINE;
  6741. },
  6742. enumerable: true,
  6743. configurable: true
  6744. });
  6745. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6746. get: function () {
  6747. return Engine._ALPHA_SUBTRACT;
  6748. },
  6749. enumerable: true,
  6750. configurable: true
  6751. });
  6752. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6753. get: function () {
  6754. return Engine._ALPHA_MULTIPLY;
  6755. },
  6756. enumerable: true,
  6757. configurable: true
  6758. });
  6759. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6760. get: function () {
  6761. return Engine._ALPHA_MAXIMIZED;
  6762. },
  6763. enumerable: true,
  6764. configurable: true
  6765. });
  6766. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6767. get: function () {
  6768. return Engine._DELAYLOADSTATE_NONE;
  6769. },
  6770. enumerable: true,
  6771. configurable: true
  6772. });
  6773. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6774. get: function () {
  6775. return Engine._DELAYLOADSTATE_LOADED;
  6776. },
  6777. enumerable: true,
  6778. configurable: true
  6779. });
  6780. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6781. get: function () {
  6782. return Engine._DELAYLOADSTATE_LOADING;
  6783. },
  6784. enumerable: true,
  6785. configurable: true
  6786. });
  6787. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6788. get: function () {
  6789. return Engine._DELAYLOADSTATE_NOTLOADED;
  6790. },
  6791. enumerable: true,
  6792. configurable: true
  6793. });
  6794. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6795. get: function () {
  6796. return Engine._TEXTUREFORMAT_ALPHA;
  6797. },
  6798. enumerable: true,
  6799. configurable: true
  6800. });
  6801. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6802. get: function () {
  6803. return Engine._TEXTUREFORMAT_LUMINANCE;
  6804. },
  6805. enumerable: true,
  6806. configurable: true
  6807. });
  6808. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6809. get: function () {
  6810. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6811. },
  6812. enumerable: true,
  6813. configurable: true
  6814. });
  6815. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6816. get: function () {
  6817. return Engine._TEXTUREFORMAT_RGB;
  6818. },
  6819. enumerable: true,
  6820. configurable: true
  6821. });
  6822. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6823. get: function () {
  6824. return Engine._TEXTUREFORMAT_RGBA;
  6825. },
  6826. enumerable: true,
  6827. configurable: true
  6828. });
  6829. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6830. get: function () {
  6831. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6832. },
  6833. enumerable: true,
  6834. configurable: true
  6835. });
  6836. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6837. get: function () {
  6838. return Engine._TEXTURETYPE_FLOAT;
  6839. },
  6840. enumerable: true,
  6841. configurable: true
  6842. });
  6843. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6844. get: function () {
  6845. return Engine._TEXTURETYPE_HALF_FLOAT;
  6846. },
  6847. enumerable: true,
  6848. configurable: true
  6849. });
  6850. Object.defineProperty(Engine, "Version", {
  6851. get: function () {
  6852. return "2.5.-beta";
  6853. },
  6854. enumerable: true,
  6855. configurable: true
  6856. });
  6857. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6858. get: function () {
  6859. return this._webGLVersion;
  6860. },
  6861. enumerable: true,
  6862. configurable: true
  6863. });
  6864. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  6865. /**
  6866. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  6867. */
  6868. get: function () {
  6869. return this._isStencilEnable;
  6870. },
  6871. enumerable: true,
  6872. configurable: true
  6873. });
  6874. Engine.prototype._prepareWorkingCanvas = function () {
  6875. if (this._workingCanvas) {
  6876. return;
  6877. }
  6878. this._workingCanvas = document.createElement("canvas");
  6879. this._workingContext = this._workingCanvas.getContext("2d");
  6880. };
  6881. Engine.prototype.resetTextureCache = function () {
  6882. for (var index = 0; index < this._maxTextureChannels; index++) {
  6883. this._activeTexturesCache[index] = null;
  6884. }
  6885. };
  6886. Engine.prototype.getGlInfo = function () {
  6887. return {
  6888. vendor: this._glVendor,
  6889. renderer: this._glRenderer,
  6890. version: this._glVersion
  6891. };
  6892. };
  6893. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6894. if (useScreen === void 0) { useScreen = false; }
  6895. var viewport = camera.viewport;
  6896. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6897. };
  6898. Engine.prototype.getRenderWidth = function (useScreen) {
  6899. if (useScreen === void 0) { useScreen = false; }
  6900. if (!useScreen && this._currentRenderTarget) {
  6901. return this._currentRenderTarget._width;
  6902. }
  6903. return this._renderingCanvas.width;
  6904. };
  6905. Engine.prototype.getRenderHeight = function (useScreen) {
  6906. if (useScreen === void 0) { useScreen = false; }
  6907. if (!useScreen && this._currentRenderTarget) {
  6908. return this._currentRenderTarget._height;
  6909. }
  6910. return this._renderingCanvas.height;
  6911. };
  6912. Engine.prototype.getRenderingCanvas = function () {
  6913. return this._renderingCanvas;
  6914. };
  6915. Engine.prototype.getRenderingCanvasClientRect = function () {
  6916. return this._renderingCanvas.getBoundingClientRect();
  6917. };
  6918. Engine.prototype.setHardwareScalingLevel = function (level) {
  6919. this._hardwareScalingLevel = level;
  6920. this.resize();
  6921. };
  6922. Engine.prototype.getHardwareScalingLevel = function () {
  6923. return this._hardwareScalingLevel;
  6924. };
  6925. Engine.prototype.getLoadedTexturesCache = function () {
  6926. return this._loadedTexturesCache;
  6927. };
  6928. Engine.prototype.getCaps = function () {
  6929. return this._caps;
  6930. };
  6931. Object.defineProperty(Engine.prototype, "drawCalls", {
  6932. get: function () {
  6933. return this._drawCalls.current;
  6934. },
  6935. enumerable: true,
  6936. configurable: true
  6937. });
  6938. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  6939. get: function () {
  6940. return this._drawCalls;
  6941. },
  6942. enumerable: true,
  6943. configurable: true
  6944. });
  6945. Engine.prototype.getDepthFunction = function () {
  6946. return this._depthCullingState.depthFunc;
  6947. };
  6948. Engine.prototype.setDepthFunction = function (depthFunc) {
  6949. this._depthCullingState.depthFunc = depthFunc;
  6950. };
  6951. Engine.prototype.setDepthFunctionToGreater = function () {
  6952. this._depthCullingState.depthFunc = this._gl.GREATER;
  6953. };
  6954. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6955. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6956. };
  6957. Engine.prototype.setDepthFunctionToLess = function () {
  6958. this._depthCullingState.depthFunc = this._gl.LESS;
  6959. };
  6960. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6961. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6962. };
  6963. Engine.prototype.getStencilBuffer = function () {
  6964. return this._stencilState.stencilTest;
  6965. };
  6966. Engine.prototype.setStencilBuffer = function (enable) {
  6967. this._stencilState.stencilTest = enable;
  6968. };
  6969. Engine.prototype.getStencilMask = function () {
  6970. return this._stencilState.stencilMask;
  6971. };
  6972. Engine.prototype.setStencilMask = function (mask) {
  6973. this._stencilState.stencilMask = mask;
  6974. };
  6975. Engine.prototype.getStencilFunction = function () {
  6976. return this._stencilState.stencilFunc;
  6977. };
  6978. Engine.prototype.getStencilFunctionReference = function () {
  6979. return this._stencilState.stencilFuncRef;
  6980. };
  6981. Engine.prototype.getStencilFunctionMask = function () {
  6982. return this._stencilState.stencilFuncMask;
  6983. };
  6984. Engine.prototype.setStencilFunction = function (stencilFunc) {
  6985. this._stencilState.stencilFunc = stencilFunc;
  6986. };
  6987. Engine.prototype.setStencilFunctionReference = function (reference) {
  6988. this._stencilState.stencilFuncRef = reference;
  6989. };
  6990. Engine.prototype.setStencilFunctionMask = function (mask) {
  6991. this._stencilState.stencilFuncMask = mask;
  6992. };
  6993. Engine.prototype.getStencilOperationFail = function () {
  6994. return this._stencilState.stencilOpStencilFail;
  6995. };
  6996. Engine.prototype.getStencilOperationDepthFail = function () {
  6997. return this._stencilState.stencilOpDepthFail;
  6998. };
  6999. Engine.prototype.getStencilOperationPass = function () {
  7000. return this._stencilState.stencilOpStencilDepthPass;
  7001. };
  7002. Engine.prototype.setStencilOperationFail = function (operation) {
  7003. this._stencilState.stencilOpStencilFail = operation;
  7004. };
  7005. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7006. this._stencilState.stencilOpDepthFail = operation;
  7007. };
  7008. Engine.prototype.setStencilOperationPass = function (operation) {
  7009. this._stencilState.stencilOpStencilDepthPass = operation;
  7010. };
  7011. /**
  7012. * stop executing a render loop function and remove it from the execution array
  7013. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7014. */
  7015. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7016. if (!renderFunction) {
  7017. this._activeRenderLoops = [];
  7018. return;
  7019. }
  7020. var index = this._activeRenderLoops.indexOf(renderFunction);
  7021. if (index >= 0) {
  7022. this._activeRenderLoops.splice(index, 1);
  7023. }
  7024. };
  7025. Engine.prototype._renderLoop = function () {
  7026. var shouldRender = true;
  7027. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7028. shouldRender = false;
  7029. }
  7030. if (shouldRender) {
  7031. // Start new frame
  7032. this.beginFrame();
  7033. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7034. var renderFunction = this._activeRenderLoops[index];
  7035. renderFunction();
  7036. }
  7037. // Present
  7038. this.endFrame();
  7039. }
  7040. if (this._activeRenderLoops.length > 0) {
  7041. // Register new frame
  7042. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7043. }
  7044. else {
  7045. this._renderingQueueLaunched = false;
  7046. }
  7047. };
  7048. /**
  7049. * Register and execute a render loop. The engine can have more than one render function.
  7050. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7051. * @example
  7052. * engine.runRenderLoop(function () {
  7053. * scene.render()
  7054. * })
  7055. */
  7056. Engine.prototype.runRenderLoop = function (renderFunction) {
  7057. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7058. return;
  7059. }
  7060. this._activeRenderLoops.push(renderFunction);
  7061. if (!this._renderingQueueLaunched) {
  7062. this._renderingQueueLaunched = true;
  7063. this._bindedRenderFunction = this._renderLoop.bind(this);
  7064. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7065. }
  7066. };
  7067. /**
  7068. * Toggle full screen mode.
  7069. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7070. * @param {any} options - an options object to be sent to the requestFullscreen function
  7071. */
  7072. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7073. if (this.isFullscreen) {
  7074. BABYLON.Tools.ExitFullscreen();
  7075. }
  7076. else {
  7077. this._pointerLockRequested = requestPointerLock;
  7078. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7079. }
  7080. };
  7081. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7082. if (stencil === void 0) { stencil = false; }
  7083. this.applyStates();
  7084. var mode = 0;
  7085. if (backBuffer) {
  7086. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  7087. mode |= this._gl.COLOR_BUFFER_BIT;
  7088. }
  7089. if (depth) {
  7090. this._gl.clearDepth(1.0);
  7091. mode |= this._gl.DEPTH_BUFFER_BIT;
  7092. }
  7093. if (stencil) {
  7094. this._gl.clearStencil(0);
  7095. mode |= this._gl.STENCIL_BUFFER_BIT;
  7096. }
  7097. this._gl.clear(mode);
  7098. };
  7099. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7100. var gl = this._gl;
  7101. // Save state
  7102. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7103. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7104. // Change state
  7105. gl.enable(gl.SCISSOR_TEST);
  7106. gl.scissor(x, y, width, height);
  7107. // Clear
  7108. this.clear(clearColor, true, true, true);
  7109. // Restore state
  7110. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7111. if (curScissor === true) {
  7112. gl.enable(gl.SCISSOR_TEST);
  7113. }
  7114. else {
  7115. gl.disable(gl.SCISSOR_TEST);
  7116. }
  7117. };
  7118. /**
  7119. * Set the WebGL's viewport
  7120. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7121. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7122. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7123. */
  7124. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7125. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  7126. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  7127. var x = viewport.x || 0;
  7128. var y = viewport.y || 0;
  7129. this._cachedViewport = viewport;
  7130. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7131. };
  7132. /**
  7133. * Directly set the WebGL Viewport
  7134. * The x, y, width & height are directly passed to the WebGL call
  7135. * @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.
  7136. */
  7137. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7138. var currentViewport = this._cachedViewport;
  7139. this._cachedViewport = null;
  7140. this._gl.viewport(x, y, width, height);
  7141. return currentViewport;
  7142. };
  7143. Engine.prototype.beginFrame = function () {
  7144. this._measureFps();
  7145. };
  7146. Engine.prototype.endFrame = function () {
  7147. //force a flush in case we are using a bad OS.
  7148. if (this._badOS) {
  7149. this.flushFramebuffer();
  7150. }
  7151. //submit frame to the vr device, if enabled
  7152. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7153. this._vrDisplayEnabled.submitFrame();
  7154. }
  7155. };
  7156. /**
  7157. * resize the view according to the canvas' size.
  7158. * @example
  7159. * window.addEventListener("resize", function () {
  7160. * engine.resize();
  7161. * });
  7162. */
  7163. Engine.prototype.resize = function () {
  7164. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7165. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7166. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7167. for (var index = 0; index < this.scenes.length; index++) {
  7168. var scene = this.scenes[index];
  7169. if (BABYLON.DebugLayer && scene.debugLayer.isVisible()) {
  7170. scene.debugLayer._syncPositions();
  7171. }
  7172. }
  7173. };
  7174. /**
  7175. * force a specific size of the canvas
  7176. * @param {number} width - the new canvas' width
  7177. * @param {number} height - the new canvas' height
  7178. */
  7179. Engine.prototype.setSize = function (width, height) {
  7180. this._renderingCanvas.width = width;
  7181. this._renderingCanvas.height = height;
  7182. for (var index = 0; index < this.scenes.length; index++) {
  7183. var scene = this.scenes[index];
  7184. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7185. var cam = scene.cameras[camIndex];
  7186. cam._currentRenderId = 0;
  7187. }
  7188. }
  7189. };
  7190. //WebVR functions
  7191. Engine.prototype.initWebVR = function () {
  7192. if (!this.vrDisplaysPromise) {
  7193. this._getVRDisplays();
  7194. }
  7195. };
  7196. Engine.prototype.enableVR = function (vrDevice) {
  7197. this._vrDisplayEnabled = vrDevice;
  7198. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7199. };
  7200. Engine.prototype.disableVR = function () {
  7201. if (this._vrDisplayEnabled) {
  7202. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7203. }
  7204. };
  7205. Engine.prototype._getVRDisplays = function () {
  7206. var _this = this;
  7207. var getWebVRDevices = function (devices) {
  7208. var size = devices.length;
  7209. var i = 0;
  7210. _this._vrDisplays = devices.filter(function (device) {
  7211. return devices[i] instanceof VRDisplay;
  7212. });
  7213. return _this._vrDisplays;
  7214. };
  7215. //using a key due to typescript
  7216. if (navigator.getVRDisplays) {
  7217. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7218. }
  7219. };
  7220. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7221. this._currentRenderTarget = texture;
  7222. this.bindUnboundFramebuffer(texture._framebuffer);
  7223. var gl = this._gl;
  7224. if (texture.isCube) {
  7225. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7226. }
  7227. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7228. this.wipeCaches();
  7229. };
  7230. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7231. if (this._currentFramebuffer !== framebuffer) {
  7232. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7233. this._currentFramebuffer = framebuffer;
  7234. }
  7235. };
  7236. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  7237. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7238. this._currentRenderTarget = null;
  7239. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7240. var gl = this._gl;
  7241. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7242. gl.generateMipmap(gl.TEXTURE_2D);
  7243. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7244. }
  7245. this.bindUnboundFramebuffer(null);
  7246. };
  7247. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7248. if (texture.generateMipMaps) {
  7249. var gl = this._gl;
  7250. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7251. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7252. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7253. }
  7254. };
  7255. Engine.prototype.flushFramebuffer = function () {
  7256. this._gl.flush();
  7257. };
  7258. Engine.prototype.restoreDefaultFramebuffer = function () {
  7259. this._currentRenderTarget = null;
  7260. this.bindUnboundFramebuffer(null);
  7261. this.setViewport(this._cachedViewport);
  7262. this.wipeCaches();
  7263. };
  7264. // VBOs
  7265. Engine.prototype._resetVertexBufferBinding = function () {
  7266. this.bindArrayBuffer(null);
  7267. this._cachedVertexBuffers = null;
  7268. };
  7269. Engine.prototype.createVertexBuffer = function (vertices) {
  7270. var vbo = this._gl.createBuffer();
  7271. this.bindArrayBuffer(vbo);
  7272. if (vertices instanceof Float32Array) {
  7273. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  7274. }
  7275. else {
  7276. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  7277. }
  7278. this._resetVertexBufferBinding();
  7279. vbo.references = 1;
  7280. return vbo;
  7281. };
  7282. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  7283. var vbo = this._gl.createBuffer();
  7284. this.bindArrayBuffer(vbo);
  7285. if (vertices instanceof Float32Array) {
  7286. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  7287. }
  7288. else {
  7289. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  7290. }
  7291. this._resetVertexBufferBinding();
  7292. vbo.references = 1;
  7293. return vbo;
  7294. };
  7295. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  7296. this.bindArrayBuffer(vertexBuffer);
  7297. if (offset === undefined) {
  7298. offset = 0;
  7299. }
  7300. if (count === undefined) {
  7301. if (vertices instanceof Float32Array) {
  7302. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  7303. }
  7304. else {
  7305. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  7306. }
  7307. }
  7308. else {
  7309. if (vertices instanceof Float32Array) {
  7310. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  7311. }
  7312. else {
  7313. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  7314. }
  7315. }
  7316. this._resetVertexBufferBinding();
  7317. };
  7318. Engine.prototype._resetIndexBufferBinding = function () {
  7319. this.bindIndexBuffer(null);
  7320. this._cachedIndexBuffer = null;
  7321. };
  7322. Engine.prototype.createIndexBuffer = function (indices) {
  7323. var vbo = this._gl.createBuffer();
  7324. this.bindIndexBuffer(vbo);
  7325. // Check for 32 bits indices
  7326. var arrayBuffer;
  7327. var need32Bits = false;
  7328. if (this._caps.uintIndices) {
  7329. for (var index = 0; index < indices.length; index++) {
  7330. if (indices[index] > 65535) {
  7331. need32Bits = true;
  7332. break;
  7333. }
  7334. }
  7335. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  7336. }
  7337. else {
  7338. arrayBuffer = new Uint16Array(indices);
  7339. }
  7340. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  7341. this._resetIndexBufferBinding();
  7342. vbo.references = 1;
  7343. vbo.is32Bits = need32Bits;
  7344. return vbo;
  7345. };
  7346. Engine.prototype.bindArrayBuffer = function (buffer) {
  7347. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  7348. };
  7349. Engine.prototype.bindIndexBuffer = function (buffer) {
  7350. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  7351. };
  7352. Engine.prototype.bindBuffer = function (buffer, target) {
  7353. if (this._currentBoundBuffer[target] !== buffer) {
  7354. this._gl.bindBuffer(target, buffer);
  7355. this._currentBoundBuffer[target] = buffer;
  7356. }
  7357. };
  7358. Engine.prototype.updateArrayBuffer = function (data) {
  7359. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7360. };
  7361. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  7362. var pointer = this._currentBufferPointers[indx];
  7363. var changed = false;
  7364. if (!pointer) {
  7365. changed = true;
  7366. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  7367. }
  7368. else {
  7369. if (pointer.buffer !== buffer) {
  7370. pointer.buffer = buffer;
  7371. changed = true;
  7372. }
  7373. if (pointer.size !== size) {
  7374. pointer.size = size;
  7375. changed = true;
  7376. }
  7377. if (pointer.type !== type) {
  7378. pointer.type = type;
  7379. changed = true;
  7380. }
  7381. if (pointer.normalized !== normalized) {
  7382. pointer.normalized = normalized;
  7383. changed = true;
  7384. }
  7385. if (pointer.stride !== stride) {
  7386. pointer.stride = stride;
  7387. changed = true;
  7388. }
  7389. if (pointer.offset !== offset) {
  7390. pointer.offset = offset;
  7391. changed = true;
  7392. }
  7393. }
  7394. if (changed) {
  7395. this.bindArrayBuffer(buffer);
  7396. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  7397. }
  7398. };
  7399. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  7400. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  7401. this._cachedVertexBuffers = vertexBuffer;
  7402. this._cachedEffectForVertexBuffers = effect;
  7403. var attributesCount = effect.getAttributesCount();
  7404. var offset = 0;
  7405. for (var index = 0; index < attributesCount; index++) {
  7406. if (index < vertexDeclaration.length) {
  7407. var order = effect.getAttributeLocation(index);
  7408. if (order >= 0) {
  7409. if (!this._vertexAttribArraysEnabled[order]) {
  7410. this._gl.enableVertexAttribArray(order);
  7411. this._vertexAttribArraysEnabled[order] = true;
  7412. }
  7413. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7414. }
  7415. offset += vertexDeclaration[index] * 4;
  7416. }
  7417. else {
  7418. //disable effect attributes that have no data
  7419. var order = effect.getAttributeLocation(index);
  7420. if (this._vertexAttribArraysEnabled[order]) {
  7421. this._gl.disableVertexAttribArray(order);
  7422. this._vertexAttribArraysEnabled[order] = false;
  7423. }
  7424. }
  7425. }
  7426. }
  7427. if (this._cachedIndexBuffer !== indexBuffer) {
  7428. this._cachedIndexBuffer = indexBuffer;
  7429. this.bindIndexBuffer(indexBuffer);
  7430. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7431. }
  7432. };
  7433. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7434. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7435. this._cachedVertexBuffers = vertexBuffers;
  7436. this._cachedEffectForVertexBuffers = effect;
  7437. var attributes = effect.getAttributesNames();
  7438. for (var index = 0; index < attributes.length; index++) {
  7439. var order = effect.getAttributeLocation(index);
  7440. if (order >= 0) {
  7441. var vertexBuffer = vertexBuffers[attributes[index]];
  7442. if (!vertexBuffer) {
  7443. if (this._vertexAttribArraysEnabled[order]) {
  7444. this._gl.disableVertexAttribArray(order);
  7445. this._vertexAttribArraysEnabled[order] = false;
  7446. }
  7447. continue;
  7448. }
  7449. if (!this._vertexAttribArraysEnabled[order]) {
  7450. this._gl.enableVertexAttribArray(order);
  7451. this._vertexAttribArraysEnabled[order] = true;
  7452. }
  7453. var buffer = vertexBuffer.getBuffer();
  7454. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7455. if (vertexBuffer.getIsInstanced()) {
  7456. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  7457. this._currentInstanceLocations.push(order);
  7458. this._currentInstanceBuffers.push(buffer);
  7459. }
  7460. }
  7461. }
  7462. }
  7463. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  7464. this._cachedIndexBuffer = indexBuffer;
  7465. this.bindIndexBuffer(indexBuffer);
  7466. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7467. }
  7468. };
  7469. Engine.prototype.unbindInstanceAttributes = function () {
  7470. var boundBuffer;
  7471. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7472. var instancesBuffer = this._currentInstanceBuffers[i];
  7473. if (boundBuffer != instancesBuffer) {
  7474. boundBuffer = instancesBuffer;
  7475. this.bindArrayBuffer(instancesBuffer);
  7476. }
  7477. var offsetLocation = this._currentInstanceLocations[i];
  7478. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  7479. }
  7480. this._currentInstanceBuffers.length = 0;
  7481. this._currentInstanceLocations.length = 0;
  7482. };
  7483. Engine.prototype._releaseBuffer = function (buffer) {
  7484. buffer.references--;
  7485. if (buffer.references === 0) {
  7486. this._gl.deleteBuffer(buffer);
  7487. return true;
  7488. }
  7489. return false;
  7490. };
  7491. Engine.prototype.createInstancesBuffer = function (capacity) {
  7492. var buffer = this._gl.createBuffer();
  7493. buffer.capacity = capacity;
  7494. this.bindArrayBuffer(buffer);
  7495. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7496. return buffer;
  7497. };
  7498. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7499. this._gl.deleteBuffer(buffer);
  7500. };
  7501. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7502. this.bindArrayBuffer(instancesBuffer);
  7503. if (data) {
  7504. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7505. }
  7506. if (offsetLocations[0].index !== undefined) {
  7507. var stride = 0;
  7508. for (var i = 0; i < offsetLocations.length; i++) {
  7509. var ai = offsetLocations[i];
  7510. stride += ai.attributeSize * 4;
  7511. }
  7512. for (var i = 0; i < offsetLocations.length; i++) {
  7513. var ai = offsetLocations[i];
  7514. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7515. this._gl.enableVertexAttribArray(ai.index);
  7516. this._vertexAttribArraysEnabled[ai.index] = true;
  7517. }
  7518. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7519. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  7520. this._currentInstanceLocations.push(ai.index);
  7521. this._currentInstanceBuffers.push(instancesBuffer);
  7522. }
  7523. }
  7524. else {
  7525. for (var index = 0; index < 4; index++) {
  7526. var offsetLocation = offsetLocations[index];
  7527. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7528. this._gl.enableVertexAttribArray(offsetLocation);
  7529. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7530. }
  7531. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7532. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  7533. this._currentInstanceLocations.push(offsetLocation);
  7534. this._currentInstanceBuffers.push(instancesBuffer);
  7535. }
  7536. }
  7537. };
  7538. Engine.prototype.applyStates = function () {
  7539. this._depthCullingState.apply(this._gl);
  7540. this._stencilState.apply(this._gl);
  7541. this._alphaState.apply(this._gl);
  7542. };
  7543. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7544. // Apply states
  7545. this.applyStates();
  7546. this._drawCalls.addCount(1, false);
  7547. // Render
  7548. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7549. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7550. if (instancesCount) {
  7551. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7552. return;
  7553. }
  7554. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7555. };
  7556. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7557. // Apply states
  7558. this.applyStates();
  7559. this._drawCalls.addCount(1, false);
  7560. if (instancesCount) {
  7561. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7562. return;
  7563. }
  7564. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7565. };
  7566. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7567. // Apply states
  7568. this.applyStates();
  7569. this._drawCalls.addCount(1, false);
  7570. if (instancesCount) {
  7571. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7572. return;
  7573. }
  7574. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7575. };
  7576. // Shaders
  7577. Engine.prototype._releaseEffect = function (effect) {
  7578. if (this._compiledEffects[effect._key]) {
  7579. delete this._compiledEffects[effect._key];
  7580. if (effect.getProgram()) {
  7581. this._gl.deleteProgram(effect.getProgram());
  7582. }
  7583. }
  7584. };
  7585. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7586. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7587. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7588. var name = vertex + "+" + fragment + "@" + defines;
  7589. if (this._compiledEffects[name]) {
  7590. return this._compiledEffects[name];
  7591. }
  7592. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7593. effect._key = name;
  7594. this._compiledEffects[name] = effect;
  7595. return effect;
  7596. };
  7597. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7598. if (uniformsNames === void 0) { uniformsNames = []; }
  7599. if (samplers === void 0) { samplers = []; }
  7600. if (defines === void 0) { defines = ""; }
  7601. return this.createEffect({
  7602. vertex: "particles",
  7603. fragmentElement: fragmentName
  7604. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7605. };
  7606. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7607. context = context || this._gl;
  7608. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  7609. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  7610. var shaderProgram = context.createProgram();
  7611. context.attachShader(shaderProgram, vertexShader);
  7612. context.attachShader(shaderProgram, fragmentShader);
  7613. context.linkProgram(shaderProgram);
  7614. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7615. if (!linked) {
  7616. var error = context.getProgramInfoLog(shaderProgram);
  7617. if (error) {
  7618. throw new Error(error);
  7619. }
  7620. }
  7621. context.deleteShader(vertexShader);
  7622. context.deleteShader(fragmentShader);
  7623. return shaderProgram;
  7624. };
  7625. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7626. var results = [];
  7627. for (var index = 0; index < uniformsNames.length; index++) {
  7628. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7629. }
  7630. return results;
  7631. };
  7632. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7633. var results = [];
  7634. for (var index = 0; index < attributesNames.length; index++) {
  7635. try {
  7636. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7637. }
  7638. catch (e) {
  7639. results.push(-1);
  7640. }
  7641. }
  7642. return results;
  7643. };
  7644. Engine.prototype.enableEffect = function (effect) {
  7645. //if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  7646. // if (effect && effect.onBind) {
  7647. // effect.onBind(effect);
  7648. // }
  7649. // return;
  7650. //}
  7651. // Use program
  7652. this.setProgram(effect.getProgram());
  7653. this._currentEffect = effect;
  7654. if (effect.onBind) {
  7655. effect.onBind(effect);
  7656. }
  7657. };
  7658. Engine.prototype.setIntArray = function (uniform, array) {
  7659. if (!uniform)
  7660. return;
  7661. this._gl.uniform1iv(uniform, array);
  7662. };
  7663. Engine.prototype.setIntArray2 = function (uniform, array) {
  7664. if (!uniform || array.length % 2 !== 0)
  7665. return;
  7666. this._gl.uniform2iv(uniform, array);
  7667. };
  7668. Engine.prototype.setIntArray3 = function (uniform, array) {
  7669. if (!uniform || array.length % 3 !== 0)
  7670. return;
  7671. this._gl.uniform3iv(uniform, array);
  7672. };
  7673. Engine.prototype.setIntArray4 = function (uniform, array) {
  7674. if (!uniform || array.length % 4 !== 0)
  7675. return;
  7676. this._gl.uniform4iv(uniform, array);
  7677. };
  7678. Engine.prototype.setFloatArray = function (uniform, array) {
  7679. if (!uniform)
  7680. return;
  7681. this._gl.uniform1fv(uniform, array);
  7682. };
  7683. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7684. if (!uniform || array.length % 2 !== 0)
  7685. return;
  7686. this._gl.uniform2fv(uniform, array);
  7687. };
  7688. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7689. if (!uniform || array.length % 3 !== 0)
  7690. return;
  7691. this._gl.uniform3fv(uniform, array);
  7692. };
  7693. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7694. if (!uniform || array.length % 4 !== 0)
  7695. return;
  7696. this._gl.uniform4fv(uniform, array);
  7697. };
  7698. Engine.prototype.setArray = function (uniform, array) {
  7699. if (!uniform)
  7700. return;
  7701. this._gl.uniform1fv(uniform, array);
  7702. };
  7703. Engine.prototype.setArray2 = function (uniform, array) {
  7704. if (!uniform || array.length % 2 !== 0)
  7705. return;
  7706. this._gl.uniform2fv(uniform, array);
  7707. };
  7708. Engine.prototype.setArray3 = function (uniform, array) {
  7709. if (!uniform || array.length % 3 !== 0)
  7710. return;
  7711. this._gl.uniform3fv(uniform, array);
  7712. };
  7713. Engine.prototype.setArray4 = function (uniform, array) {
  7714. if (!uniform || array.length % 4 !== 0)
  7715. return;
  7716. this._gl.uniform4fv(uniform, array);
  7717. };
  7718. Engine.prototype.setMatrices = function (uniform, matrices) {
  7719. if (!uniform)
  7720. return;
  7721. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7722. };
  7723. Engine.prototype.setMatrix = function (uniform, matrix) {
  7724. if (!uniform)
  7725. return;
  7726. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7727. };
  7728. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7729. if (!uniform)
  7730. return;
  7731. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7732. };
  7733. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7734. if (!uniform)
  7735. return;
  7736. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7737. };
  7738. Engine.prototype.setFloat = function (uniform, value) {
  7739. if (!uniform)
  7740. return;
  7741. this._gl.uniform1f(uniform, value);
  7742. };
  7743. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7744. if (!uniform)
  7745. return;
  7746. this._gl.uniform2f(uniform, x, y);
  7747. };
  7748. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7749. if (!uniform)
  7750. return;
  7751. this._gl.uniform3f(uniform, x, y, z);
  7752. };
  7753. Engine.prototype.setBool = function (uniform, bool) {
  7754. if (!uniform)
  7755. return;
  7756. this._gl.uniform1i(uniform, bool);
  7757. };
  7758. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7759. if (!uniform)
  7760. return;
  7761. this._gl.uniform4f(uniform, x, y, z, w);
  7762. };
  7763. Engine.prototype.setColor3 = function (uniform, color3) {
  7764. if (!uniform)
  7765. return;
  7766. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7767. };
  7768. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7769. if (!uniform)
  7770. return;
  7771. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7772. };
  7773. // States
  7774. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7775. if (zOffset === void 0) { zOffset = 0; }
  7776. if (reverseSide === void 0) { reverseSide = false; }
  7777. // Culling
  7778. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7779. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7780. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7781. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7782. if (culling) {
  7783. this._depthCullingState.cullFace = cullFace;
  7784. this._depthCullingState.cull = true;
  7785. }
  7786. else {
  7787. this._depthCullingState.cull = false;
  7788. }
  7789. }
  7790. // Z offset
  7791. this._depthCullingState.zOffset = zOffset;
  7792. };
  7793. Engine.prototype.setDepthBuffer = function (enable) {
  7794. this._depthCullingState.depthTest = enable;
  7795. };
  7796. Engine.prototype.getDepthWrite = function () {
  7797. return this._depthCullingState.depthMask;
  7798. };
  7799. Engine.prototype.setDepthWrite = function (enable) {
  7800. this._depthCullingState.depthMask = enable;
  7801. };
  7802. Engine.prototype.setColorWrite = function (enable) {
  7803. this._gl.colorMask(enable, enable, enable, enable);
  7804. };
  7805. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7806. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7807. if (this._alphaMode === mode) {
  7808. return;
  7809. }
  7810. switch (mode) {
  7811. case Engine.ALPHA_DISABLE:
  7812. this._alphaState.alphaBlend = false;
  7813. break;
  7814. case Engine.ALPHA_COMBINE:
  7815. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7816. this._alphaState.alphaBlend = true;
  7817. break;
  7818. case Engine.ALPHA_ONEONE:
  7819. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7820. this._alphaState.alphaBlend = true;
  7821. break;
  7822. case Engine.ALPHA_ADD:
  7823. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7824. this._alphaState.alphaBlend = true;
  7825. break;
  7826. case Engine.ALPHA_SUBTRACT:
  7827. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7828. this._alphaState.alphaBlend = true;
  7829. break;
  7830. case Engine.ALPHA_MULTIPLY:
  7831. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7832. this._alphaState.alphaBlend = true;
  7833. break;
  7834. case Engine.ALPHA_MAXIMIZED:
  7835. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7836. this._alphaState.alphaBlend = true;
  7837. break;
  7838. }
  7839. if (!noDepthWriteChange) {
  7840. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7841. }
  7842. this._alphaMode = mode;
  7843. };
  7844. Engine.prototype.getAlphaMode = function () {
  7845. return this._alphaMode;
  7846. };
  7847. Engine.prototype.setAlphaTesting = function (enable) {
  7848. this._alphaTest = enable;
  7849. };
  7850. Engine.prototype.getAlphaTesting = function () {
  7851. return this._alphaTest;
  7852. };
  7853. // Textures
  7854. Engine.prototype.wipeCaches = function () {
  7855. this.resetTextureCache();
  7856. this._currentEffect = null;
  7857. this._stencilState.reset();
  7858. this._depthCullingState.reset();
  7859. this.setDepthFunctionToLessOrEqual();
  7860. this._alphaState.reset();
  7861. this._cachedVertexBuffers = null;
  7862. this._cachedIndexBuffer = null;
  7863. this._cachedEffectForVertexBuffers = null;
  7864. };
  7865. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7866. var gl = this._gl;
  7867. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7868. var magFilter = gl.NEAREST;
  7869. var minFilter = gl.NEAREST;
  7870. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7871. magFilter = gl.LINEAR;
  7872. minFilter = gl.LINEAR;
  7873. }
  7874. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7875. magFilter = gl.LINEAR;
  7876. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7877. }
  7878. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  7879. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  7880. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7881. texture.samplingMode = samplingMode;
  7882. };
  7883. Engine.prototype.createTexture = function (urlOrList, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  7884. var _this = this;
  7885. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7886. if (onLoad === void 0) { onLoad = null; }
  7887. if (onError === void 0) { onError = null; }
  7888. if (buffer === void 0) { buffer = null; }
  7889. var texture = this._gl.createTexture();
  7890. var url = ((urlOrList.constructor === Array) ? urlOrList[0] : urlOrList);
  7891. var extension;
  7892. var fromData = false;
  7893. if (url.substr(0, 5) === "data:") {
  7894. fromData = true;
  7895. }
  7896. if (!fromData)
  7897. extension = url.substr(url.length - 4, 4).toLowerCase();
  7898. else {
  7899. var oldUrl = url;
  7900. fromData = oldUrl.split(':');
  7901. url = oldUrl;
  7902. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  7903. }
  7904. var isDDS = (extension === ".dds");
  7905. var isTGA = (extension === ".tga");
  7906. scene._addPendingData(texture);
  7907. texture.url = url;
  7908. texture.noMipmap = noMipmap;
  7909. texture.references = 1;
  7910. texture.samplingMode = samplingMode;
  7911. texture.onLoadedCallbacks = [onLoad];
  7912. this._loadedTexturesCache.push(texture);
  7913. var onerror = function () {
  7914. scene._removePendingData(texture);
  7915. if (onError) {
  7916. onError();
  7917. }
  7918. };
  7919. var callback;
  7920. if (isTGA) {
  7921. callback = function (arrayBuffer) {
  7922. var data = new Uint8Array(arrayBuffer);
  7923. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  7924. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  7925. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  7926. }, samplingMode);
  7927. };
  7928. if (!(fromData instanceof Array))
  7929. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  7930. callback(arrayBuffer);
  7931. }, null, scene.database, true, onerror);
  7932. else
  7933. callback(buffer);
  7934. }
  7935. else if (isDDS) {
  7936. if (!this.getCaps().s3tc) {
  7937. if (urlOrList instanceof Array) {
  7938. var newList = urlOrList.slice(1);
  7939. if (newList.length > 0) {
  7940. return this.createTexture(newList, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer);
  7941. }
  7942. }
  7943. onerror();
  7944. return null;
  7945. }
  7946. callback = function (data) {
  7947. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7948. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  7949. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  7950. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  7951. }, samplingMode);
  7952. };
  7953. if (!(fromData instanceof Array))
  7954. BABYLON.Tools.LoadFile(url, function (data) {
  7955. callback(data);
  7956. }, null, scene.database, true, onerror);
  7957. else
  7958. callback(buffer);
  7959. }
  7960. else {
  7961. var onload = function (img) {
  7962. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  7963. var isPot = (img.width === potWidth && img.height === potHeight);
  7964. if (!isPot) {
  7965. _this._prepareWorkingCanvas();
  7966. _this._workingCanvas.width = potWidth;
  7967. _this._workingCanvas.height = potHeight;
  7968. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7969. _this._workingContext.imageSmoothingEnabled = false;
  7970. _this._workingContext.mozImageSmoothingEnabled = false;
  7971. _this._workingContext.oImageSmoothingEnabled = false;
  7972. _this._workingContext.webkitImageSmoothingEnabled = false;
  7973. _this._workingContext.msImageSmoothingEnabled = false;
  7974. }
  7975. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  7976. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7977. _this._workingContext.imageSmoothingEnabled = true;
  7978. _this._workingContext.mozImageSmoothingEnabled = true;
  7979. _this._workingContext.oImageSmoothingEnabled = true;
  7980. _this._workingContext.webkitImageSmoothingEnabled = true;
  7981. _this._workingContext.msImageSmoothingEnabled = true;
  7982. }
  7983. }
  7984. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  7985. }, samplingMode);
  7986. };
  7987. if (!(fromData instanceof Array))
  7988. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7989. else
  7990. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  7991. }
  7992. return texture;
  7993. };
  7994. Engine.prototype._getInternalFormat = function (format) {
  7995. var internalFormat = this._gl.RGBA;
  7996. switch (format) {
  7997. case Engine.TEXTUREFORMAT_ALPHA:
  7998. internalFormat = this._gl.ALPHA;
  7999. break;
  8000. case Engine.TEXTUREFORMAT_LUMINANCE:
  8001. internalFormat = this._gl.LUMINANCE;
  8002. break;
  8003. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  8004. internalFormat = this._gl.LUMINANCE_ALPHA;
  8005. break;
  8006. case Engine.TEXTUREFORMAT_RGB:
  8007. internalFormat = this._gl.RGB;
  8008. break;
  8009. case Engine.TEXTUREFORMAT_RGBA:
  8010. internalFormat = this._gl.RGBA;
  8011. break;
  8012. }
  8013. return internalFormat;
  8014. };
  8015. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  8016. if (compression === void 0) { compression = null; }
  8017. var internalFormat = this._getInternalFormat(format);
  8018. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8019. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  8020. if (texture._width % 4 !== 0) {
  8021. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  8022. }
  8023. if (compression) {
  8024. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  8025. }
  8026. else {
  8027. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  8028. }
  8029. if (texture.generateMipMaps) {
  8030. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8031. }
  8032. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8033. this.resetTextureCache();
  8034. texture.isReady = true;
  8035. };
  8036. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  8037. if (compression === void 0) { compression = null; }
  8038. var texture = this._gl.createTexture();
  8039. texture._baseWidth = width;
  8040. texture._baseHeight = height;
  8041. texture._width = width;
  8042. texture._height = height;
  8043. texture.references = 1;
  8044. this.updateRawTexture(texture, data, format, invertY, compression);
  8045. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8046. // Filters
  8047. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  8048. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8049. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8050. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8051. texture.samplingMode = samplingMode;
  8052. this._loadedTexturesCache.push(texture);
  8053. return texture;
  8054. };
  8055. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  8056. var texture = this._gl.createTexture();
  8057. texture._baseWidth = width;
  8058. texture._baseHeight = height;
  8059. if (generateMipMaps) {
  8060. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  8061. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  8062. }
  8063. this.resetTextureCache();
  8064. texture._width = width;
  8065. texture._height = height;
  8066. texture.isReady = false;
  8067. texture.generateMipMaps = generateMipMaps;
  8068. texture.references = 1;
  8069. texture.samplingMode = samplingMode;
  8070. this.updateTextureSamplingMode(samplingMode, texture);
  8071. this._loadedTexturesCache.push(texture);
  8072. return texture;
  8073. };
  8074. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  8075. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  8076. if (texture.isCube) {
  8077. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  8078. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8079. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8080. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8081. }
  8082. else {
  8083. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8084. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8085. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8086. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8087. }
  8088. };
  8089. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  8090. if (premulAlpha === void 0) { premulAlpha = false; }
  8091. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8092. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  8093. if (premulAlpha) {
  8094. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  8095. }
  8096. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  8097. if (texture.generateMipMaps) {
  8098. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8099. }
  8100. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8101. if (premulAlpha) {
  8102. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  8103. }
  8104. this.resetTextureCache();
  8105. texture.isReady = true;
  8106. };
  8107. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8108. if (texture._isDisabled) {
  8109. return;
  8110. }
  8111. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8112. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  8113. try {
  8114. // Testing video texture support
  8115. if (this._videoTextureSupported === undefined) {
  8116. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8117. if (this._gl.getError() !== 0) {
  8118. this._videoTextureSupported = false;
  8119. }
  8120. else {
  8121. this._videoTextureSupported = true;
  8122. }
  8123. }
  8124. // Copy video through the current working canvas if video texture is not supported
  8125. if (!this._videoTextureSupported) {
  8126. if (!texture._workingCanvas) {
  8127. texture._workingCanvas = document.createElement("canvas");
  8128. texture._workingContext = texture._workingCanvas.getContext("2d");
  8129. texture._workingCanvas.width = texture._width;
  8130. texture._workingCanvas.height = texture._height;
  8131. }
  8132. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  8133. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  8134. }
  8135. else {
  8136. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8137. }
  8138. if (texture.generateMipMaps) {
  8139. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8140. }
  8141. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8142. this.resetTextureCache();
  8143. texture.isReady = true;
  8144. }
  8145. catch (ex) {
  8146. // Something unexpected
  8147. // Let's disable the texture
  8148. texture._isDisabled = true;
  8149. }
  8150. };
  8151. Engine.prototype.createRenderTargetTexture = function (size, options) {
  8152. // old version had a "generateMipMaps" arg instead of options.
  8153. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  8154. // in the same way, generateDepthBuffer is defaulted to true
  8155. var generateMipMaps = false;
  8156. var generateDepthBuffer = true;
  8157. var generateStencilBuffer = false;
  8158. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8159. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8160. if (options !== undefined) {
  8161. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8162. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8163. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8164. type = options.type === undefined ? type : options.type;
  8165. if (options.samplingMode !== undefined) {
  8166. samplingMode = options.samplingMode;
  8167. }
  8168. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  8169. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  8170. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8171. }
  8172. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  8173. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  8174. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8175. }
  8176. }
  8177. var gl = this._gl;
  8178. var texture = gl.createTexture();
  8179. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8180. var width = size.width || size;
  8181. var height = size.height || size;
  8182. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8183. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  8184. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8185. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  8186. }
  8187. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  8188. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  8189. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8190. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8191. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  8192. var depthStencilBuffer;
  8193. // Create the depth/stencil buffer
  8194. if (generateStencilBuffer) {
  8195. depthStencilBuffer = gl.createRenderbuffer();
  8196. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8197. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  8198. }
  8199. else if (generateDepthBuffer) {
  8200. depthStencilBuffer = gl.createRenderbuffer();
  8201. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8202. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  8203. }
  8204. // Create the framebuffer
  8205. var framebuffer = gl.createFramebuffer();
  8206. this.bindUnboundFramebuffer(framebuffer);
  8207. // Manage attachments
  8208. if (generateStencilBuffer) {
  8209. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8210. }
  8211. else if (generateDepthBuffer) {
  8212. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8213. }
  8214. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  8215. if (generateMipMaps) {
  8216. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8217. }
  8218. // Unbind
  8219. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8220. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8221. this.bindUnboundFramebuffer(null);
  8222. texture._framebuffer = framebuffer;
  8223. if (generateDepthBuffer) {
  8224. texture._depthBuffer = depthStencilBuffer;
  8225. }
  8226. texture._baseWidth = width;
  8227. texture._baseHeight = height;
  8228. texture._width = width;
  8229. texture._height = height;
  8230. texture.isReady = true;
  8231. texture.generateMipMaps = generateMipMaps;
  8232. texture.references = 1;
  8233. texture.samplingMode = samplingMode;
  8234. texture.type = type;
  8235. this.resetTextureCache();
  8236. this._loadedTexturesCache.push(texture);
  8237. return texture;
  8238. };
  8239. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  8240. var gl = this._gl;
  8241. var texture = gl.createTexture();
  8242. var generateMipMaps = true;
  8243. var generateDepthBuffer = true;
  8244. var generateStencilBuffer = false;
  8245. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8246. if (options !== undefined) {
  8247. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8248. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8249. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8250. if (options.samplingMode !== undefined) {
  8251. samplingMode = options.samplingMode;
  8252. }
  8253. }
  8254. texture.isCube = true;
  8255. texture.references = 1;
  8256. texture.generateMipMaps = generateMipMaps;
  8257. texture.references = 1;
  8258. texture.samplingMode = samplingMode;
  8259. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8260. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8261. for (var face = 0; face < 6; face++) {
  8262. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  8263. }
  8264. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  8265. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  8266. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8267. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8268. // Create the depth buffer
  8269. var depthStencilBuffer;
  8270. // Create the depth/stencil buffer
  8271. if (generateStencilBuffer) {
  8272. depthStencilBuffer = gl.createRenderbuffer();
  8273. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8274. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  8275. }
  8276. else if (generateDepthBuffer) {
  8277. depthStencilBuffer = gl.createRenderbuffer();
  8278. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8279. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  8280. }
  8281. // Create the framebuffer
  8282. var framebuffer = gl.createFramebuffer();
  8283. this.bindUnboundFramebuffer(framebuffer);
  8284. // Manage attachments
  8285. if (generateStencilBuffer) {
  8286. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8287. }
  8288. else if (generateDepthBuffer) {
  8289. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8290. }
  8291. // Mipmaps
  8292. if (texture.generateMipMaps) {
  8293. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8294. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8295. }
  8296. // Unbind
  8297. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8298. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8299. this.bindUnboundFramebuffer(null);
  8300. texture._framebuffer = framebuffer;
  8301. if (generateDepthBuffer) {
  8302. texture._depthBuffer = depthStencilBuffer;
  8303. }
  8304. texture._width = size;
  8305. texture._height = size;
  8306. texture.isReady = true;
  8307. this.resetTextureCache();
  8308. this._loadedTexturesCache.push(texture);
  8309. return texture;
  8310. };
  8311. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError) {
  8312. var _this = this;
  8313. if (onLoad === void 0) { onLoad = null; }
  8314. if (onError === void 0) { onError = null; }
  8315. var gl = this._gl;
  8316. var texture = gl.createTexture();
  8317. texture.isCube = true;
  8318. texture.url = rootUrl;
  8319. texture.references = 1;
  8320. texture.onLoadedCallbacks = [];
  8321. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  8322. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8323. if (isDDS) {
  8324. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8325. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8326. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  8327. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8328. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8329. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  8330. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  8331. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8332. }
  8333. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8334. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8335. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8336. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8337. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8338. _this.resetTextureCache();
  8339. texture._width = info.width;
  8340. texture._height = info.height;
  8341. texture.isReady = true;
  8342. }, null, null, true, onError);
  8343. }
  8344. else {
  8345. cascadeLoad(rootUrl, scene, function (imgs) {
  8346. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8347. var height = width;
  8348. _this._prepareWorkingCanvas();
  8349. _this._workingCanvas.width = width;
  8350. _this._workingCanvas.height = height;
  8351. var faces = [
  8352. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8353. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8354. ];
  8355. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8356. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8357. for (var index = 0; index < faces.length; index++) {
  8358. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8359. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8360. }
  8361. if (!noMipmap) {
  8362. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8363. }
  8364. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8365. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8366. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8367. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8368. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8369. _this.resetTextureCache();
  8370. texture._width = width;
  8371. texture._height = height;
  8372. texture.isReady = true;
  8373. texture.onLoadedCallbacks.forEach(function (callback) {
  8374. callback();
  8375. });
  8376. if (onLoad) {
  8377. onLoad();
  8378. }
  8379. }, files, onError);
  8380. }
  8381. this._loadedTexturesCache.push(texture);
  8382. return texture;
  8383. };
  8384. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8385. texture._width = width;
  8386. texture._height = height;
  8387. texture._size = width * height;
  8388. texture._baseWidth = width;
  8389. texture._baseHeight = height;
  8390. };
  8391. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  8392. var _this = this;
  8393. var gl = this._gl;
  8394. var texture = gl.createTexture();
  8395. scene._addPendingData(texture);
  8396. texture.isCube = true;
  8397. texture.references = 1;
  8398. texture.url = url;
  8399. var internalFormat = this._getInternalFormat(format);
  8400. var textureType = gl.UNSIGNED_BYTE;
  8401. if (type === Engine.TEXTURETYPE_FLOAT) {
  8402. textureType = gl.FLOAT;
  8403. }
  8404. var width = size;
  8405. var height = width;
  8406. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8407. texture._width = width;
  8408. texture._height = height;
  8409. var onerror = function () {
  8410. scene._removePendingData(texture);
  8411. };
  8412. var internalCallback = function (data) {
  8413. var rgbeDataArrays = callback(data);
  8414. var facesIndex = [
  8415. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8416. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8417. ];
  8418. width = texture._width;
  8419. height = texture._height;
  8420. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8421. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8422. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8423. if (!noMipmap && isPot) {
  8424. if (mipmmapGenerator) {
  8425. var arrayTemp = [];
  8426. // Data are known to be in +X +Y +Z -X -Y -Z
  8427. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8428. arrayTemp.push(rgbeDataArrays[0]); // +X
  8429. arrayTemp.push(rgbeDataArrays[3]); // -X
  8430. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8431. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8432. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8433. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8434. var mipData = mipmmapGenerator(arrayTemp);
  8435. for (var level = 0; level < mipData.length; level++) {
  8436. var mipSize = width >> level;
  8437. // mipData is order in +X -X +Y -Y +Z -Z
  8438. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  8439. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  8440. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  8441. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  8442. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  8443. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  8444. }
  8445. }
  8446. else {
  8447. // Data are known to be in +X +Y +Z -X -Y -Z
  8448. for (var index = 0; index < facesIndex.length; index++) {
  8449. var faceData = rgbeDataArrays[index];
  8450. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  8451. }
  8452. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8453. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  8454. // By following the webgl standard changes from Revision 7, 2014/11/24
  8455. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  8456. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  8457. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  8458. // Data are known to be in +X +Y +Z -X -Y -Z
  8459. for (var index = 0; index < facesIndex.length; index++) {
  8460. var faceData = rgbeDataArrays[index];
  8461. // Create a new RGBA Face.
  8462. var newFaceData = new Float32Array(width * height * 4);
  8463. for (var x = 0; x < width; x++) {
  8464. for (var y = 0; y < height; y++) {
  8465. var index_1 = (y * width + x) * 3;
  8466. var newIndex = (y * width + x) * 4;
  8467. // Map Old Value to new value.
  8468. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  8469. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  8470. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  8471. // Add fully opaque alpha channel.
  8472. newFaceData[newIndex + 3] = 1;
  8473. }
  8474. }
  8475. // Reupload the face.
  8476. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  8477. }
  8478. // Try to generate mipmap again.
  8479. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8480. }
  8481. }
  8482. }
  8483. else {
  8484. noMipmap = true;
  8485. }
  8486. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8487. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8488. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8489. }
  8490. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8491. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8492. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8493. }
  8494. else {
  8495. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8496. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8497. }
  8498. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8499. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8500. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8501. texture.isReady = true;
  8502. _this.resetTextureCache();
  8503. scene._removePendingData(texture);
  8504. };
  8505. BABYLON.Tools.LoadFile(url, function (data) {
  8506. internalCallback(data);
  8507. }, onerror, scene.database, true);
  8508. return texture;
  8509. };
  8510. ;
  8511. Engine.prototype._releaseTexture = function (texture) {
  8512. var gl = this._gl;
  8513. if (texture._framebuffer) {
  8514. gl.deleteFramebuffer(texture._framebuffer);
  8515. }
  8516. if (texture._depthBuffer) {
  8517. gl.deleteRenderbuffer(texture._depthBuffer);
  8518. }
  8519. gl.deleteTexture(texture);
  8520. // Unbind channels
  8521. this.unbindAllTextures();
  8522. var index = this._loadedTexturesCache.indexOf(texture);
  8523. if (index !== -1) {
  8524. this._loadedTexturesCache.splice(index, 1);
  8525. }
  8526. };
  8527. Engine.prototype.setProgram = function (program) {
  8528. if (this._currentProgram !== program) {
  8529. this._gl.useProgram(program);
  8530. this._currentProgram = program;
  8531. }
  8532. };
  8533. Engine.prototype.bindSamplers = function (effect) {
  8534. this.setProgram(effect.getProgram());
  8535. var samplers = effect.getSamplers();
  8536. for (var index = 0; index < samplers.length; index++) {
  8537. var uniform = effect.getUniform(samplers[index]);
  8538. this._gl.uniform1i(uniform, index);
  8539. }
  8540. this._currentEffect = null;
  8541. };
  8542. Engine.prototype.activateTexture = function (texture) {
  8543. if (this._activeTexture !== texture) {
  8544. this._gl.activeTexture(texture);
  8545. this._activeTexture = texture;
  8546. }
  8547. };
  8548. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8549. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8550. this._gl.bindTexture(target, texture);
  8551. this._activeTexturesCache[this._activeTexture] = texture;
  8552. }
  8553. };
  8554. Engine.prototype._bindTexture = function (channel, texture) {
  8555. if (channel < 0) {
  8556. return;
  8557. }
  8558. this.activateTexture(this._gl["TEXTURE" + channel]);
  8559. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8560. };
  8561. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8562. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8563. };
  8564. Engine.prototype.unbindAllTextures = function () {
  8565. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8566. this.activateTexture(this._gl["TEXTURE" + channel]);
  8567. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8568. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8569. }
  8570. };
  8571. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8572. if (channel < 0) {
  8573. return;
  8574. }
  8575. this._gl.uniform1i(uniform, channel);
  8576. this._setTexture(channel, texture);
  8577. };
  8578. Engine.prototype._setTexture = function (channel, texture) {
  8579. // Not ready?
  8580. if (!texture || !texture.isReady()) {
  8581. if (this._activeTexturesCache[channel] != null) {
  8582. this.activateTexture(this._gl["TEXTURE" + channel]);
  8583. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8584. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8585. }
  8586. return;
  8587. }
  8588. // Video
  8589. var alreadyActivated = false;
  8590. if (texture instanceof BABYLON.VideoTexture) {
  8591. this.activateTexture(this._gl["TEXTURE" + channel]);
  8592. alreadyActivated = true;
  8593. texture.update();
  8594. }
  8595. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8596. texture.delayLoad();
  8597. return;
  8598. }
  8599. var internalTexture = texture.getInternalTexture();
  8600. if (this._activeTexturesCache[channel] === internalTexture) {
  8601. return;
  8602. }
  8603. if (!alreadyActivated) {
  8604. this.activateTexture(this._gl["TEXTURE" + channel]);
  8605. }
  8606. if (internalTexture.isCube) {
  8607. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8608. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8609. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8610. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8611. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8612. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8613. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8614. }
  8615. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8616. }
  8617. else {
  8618. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8619. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8620. internalTexture._cachedWrapU = texture.wrapU;
  8621. switch (texture.wrapU) {
  8622. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8623. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8624. break;
  8625. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8626. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8627. break;
  8628. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8629. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8630. break;
  8631. }
  8632. }
  8633. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8634. internalTexture._cachedWrapV = texture.wrapV;
  8635. switch (texture.wrapV) {
  8636. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8637. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8638. break;
  8639. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8640. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8641. break;
  8642. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8643. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8644. break;
  8645. }
  8646. }
  8647. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8648. }
  8649. };
  8650. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8651. if (channel < 0) {
  8652. return;
  8653. }
  8654. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8655. this._textureUnits = new Int32Array(textures.length);
  8656. }
  8657. for (var i = 0; i < textures.length; i++) {
  8658. this._textureUnits[i] = channel + i;
  8659. }
  8660. this._gl.uniform1iv(uniform, this._textureUnits);
  8661. for (var index = 0; index < textures.length; index++) {
  8662. this._setTexture(channel + index, textures[index]);
  8663. }
  8664. };
  8665. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8666. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8667. var value = texture.anisotropicFilteringLevel;
  8668. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8669. value = 1;
  8670. }
  8671. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8672. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8673. texture._cachedAnisotropicFilteringLevel = value;
  8674. }
  8675. };
  8676. Engine.prototype.readPixels = function (x, y, width, height) {
  8677. var data = new Uint8Array(height * width * 4);
  8678. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8679. return data;
  8680. };
  8681. /**
  8682. * Add an externaly attached data from its key.
  8683. * This method call will fail and return false, if such key already exists.
  8684. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8685. * @param key the unique key that identifies the data
  8686. * @param data the data object to associate to the key for this Engine instance
  8687. * @return true if no such key were already present and the data was added successfully, false otherwise
  8688. */
  8689. Engine.prototype.addExternalData = function (key, data) {
  8690. return this._externalData.add(key, data);
  8691. };
  8692. /**
  8693. * Get an externaly attached data from its key
  8694. * @param key the unique key that identifies the data
  8695. * @return the associated data, if present (can be null), or undefined if not present
  8696. */
  8697. Engine.prototype.getExternalData = function (key) {
  8698. return this._externalData.get(key);
  8699. };
  8700. /**
  8701. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8702. * @param key the unique key that identifies the data
  8703. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8704. * @return the associated data, can be null if the factory returned null.
  8705. */
  8706. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8707. return this._externalData.getOrAddWithFactory(key, factory);
  8708. };
  8709. /**
  8710. * Remove an externaly attached data from the Engine instance
  8711. * @param key the unique key that identifies the data
  8712. * @return true if the data was successfully removed, false if it doesn't exist
  8713. */
  8714. Engine.prototype.removeExternalData = function (key) {
  8715. return this._externalData.remove(key);
  8716. };
  8717. Engine.prototype.releaseInternalTexture = function (texture) {
  8718. if (!texture) {
  8719. return;
  8720. }
  8721. texture.references--;
  8722. // Final reference ?
  8723. if (texture.references === 0) {
  8724. var texturesCache = this.getLoadedTexturesCache();
  8725. var index = texturesCache.indexOf(texture);
  8726. if (index > -1) {
  8727. texturesCache.splice(index, 1);
  8728. }
  8729. this._releaseTexture(texture);
  8730. }
  8731. };
  8732. Engine.prototype.unbindAllAttributes = function () {
  8733. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8734. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  8735. continue;
  8736. }
  8737. this._gl.disableVertexAttribArray(i);
  8738. this._vertexAttribArraysEnabled[i] = false;
  8739. }
  8740. };
  8741. // Dispose
  8742. Engine.prototype.dispose = function () {
  8743. this.hideLoadingUI();
  8744. this.stopRenderLoop();
  8745. // Release scenes
  8746. while (this.scenes.length) {
  8747. this.scenes[0].dispose();
  8748. }
  8749. // Release audio engine
  8750. Engine.audioEngine.dispose();
  8751. // Release effects
  8752. for (var name in this._compiledEffects) {
  8753. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8754. }
  8755. // Unbind
  8756. this.unbindAllAttributes();
  8757. this._gl = null;
  8758. //WebVR
  8759. this.disableVR();
  8760. // Events
  8761. window.removeEventListener("blur", this._onBlur);
  8762. window.removeEventListener("focus", this._onFocus);
  8763. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8764. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8765. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8766. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8767. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8768. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8769. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8770. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8771. };
  8772. // Loading screen
  8773. Engine.prototype.displayLoadingUI = function () {
  8774. this._loadingScreen.displayLoadingUI();
  8775. };
  8776. Engine.prototype.hideLoadingUI = function () {
  8777. this._loadingScreen.hideLoadingUI();
  8778. };
  8779. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8780. get: function () {
  8781. return this._loadingScreen;
  8782. },
  8783. set: function (loadingScreen) {
  8784. this._loadingScreen = loadingScreen;
  8785. },
  8786. enumerable: true,
  8787. configurable: true
  8788. });
  8789. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8790. set: function (text) {
  8791. this._loadingScreen.loadingUIText = text;
  8792. },
  8793. enumerable: true,
  8794. configurable: true
  8795. });
  8796. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8797. set: function (color) {
  8798. this._loadingScreen.loadingUIBackgroundColor = color;
  8799. },
  8800. enumerable: true,
  8801. configurable: true
  8802. });
  8803. Engine.prototype.attachContextLostEvent = function (callback) {
  8804. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  8805. };
  8806. Engine.prototype.attachContextRestoredEvent = function (callback) {
  8807. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  8808. };
  8809. // FPS
  8810. Engine.prototype.getFps = function () {
  8811. return this.fps;
  8812. };
  8813. Engine.prototype.getDeltaTime = function () {
  8814. return this.deltaTime;
  8815. };
  8816. Engine.prototype._measureFps = function () {
  8817. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8818. var length = this.previousFramesDuration.length;
  8819. if (length >= 2) {
  8820. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8821. }
  8822. if (length >= this.fpsRange) {
  8823. if (length > this.fpsRange) {
  8824. this.previousFramesDuration.splice(0, 1);
  8825. length = this.previousFramesDuration.length;
  8826. }
  8827. var sum = 0;
  8828. for (var id = 0; id < length - 1; id++) {
  8829. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8830. }
  8831. this.fps = 1000.0 / (sum / (length - 1));
  8832. }
  8833. };
  8834. Engine.prototype._canRenderToFloatTexture = function () {
  8835. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  8836. };
  8837. Engine.prototype._canRenderToHalfFloatTexture = function () {
  8838. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  8839. };
  8840. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  8841. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  8842. var tempcanvas = document.createElement("canvas");
  8843. tempcanvas.height = 16;
  8844. tempcanvas.width = 16;
  8845. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  8846. // extension.
  8847. var ext = gl.getExtension(extension);
  8848. if (!ext) {
  8849. return false;
  8850. }
  8851. // setup GLSL program
  8852. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  8853. 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 }";
  8854. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  8855. gl.useProgram(program);
  8856. // look up where the vertex data needs to go.
  8857. var positionLocation = gl.getAttribLocation(program, "a_position");
  8858. var colorLoc = gl.getUniformLocation(program, "u_color");
  8859. // provide texture coordinates for the rectangle.
  8860. var positionBuffer = gl.createBuffer();
  8861. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  8862. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  8863. -1.0, -1.0,
  8864. 1.0, -1.0,
  8865. -1.0, 1.0,
  8866. -1.0, 1.0,
  8867. 1.0, -1.0,
  8868. 1.0, 1.0]), gl.STATIC_DRAW);
  8869. gl.enableVertexAttribArray(positionLocation);
  8870. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  8871. var whiteTex = gl.createTexture();
  8872. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8873. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  8874. var tex = gl.createTexture();
  8875. gl.bindTexture(gl.TEXTURE_2D, tex);
  8876. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  8877. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8878. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8879. var fb = gl.createFramebuffer();
  8880. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  8881. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  8882. var cleanup = function () {
  8883. gl.deleteProgram(program);
  8884. gl.disableVertexAttribArray(positionLocation);
  8885. gl.deleteBuffer(positionBuffer);
  8886. gl.deleteFramebuffer(fb);
  8887. gl.deleteTexture(whiteTex);
  8888. gl.deleteTexture(tex);
  8889. };
  8890. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  8891. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  8892. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  8893. cleanup();
  8894. return false;
  8895. }
  8896. // Draw the rectangle.
  8897. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8898. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  8899. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8900. gl.bindTexture(gl.TEXTURE_2D, tex);
  8901. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8902. gl.clearColor(1, 0, 0, 1);
  8903. gl.clear(gl.COLOR_BUFFER_BIT);
  8904. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  8905. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8906. var pixel = new Uint8Array(4);
  8907. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  8908. if (pixel[0] !== 0 ||
  8909. pixel[1] < 248 ||
  8910. pixel[2] < 248 ||
  8911. pixel[3] < 254) {
  8912. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  8913. cleanup();
  8914. return false;
  8915. }
  8916. // Succesfully rendered to "format" texture.
  8917. cleanup();
  8918. return true;
  8919. };
  8920. // Statics
  8921. Engine.isSupported = function () {
  8922. try {
  8923. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  8924. if (navigator.isCocoonJS) {
  8925. return true;
  8926. }
  8927. var tempcanvas = document.createElement("canvas");
  8928. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  8929. return gl != null && !!window.WebGLRenderingContext;
  8930. }
  8931. catch (e) {
  8932. return false;
  8933. }
  8934. };
  8935. // Const statics
  8936. Engine._ALPHA_DISABLE = 0;
  8937. Engine._ALPHA_ADD = 1;
  8938. Engine._ALPHA_COMBINE = 2;
  8939. Engine._ALPHA_SUBTRACT = 3;
  8940. Engine._ALPHA_MULTIPLY = 4;
  8941. Engine._ALPHA_MAXIMIZED = 5;
  8942. Engine._ALPHA_ONEONE = 6;
  8943. Engine._DELAYLOADSTATE_NONE = 0;
  8944. Engine._DELAYLOADSTATE_LOADED = 1;
  8945. Engine._DELAYLOADSTATE_LOADING = 2;
  8946. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  8947. Engine._TEXTUREFORMAT_ALPHA = 0;
  8948. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  8949. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  8950. Engine._TEXTUREFORMAT_RGB = 4;
  8951. Engine._TEXTUREFORMAT_RGBA = 5;
  8952. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  8953. Engine._TEXTURETYPE_FLOAT = 1;
  8954. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  8955. // Depht or Stencil test Constants.
  8956. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  8957. 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.
  8958. 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.
  8959. 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.
  8960. 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.
  8961. 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.
  8962. 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.
  8963. 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.
  8964. // Stencil Actions Constants.
  8965. Engine._KEEP = 0x1E00;
  8966. Engine._REPLACE = 0x1E01;
  8967. Engine._INCR = 0x1E02;
  8968. Engine._DECR = 0x1E03;
  8969. Engine._INVERT = 0x150A;
  8970. Engine._INCR_WRAP = 0x8507;
  8971. Engine._DECR_WRAP = 0x8508;
  8972. // Updatable statics so stick with vars here
  8973. Engine.CollisionsEpsilon = 0.001;
  8974. Engine.CodeRepository = "src/";
  8975. Engine.ShadersRepository = "src/Shaders/";
  8976. return Engine;
  8977. }());
  8978. BABYLON.Engine = Engine;
  8979. })(BABYLON || (BABYLON = {}));
  8980. var BABYLON;
  8981. (function (BABYLON) {
  8982. /**
  8983. * Node is the basic class for all scene objects (Mesh, Light Camera).
  8984. */
  8985. var Node = (function () {
  8986. /**
  8987. * @constructor
  8988. * @param {string} name - the name and id to be given to this node
  8989. * @param {BABYLON.Scene} the scene this node will be added to
  8990. */
  8991. function Node(name, scene) {
  8992. this.state = "";
  8993. this.metadata = null;
  8994. this.animations = new Array();
  8995. this._ranges = {};
  8996. this._childrenFlag = -1;
  8997. this._isEnabled = true;
  8998. this._isReady = true;
  8999. this._currentRenderId = -1;
  9000. this._parentRenderId = -1;
  9001. this.name = name;
  9002. this.id = name;
  9003. this._scene = scene;
  9004. this._initCache();
  9005. }
  9006. Object.defineProperty(Node.prototype, "parent", {
  9007. get: function () {
  9008. return this._parentNode;
  9009. },
  9010. set: function (parent) {
  9011. if (this._parentNode === parent) {
  9012. return;
  9013. }
  9014. if (this._parentNode) {
  9015. var index = this._parentNode._children.indexOf(this);
  9016. if (index !== -1) {
  9017. this._parentNode._children.splice(index, 1);
  9018. }
  9019. }
  9020. this._parentNode = parent;
  9021. if (this._parentNode) {
  9022. if (!this._parentNode._children) {
  9023. this._parentNode._children = new Array();
  9024. }
  9025. this._parentNode._children.push(this);
  9026. }
  9027. },
  9028. enumerable: true,
  9029. configurable: true
  9030. });
  9031. Node.prototype.getScene = function () {
  9032. return this._scene;
  9033. };
  9034. Node.prototype.getEngine = function () {
  9035. return this._scene.getEngine();
  9036. };
  9037. // override it in derived class
  9038. Node.prototype.getWorldMatrix = function () {
  9039. return BABYLON.Matrix.Identity();
  9040. };
  9041. // override it in derived class if you add new variables to the cache
  9042. // and call the parent class method
  9043. Node.prototype._initCache = function () {
  9044. this._cache = {};
  9045. this._cache.parent = undefined;
  9046. };
  9047. Node.prototype.updateCache = function (force) {
  9048. if (!force && this.isSynchronized())
  9049. return;
  9050. this._cache.parent = this.parent;
  9051. this._updateCache();
  9052. };
  9053. // override it in derived class if you add new variables to the cache
  9054. // and call the parent class method if !ignoreParentClass
  9055. Node.prototype._updateCache = function (ignoreParentClass) {
  9056. };
  9057. // override it in derived class if you add new variables to the cache
  9058. Node.prototype._isSynchronized = function () {
  9059. return true;
  9060. };
  9061. Node.prototype._markSyncedWithParent = function () {
  9062. this._parentRenderId = this.parent._currentRenderId;
  9063. };
  9064. Node.prototype.isSynchronizedWithParent = function () {
  9065. if (!this.parent) {
  9066. return true;
  9067. }
  9068. if (this._parentRenderId !== this.parent._currentRenderId) {
  9069. return false;
  9070. }
  9071. return this.parent.isSynchronized();
  9072. };
  9073. Node.prototype.isSynchronized = function (updateCache) {
  9074. var check = this.hasNewParent();
  9075. check = check || !this.isSynchronizedWithParent();
  9076. check = check || !this._isSynchronized();
  9077. if (updateCache)
  9078. this.updateCache(true);
  9079. return !check;
  9080. };
  9081. Node.prototype.hasNewParent = function (update) {
  9082. if (this._cache.parent === this.parent)
  9083. return false;
  9084. if (update)
  9085. this._cache.parent = this.parent;
  9086. return true;
  9087. };
  9088. /**
  9089. * Is this node ready to be used/rendered
  9090. * @return {boolean} is it ready
  9091. */
  9092. Node.prototype.isReady = function () {
  9093. return this._isReady;
  9094. };
  9095. /**
  9096. * Is this node enabled.
  9097. * If the node has a parent and is enabled, the parent will be inspected as well.
  9098. * @return {boolean} whether this node (and its parent) is enabled.
  9099. * @see setEnabled
  9100. */
  9101. Node.prototype.isEnabled = function () {
  9102. if (!this._isEnabled) {
  9103. return false;
  9104. }
  9105. if (this.parent) {
  9106. return this.parent.isEnabled();
  9107. }
  9108. return true;
  9109. };
  9110. /**
  9111. * Set the enabled state of this node.
  9112. * @param {boolean} value - the new enabled state
  9113. * @see isEnabled
  9114. */
  9115. Node.prototype.setEnabled = function (value) {
  9116. this._isEnabled = value;
  9117. };
  9118. /**
  9119. * Is this node a descendant of the given node.
  9120. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  9121. * @param {BABYLON.Node} ancestor - The parent node to inspect
  9122. * @see parent
  9123. */
  9124. Node.prototype.isDescendantOf = function (ancestor) {
  9125. if (this.parent) {
  9126. if (this.parent === ancestor) {
  9127. return true;
  9128. }
  9129. return this.parent.isDescendantOf(ancestor);
  9130. }
  9131. return false;
  9132. };
  9133. /**
  9134. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  9135. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  9136. * @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.
  9137. * @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.
  9138. */
  9139. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  9140. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  9141. if (!this._children) {
  9142. return;
  9143. }
  9144. for (var index = 0; index < this._children.length; index++) {
  9145. var item = this._children[index];
  9146. if (!predicate || predicate(item)) {
  9147. results.push(item);
  9148. }
  9149. if (!directDescendantsOnly) {
  9150. item._getDescendants(results, false, predicate);
  9151. }
  9152. }
  9153. };
  9154. /**
  9155. * Will return all nodes that have this node as ascendant.
  9156. * @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.
  9157. * @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.
  9158. * @return {BABYLON.Node[]} all children nodes of all types.
  9159. */
  9160. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  9161. var results = [];
  9162. this._getDescendants(results, directDescendantsOnly, predicate);
  9163. return results;
  9164. };
  9165. /**
  9166. * @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.
  9167. * @Deprecated, legacy support.
  9168. * use getDecendants instead.
  9169. */
  9170. Node.prototype.getChildren = function (predicate) {
  9171. return this.getDescendants(true, predicate);
  9172. };
  9173. /**
  9174. * Get all child-meshes of this node.
  9175. */
  9176. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  9177. var results = [];
  9178. this._getDescendants(results, directDecendantsOnly, function (node) {
  9179. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  9180. });
  9181. return results;
  9182. };
  9183. Node.prototype._setReady = function (state) {
  9184. if (state === this._isReady) {
  9185. return;
  9186. }
  9187. if (!state) {
  9188. this._isReady = false;
  9189. return;
  9190. }
  9191. this._isReady = true;
  9192. if (this.onReady) {
  9193. this.onReady(this);
  9194. }
  9195. };
  9196. Node.prototype.getAnimationByName = function (name) {
  9197. for (var i = 0; i < this.animations.length; i++) {
  9198. var animation = this.animations[i];
  9199. if (animation.name === name) {
  9200. return animation;
  9201. }
  9202. }
  9203. return null;
  9204. };
  9205. Node.prototype.createAnimationRange = function (name, from, to) {
  9206. // check name not already in use
  9207. if (!this._ranges[name]) {
  9208. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  9209. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9210. if (this.animations[i]) {
  9211. this.animations[i].createRange(name, from, to);
  9212. }
  9213. }
  9214. }
  9215. };
  9216. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  9217. if (deleteFrames === void 0) { deleteFrames = true; }
  9218. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9219. if (this.animations[i]) {
  9220. this.animations[i].deleteRange(name, deleteFrames);
  9221. }
  9222. }
  9223. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  9224. };
  9225. Node.prototype.getAnimationRange = function (name) {
  9226. return this._ranges[name];
  9227. };
  9228. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  9229. var range = this.getAnimationRange(name);
  9230. if (!range) {
  9231. return null;
  9232. }
  9233. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  9234. };
  9235. Node.prototype.serializeAnimationRanges = function () {
  9236. var serializationRanges = [];
  9237. for (var name in this._ranges) {
  9238. var range = {};
  9239. range.name = name;
  9240. range.from = this._ranges[name].from;
  9241. range.to = this._ranges[name].to;
  9242. serializationRanges.push(range);
  9243. }
  9244. return serializationRanges;
  9245. };
  9246. Node.prototype.dispose = function () {
  9247. this.parent = null;
  9248. };
  9249. Node.prototype.getDirection = function (localAxis) {
  9250. var result = BABYLON.Vector3.Zero();
  9251. this.getDirectionToRef(localAxis, result);
  9252. return result;
  9253. };
  9254. Node.prototype.getDirectionToRef = function (localAxis, result) {
  9255. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  9256. };
  9257. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  9258. if (parsedNode.ranges) {
  9259. for (var index = 0; index < parsedNode.ranges.length; index++) {
  9260. var data = parsedNode.ranges[index];
  9261. node.createAnimationRange(data.name, data.from, data.to);
  9262. }
  9263. }
  9264. };
  9265. __decorate([
  9266. BABYLON.serialize()
  9267. ], Node.prototype, "name", void 0);
  9268. __decorate([
  9269. BABYLON.serialize()
  9270. ], Node.prototype, "id", void 0);
  9271. __decorate([
  9272. BABYLON.serialize()
  9273. ], Node.prototype, "uniqueId", void 0);
  9274. __decorate([
  9275. BABYLON.serialize()
  9276. ], Node.prototype, "state", void 0);
  9277. __decorate([
  9278. BABYLON.serialize()
  9279. ], Node.prototype, "metadata", void 0);
  9280. return Node;
  9281. }());
  9282. BABYLON.Node = Node;
  9283. })(BABYLON || (BABYLON = {}));
  9284. var BABYLON;
  9285. (function (BABYLON) {
  9286. var FilesInput = (function () {
  9287. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  9288. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  9289. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  9290. this._engine = p_engine;
  9291. this._canvas = p_canvas;
  9292. this._currentScene = p_scene;
  9293. this._sceneLoadedCallback = p_sceneLoadedCallback;
  9294. this._progressCallback = p_progressCallback;
  9295. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  9296. this._textureLoadingCallback = p_textureLoadingCallback;
  9297. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  9298. }
  9299. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  9300. var _this = this;
  9301. if (p_elementToMonitor) {
  9302. this._elementToMonitor = p_elementToMonitor;
  9303. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  9304. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  9305. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  9306. }
  9307. };
  9308. FilesInput.prototype.renderFunction = function () {
  9309. if (this._additionnalRenderLoopLogicCallback) {
  9310. this._additionnalRenderLoopLogicCallback();
  9311. }
  9312. if (this._currentScene) {
  9313. if (this._textureLoadingCallback) {
  9314. var remaining = this._currentScene.getWaitingItemsCount();
  9315. if (remaining > 0) {
  9316. this._textureLoadingCallback(remaining);
  9317. }
  9318. }
  9319. this._currentScene.render();
  9320. }
  9321. };
  9322. FilesInput.prototype.drag = function (e) {
  9323. e.stopPropagation();
  9324. e.preventDefault();
  9325. };
  9326. FilesInput.prototype.drop = function (eventDrop) {
  9327. eventDrop.stopPropagation();
  9328. eventDrop.preventDefault();
  9329. this.loadFiles(eventDrop);
  9330. };
  9331. FilesInput.prototype.loadFiles = function (event) {
  9332. if (this._startingProcessingFilesCallback)
  9333. this._startingProcessingFilesCallback();
  9334. // Handling data transfer via drag'n'drop
  9335. if (event && event.dataTransfer && event.dataTransfer.files) {
  9336. this._filesToLoad = event.dataTransfer.files;
  9337. }
  9338. // Handling files from input files
  9339. if (event && event.target && event.target.files) {
  9340. this._filesToLoad = event.target.files;
  9341. }
  9342. if (this._filesToLoad && this._filesToLoad.length > 0) {
  9343. for (var i = 0; i < this._filesToLoad.length; i++) {
  9344. switch (this._filesToLoad[i].type) {
  9345. case "image/jpeg":
  9346. case "image/png":
  9347. case "image/bmp":
  9348. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9349. break;
  9350. case "image/targa":
  9351. case "image/vnd.ms-dds":
  9352. case "audio/wav":
  9353. case "audio/x-wav":
  9354. case "audio/mp3":
  9355. case "audio/mpeg":
  9356. case "audio/mpeg3":
  9357. case "audio/x-mpeg-3":
  9358. case "audio/ogg":
  9359. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9360. break;
  9361. default:
  9362. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  9363. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9364. }
  9365. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  9366. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  9367. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  9368. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  9369. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  9370. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  9371. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  9372. this._sceneFileToLoad = this._filesToLoad[i];
  9373. }
  9374. break;
  9375. }
  9376. }
  9377. this.reload();
  9378. }
  9379. };
  9380. FilesInput.prototype.reload = function () {
  9381. var _this = this;
  9382. var that = this;
  9383. // If a ".babylon" file has been provided
  9384. if (this._sceneFileToLoad) {
  9385. if (this._currentScene) {
  9386. if (BABYLON.Tools.errorsCount > 0) {
  9387. BABYLON.Tools.ClearLogCache();
  9388. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9389. }
  9390. this._engine.stopRenderLoop();
  9391. this._currentScene.dispose();
  9392. }
  9393. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9394. that._currentScene = newScene;
  9395. // Wait for textures and shaders to be ready
  9396. that._currentScene.executeWhenReady(function () {
  9397. // Attach camera to canvas inputs
  9398. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9399. that._currentScene.createDefaultCameraOrLight();
  9400. }
  9401. that._currentScene.activeCamera.attachControl(that._canvas);
  9402. if (that._sceneLoadedCallback) {
  9403. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9404. }
  9405. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9406. });
  9407. }, function (progress) {
  9408. if (_this._progressCallback) {
  9409. _this._progressCallback(progress);
  9410. }
  9411. });
  9412. }
  9413. else {
  9414. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9415. }
  9416. };
  9417. FilesInput.FilesTextures = new Array();
  9418. FilesInput.FilesToLoad = new Array();
  9419. return FilesInput;
  9420. }());
  9421. BABYLON.FilesInput = FilesInput;
  9422. })(BABYLON || (BABYLON = {}));
  9423. var BABYLON;
  9424. (function (BABYLON) {
  9425. var IntersectionInfo = (function () {
  9426. function IntersectionInfo(bu, bv, distance) {
  9427. this.bu = bu;
  9428. this.bv = bv;
  9429. this.distance = distance;
  9430. this.faceId = 0;
  9431. this.subMeshId = 0;
  9432. }
  9433. return IntersectionInfo;
  9434. }());
  9435. BABYLON.IntersectionInfo = IntersectionInfo;
  9436. var PickingInfo = (function () {
  9437. function PickingInfo() {
  9438. this.hit = false;
  9439. this.distance = 0;
  9440. this.pickedPoint = null;
  9441. this.pickedMesh = null;
  9442. this.bu = 0;
  9443. this.bv = 0;
  9444. this.faceId = -1;
  9445. this.subMeshId = 0;
  9446. this.pickedSprite = null;
  9447. }
  9448. // Methods
  9449. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9450. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9451. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9452. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9453. return null;
  9454. }
  9455. var indices = this.pickedMesh.getIndices();
  9456. var result;
  9457. if (useVerticesNormals) {
  9458. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9459. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9460. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9461. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9462. normal0 = normal0.scale(this.bu);
  9463. normal1 = normal1.scale(this.bv);
  9464. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9465. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9466. }
  9467. else {
  9468. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9469. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9470. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9471. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9472. var p1p2 = vertex1.subtract(vertex2);
  9473. var p3p2 = vertex3.subtract(vertex2);
  9474. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9475. }
  9476. if (useWorldCoordinates) {
  9477. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9478. }
  9479. return BABYLON.Vector3.Normalize(result);
  9480. };
  9481. PickingInfo.prototype.getTextureCoordinates = function () {
  9482. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9483. return null;
  9484. }
  9485. var indices = this.pickedMesh.getIndices();
  9486. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9487. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9488. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9489. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9490. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9491. uv1 = uv1.scale(this.bu);
  9492. uv2 = uv2.scale(this.bv);
  9493. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9494. };
  9495. return PickingInfo;
  9496. }());
  9497. BABYLON.PickingInfo = PickingInfo;
  9498. })(BABYLON || (BABYLON = {}));
  9499. var BABYLON;
  9500. (function (BABYLON) {
  9501. var BoundingSphere = (function () {
  9502. function BoundingSphere(minimum, maximum) {
  9503. this.minimum = minimum;
  9504. this.maximum = maximum;
  9505. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9506. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9507. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9508. this.radius = distance * 0.5;
  9509. this.centerWorld = BABYLON.Vector3.Zero();
  9510. this._update(BABYLON.Matrix.Identity());
  9511. }
  9512. // Methods
  9513. BoundingSphere.prototype._update = function (world) {
  9514. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9515. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9516. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9517. };
  9518. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9519. for (var i = 0; i < 6; i++) {
  9520. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9521. return false;
  9522. }
  9523. return true;
  9524. };
  9525. BoundingSphere.prototype.intersectsPoint = function (point) {
  9526. var x = this.centerWorld.x - point.x;
  9527. var y = this.centerWorld.y - point.y;
  9528. var z = this.centerWorld.z - point.z;
  9529. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9530. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9531. return false;
  9532. return true;
  9533. };
  9534. // Statics
  9535. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9536. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9537. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9538. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9539. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9540. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9541. return false;
  9542. return true;
  9543. };
  9544. return BoundingSphere;
  9545. }());
  9546. BABYLON.BoundingSphere = BoundingSphere;
  9547. })(BABYLON || (BABYLON = {}));
  9548. var BABYLON;
  9549. (function (BABYLON) {
  9550. var BoundingBox = (function () {
  9551. function BoundingBox(minimum, maximum) {
  9552. this.minimum = minimum;
  9553. this.maximum = maximum;
  9554. this.vectors = new Array();
  9555. this.vectorsWorld = new Array();
  9556. // Bounding vectors
  9557. this.vectors.push(this.minimum.clone());
  9558. this.vectors.push(this.maximum.clone());
  9559. this.vectors.push(this.minimum.clone());
  9560. this.vectors[2].x = this.maximum.x;
  9561. this.vectors.push(this.minimum.clone());
  9562. this.vectors[3].y = this.maximum.y;
  9563. this.vectors.push(this.minimum.clone());
  9564. this.vectors[4].z = this.maximum.z;
  9565. this.vectors.push(this.maximum.clone());
  9566. this.vectors[5].z = this.minimum.z;
  9567. this.vectors.push(this.maximum.clone());
  9568. this.vectors[6].x = this.minimum.x;
  9569. this.vectors.push(this.maximum.clone());
  9570. this.vectors[7].y = this.minimum.y;
  9571. // OBB
  9572. this.center = this.maximum.add(this.minimum).scale(0.5);
  9573. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9574. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9575. // World
  9576. for (var index = 0; index < this.vectors.length; index++) {
  9577. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9578. }
  9579. this.minimumWorld = BABYLON.Vector3.Zero();
  9580. this.maximumWorld = BABYLON.Vector3.Zero();
  9581. this._update(BABYLON.Matrix.Identity());
  9582. }
  9583. // Methods
  9584. BoundingBox.prototype.getWorldMatrix = function () {
  9585. return this._worldMatrix;
  9586. };
  9587. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9588. this._worldMatrix.copyFrom(matrix);
  9589. return this;
  9590. };
  9591. BoundingBox.prototype._update = function (world) {
  9592. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9593. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9594. for (var index = 0; index < this.vectors.length; index++) {
  9595. var v = this.vectorsWorld[index];
  9596. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9597. if (v.x < this.minimumWorld.x)
  9598. this.minimumWorld.x = v.x;
  9599. if (v.y < this.minimumWorld.y)
  9600. this.minimumWorld.y = v.y;
  9601. if (v.z < this.minimumWorld.z)
  9602. this.minimumWorld.z = v.z;
  9603. if (v.x > this.maximumWorld.x)
  9604. this.maximumWorld.x = v.x;
  9605. if (v.y > this.maximumWorld.y)
  9606. this.maximumWorld.y = v.y;
  9607. if (v.z > this.maximumWorld.z)
  9608. this.maximumWorld.z = v.z;
  9609. }
  9610. // OBB
  9611. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9612. this.center.scaleInPlace(0.5);
  9613. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9614. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9615. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9616. this._worldMatrix = world;
  9617. };
  9618. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9619. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9620. };
  9621. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9622. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9623. };
  9624. BoundingBox.prototype.intersectsPoint = function (point) {
  9625. var delta = -BABYLON.Epsilon;
  9626. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9627. return false;
  9628. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9629. return false;
  9630. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9631. return false;
  9632. return true;
  9633. };
  9634. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9635. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9636. };
  9637. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9638. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9639. return false;
  9640. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9641. return false;
  9642. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9643. return false;
  9644. return true;
  9645. };
  9646. // Statics
  9647. BoundingBox.Intersects = function (box0, box1) {
  9648. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9649. return false;
  9650. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9651. return false;
  9652. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9653. return false;
  9654. return true;
  9655. };
  9656. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9657. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9658. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9659. return (num <= (sphereRadius * sphereRadius));
  9660. };
  9661. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9662. for (var p = 0; p < 6; p++) {
  9663. for (var i = 0; i < 8; i++) {
  9664. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9665. return false;
  9666. }
  9667. }
  9668. }
  9669. return true;
  9670. };
  9671. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9672. for (var p = 0; p < 6; p++) {
  9673. var inCount = 8;
  9674. for (var i = 0; i < 8; i++) {
  9675. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9676. --inCount;
  9677. }
  9678. else {
  9679. break;
  9680. }
  9681. }
  9682. if (inCount === 0)
  9683. return false;
  9684. }
  9685. return true;
  9686. };
  9687. return BoundingBox;
  9688. }());
  9689. BABYLON.BoundingBox = BoundingBox;
  9690. })(BABYLON || (BABYLON = {}));
  9691. var BABYLON;
  9692. (function (BABYLON) {
  9693. var computeBoxExtents = function (axis, box) {
  9694. var p = BABYLON.Vector3.Dot(box.center, axis);
  9695. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9696. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9697. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9698. var r = r0 + r1 + r2;
  9699. return {
  9700. min: p - r,
  9701. max: p + r
  9702. };
  9703. };
  9704. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  9705. var axisOverlap = function (axis, box0, box1) {
  9706. var result0 = computeBoxExtents(axis, box0);
  9707. var result1 = computeBoxExtents(axis, box1);
  9708. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  9709. };
  9710. var BoundingInfo = (function () {
  9711. function BoundingInfo(minimum, maximum) {
  9712. this.minimum = minimum;
  9713. this.maximum = maximum;
  9714. this._isLocked = false;
  9715. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  9716. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  9717. }
  9718. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  9719. get: function () {
  9720. return this._isLocked;
  9721. },
  9722. set: function (value) {
  9723. this._isLocked = value;
  9724. },
  9725. enumerable: true,
  9726. configurable: true
  9727. });
  9728. // Methods
  9729. BoundingInfo.prototype.update = function (world) {
  9730. if (this._isLocked) {
  9731. return;
  9732. }
  9733. this.boundingBox._update(world);
  9734. this.boundingSphere._update(world);
  9735. };
  9736. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  9737. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  9738. return false;
  9739. return this.boundingBox.isInFrustum(frustumPlanes);
  9740. };
  9741. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9742. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  9743. };
  9744. BoundingInfo.prototype._checkCollision = function (collider) {
  9745. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  9746. };
  9747. BoundingInfo.prototype.intersectsPoint = function (point) {
  9748. if (!this.boundingSphere.centerWorld) {
  9749. return false;
  9750. }
  9751. if (!this.boundingSphere.intersectsPoint(point)) {
  9752. return false;
  9753. }
  9754. if (!this.boundingBox.intersectsPoint(point)) {
  9755. return false;
  9756. }
  9757. return true;
  9758. };
  9759. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  9760. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  9761. return false;
  9762. }
  9763. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  9764. return false;
  9765. }
  9766. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  9767. return false;
  9768. }
  9769. if (!precise) {
  9770. return true;
  9771. }
  9772. var box0 = this.boundingBox;
  9773. var box1 = boundingInfo.boundingBox;
  9774. if (!axisOverlap(box0.directions[0], box0, box1))
  9775. return false;
  9776. if (!axisOverlap(box0.directions[1], box0, box1))
  9777. return false;
  9778. if (!axisOverlap(box0.directions[2], box0, box1))
  9779. return false;
  9780. if (!axisOverlap(box1.directions[0], box0, box1))
  9781. return false;
  9782. if (!axisOverlap(box1.directions[1], box0, box1))
  9783. return false;
  9784. if (!axisOverlap(box1.directions[2], box0, box1))
  9785. return false;
  9786. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  9787. return false;
  9788. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  9789. return false;
  9790. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  9791. return false;
  9792. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  9793. return false;
  9794. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  9795. return false;
  9796. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  9797. return false;
  9798. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  9799. return false;
  9800. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  9801. return false;
  9802. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  9803. return false;
  9804. return true;
  9805. };
  9806. return BoundingInfo;
  9807. }());
  9808. BABYLON.BoundingInfo = BoundingInfo;
  9809. })(BABYLON || (BABYLON = {}));
  9810. var BABYLON;
  9811. (function (BABYLON) {
  9812. var Ray = (function () {
  9813. function Ray(origin, direction, length) {
  9814. if (length === void 0) { length = Number.MAX_VALUE; }
  9815. this.origin = origin;
  9816. this.direction = direction;
  9817. this.length = length;
  9818. }
  9819. // Methods
  9820. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  9821. var d = 0.0;
  9822. var maxValue = Number.MAX_VALUE;
  9823. var inv;
  9824. var min;
  9825. var max;
  9826. var temp;
  9827. if (Math.abs(this.direction.x) < 0.0000001) {
  9828. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  9829. return false;
  9830. }
  9831. }
  9832. else {
  9833. inv = 1.0 / this.direction.x;
  9834. min = (minimum.x - this.origin.x) * inv;
  9835. max = (maximum.x - this.origin.x) * inv;
  9836. if (max === -Infinity) {
  9837. max = Infinity;
  9838. }
  9839. if (min > max) {
  9840. temp = min;
  9841. min = max;
  9842. max = temp;
  9843. }
  9844. d = Math.max(min, d);
  9845. maxValue = Math.min(max, maxValue);
  9846. if (d > maxValue) {
  9847. return false;
  9848. }
  9849. }
  9850. if (Math.abs(this.direction.y) < 0.0000001) {
  9851. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  9852. return false;
  9853. }
  9854. }
  9855. else {
  9856. inv = 1.0 / this.direction.y;
  9857. min = (minimum.y - this.origin.y) * inv;
  9858. max = (maximum.y - this.origin.y) * inv;
  9859. if (max === -Infinity) {
  9860. max = Infinity;
  9861. }
  9862. if (min > max) {
  9863. temp = min;
  9864. min = max;
  9865. max = temp;
  9866. }
  9867. d = Math.max(min, d);
  9868. maxValue = Math.min(max, maxValue);
  9869. if (d > maxValue) {
  9870. return false;
  9871. }
  9872. }
  9873. if (Math.abs(this.direction.z) < 0.0000001) {
  9874. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  9875. return false;
  9876. }
  9877. }
  9878. else {
  9879. inv = 1.0 / this.direction.z;
  9880. min = (minimum.z - this.origin.z) * inv;
  9881. max = (maximum.z - this.origin.z) * inv;
  9882. if (max === -Infinity) {
  9883. max = Infinity;
  9884. }
  9885. if (min > max) {
  9886. temp = min;
  9887. min = max;
  9888. max = temp;
  9889. }
  9890. d = Math.max(min, d);
  9891. maxValue = Math.min(max, maxValue);
  9892. if (d > maxValue) {
  9893. return false;
  9894. }
  9895. }
  9896. return true;
  9897. };
  9898. Ray.prototype.intersectsBox = function (box) {
  9899. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  9900. };
  9901. Ray.prototype.intersectsSphere = function (sphere) {
  9902. var x = sphere.center.x - this.origin.x;
  9903. var y = sphere.center.y - this.origin.y;
  9904. var z = sphere.center.z - this.origin.z;
  9905. var pyth = (x * x) + (y * y) + (z * z);
  9906. var rr = sphere.radius * sphere.radius;
  9907. if (pyth <= rr) {
  9908. return true;
  9909. }
  9910. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  9911. if (dot < 0.0) {
  9912. return false;
  9913. }
  9914. var temp = pyth - (dot * dot);
  9915. return temp <= rr;
  9916. };
  9917. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  9918. if (!this._edge1) {
  9919. this._edge1 = BABYLON.Vector3.Zero();
  9920. this._edge2 = BABYLON.Vector3.Zero();
  9921. this._pvec = BABYLON.Vector3.Zero();
  9922. this._tvec = BABYLON.Vector3.Zero();
  9923. this._qvec = BABYLON.Vector3.Zero();
  9924. }
  9925. vertex1.subtractToRef(vertex0, this._edge1);
  9926. vertex2.subtractToRef(vertex0, this._edge2);
  9927. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  9928. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  9929. if (det === 0) {
  9930. return null;
  9931. }
  9932. var invdet = 1 / det;
  9933. this.origin.subtractToRef(vertex0, this._tvec);
  9934. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  9935. if (bu < 0 || bu > 1.0) {
  9936. return null;
  9937. }
  9938. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  9939. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  9940. if (bv < 0 || bu + bv > 1.0) {
  9941. return null;
  9942. }
  9943. //check if the distance is longer than the predefined length.
  9944. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  9945. if (distance > this.length) {
  9946. return null;
  9947. }
  9948. return new BABYLON.IntersectionInfo(bu, bv, distance);
  9949. };
  9950. Ray.prototype.intersectsPlane = function (plane) {
  9951. var distance;
  9952. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  9953. if (Math.abs(result1) < 9.99999997475243E-07) {
  9954. return null;
  9955. }
  9956. else {
  9957. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  9958. distance = (-plane.d - result2) / result1;
  9959. if (distance < 0.0) {
  9960. if (distance < -9.99999997475243E-07) {
  9961. return null;
  9962. }
  9963. else {
  9964. return 0;
  9965. }
  9966. }
  9967. return distance;
  9968. }
  9969. };
  9970. /**
  9971. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  9972. * @param sega the first point of the segment to test the intersection against
  9973. * @param segb the second point of the segment to test the intersection against
  9974. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  9975. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  9976. */
  9977. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  9978. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  9979. var u = segb.subtract(sega);
  9980. var v = rsegb.subtract(this.origin);
  9981. var w = sega.subtract(this.origin);
  9982. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  9983. var b = BABYLON.Vector3.Dot(u, v);
  9984. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  9985. var d = BABYLON.Vector3.Dot(u, w);
  9986. var e = BABYLON.Vector3.Dot(v, w);
  9987. var D = a * c - b * b; // always >= 0
  9988. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  9989. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  9990. // compute the line parameters of the two closest points
  9991. if (D < Ray.smallnum) {
  9992. sN = 0.0; // force using point P0 on segment S1
  9993. sD = 1.0; // to prevent possible division by 0.0 later
  9994. tN = e;
  9995. tD = c;
  9996. }
  9997. else {
  9998. sN = (b * e - c * d);
  9999. tN = (a * e - b * d);
  10000. if (sN < 0.0) {
  10001. sN = 0.0;
  10002. tN = e;
  10003. tD = c;
  10004. }
  10005. else if (sN > sD) {
  10006. sN = sD;
  10007. tN = e + b;
  10008. tD = c;
  10009. }
  10010. }
  10011. if (tN < 0.0) {
  10012. tN = 0.0;
  10013. // recompute sc for this edge
  10014. if (-d < 0.0) {
  10015. sN = 0.0;
  10016. }
  10017. else if (-d > a)
  10018. sN = sD;
  10019. else {
  10020. sN = -d;
  10021. sD = a;
  10022. }
  10023. }
  10024. else if (tN > tD) {
  10025. tN = tD;
  10026. // recompute sc for this edge
  10027. if ((-d + b) < 0.0) {
  10028. sN = 0;
  10029. }
  10030. else if ((-d + b) > a) {
  10031. sN = sD;
  10032. }
  10033. else {
  10034. sN = (-d + b);
  10035. sD = a;
  10036. }
  10037. }
  10038. // finally do the division to get sc and tc
  10039. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  10040. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  10041. // get the difference of the two closest points
  10042. var qtc = v.multiplyByFloats(tc, tc, tc);
  10043. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  10044. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  10045. if (isIntersected) {
  10046. return qtc.length();
  10047. }
  10048. return -1;
  10049. };
  10050. // Statics
  10051. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  10052. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  10053. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  10054. var direction = end.subtract(start);
  10055. direction.normalize();
  10056. return new Ray(start, direction);
  10057. };
  10058. /**
  10059. * 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
  10060. * transformed to the given world matrix.
  10061. * @param origin The origin point
  10062. * @param end The end point
  10063. * @param world a matrix to transform the ray to. Default is the identity matrix.
  10064. */
  10065. Ray.CreateNewFromTo = function (origin, end, world) {
  10066. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  10067. var direction = end.subtract(origin);
  10068. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  10069. direction.normalize();
  10070. return Ray.Transform(new Ray(origin, direction, length), world);
  10071. };
  10072. Ray.Transform = function (ray, matrix) {
  10073. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  10074. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  10075. newDirection.normalize();
  10076. return new Ray(newOrigin, newDirection, ray.length);
  10077. };
  10078. Ray.smallnum = 0.00000001;
  10079. Ray.rayl = 10e8;
  10080. return Ray;
  10081. }());
  10082. BABYLON.Ray = Ray;
  10083. })(BABYLON || (BABYLON = {}));
  10084. var BABYLON;
  10085. (function (BABYLON) {
  10086. var AbstractMesh = (function (_super) {
  10087. __extends(AbstractMesh, _super);
  10088. // Constructor
  10089. function AbstractMesh(name, scene) {
  10090. var _this = this;
  10091. _super.call(this, name, scene);
  10092. // Events
  10093. /**
  10094. * An event triggered when the mesh is disposed.
  10095. * @type {BABYLON.Observable}
  10096. */
  10097. this.onDisposeObservable = new BABYLON.Observable();
  10098. /**
  10099. * An event triggered when this mesh collides with another one
  10100. * @type {BABYLON.Observable}
  10101. */
  10102. this.onCollideObservable = new BABYLON.Observable();
  10103. /**
  10104. * An event triggered when the collision's position changes
  10105. * @type {BABYLON.Observable}
  10106. */
  10107. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10108. /**
  10109. * An event triggered after the world matrix is updated
  10110. * @type {BABYLON.Observable}
  10111. */
  10112. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10113. // Properties
  10114. this.definedFacingForward = true; // orientation for POV movement & rotation
  10115. this.position = new BABYLON.Vector3(0, 0, 0);
  10116. this._rotation = new BABYLON.Vector3(0, 0, 0);
  10117. this._scaling = new BABYLON.Vector3(1, 1, 1);
  10118. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10119. this.visibility = 1.0;
  10120. this.alphaIndex = Number.MAX_VALUE;
  10121. this.infiniteDistance = false;
  10122. this.isVisible = true;
  10123. this.isPickable = true;
  10124. this.showBoundingBox = false;
  10125. this.showSubMeshesBoundingBox = false;
  10126. this.isBlocker = false;
  10127. this.renderingGroupId = 0;
  10128. this.receiveShadows = false;
  10129. this.renderOutline = false;
  10130. this.outlineColor = BABYLON.Color3.Red();
  10131. this.outlineWidth = 0.02;
  10132. this.renderOverlay = false;
  10133. this.overlayColor = BABYLON.Color3.Red();
  10134. this.overlayAlpha = 0.5;
  10135. this.hasVertexAlpha = false;
  10136. this.useVertexColors = true;
  10137. this.applyFog = true;
  10138. this.computeBonesUsingShaders = true;
  10139. this.scalingDeterminant = 1;
  10140. this.numBoneInfluencers = 4;
  10141. this.useOctreeForRenderingSelection = true;
  10142. this.useOctreeForPicking = true;
  10143. this.useOctreeForCollisions = true;
  10144. this.layerMask = 0x0FFFFFFF;
  10145. this.alwaysSelectAsActiveMesh = false;
  10146. // Collisions
  10147. this._checkCollisions = false;
  10148. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10149. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10150. this._collider = new BABYLON.Collider();
  10151. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10152. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10153. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10154. // Edges
  10155. this.edgesWidth = 1;
  10156. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10157. // Cache
  10158. this._localWorld = BABYLON.Matrix.Zero();
  10159. this._worldMatrix = BABYLON.Matrix.Zero();
  10160. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10161. this._absolutePosition = BABYLON.Vector3.Zero();
  10162. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10163. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10164. this._isDirty = false;
  10165. this._pivotMatrix = BABYLON.Matrix.Identity();
  10166. this._isDisposed = false;
  10167. this._renderId = 0;
  10168. this._intersectionsInProgress = new Array();
  10169. this._isWorldMatrixFrozen = false;
  10170. this._unIndexed = false;
  10171. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10172. if (collidedMesh === void 0) { collidedMesh = null; }
  10173. //TODO move this to the collision coordinator!
  10174. if (_this.getScene().workerCollisions)
  10175. newPosition.multiplyInPlace(_this._collider.radius);
  10176. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10177. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10178. _this.position.addInPlace(_this._diffPositionForCollisions);
  10179. }
  10180. if (collidedMesh) {
  10181. _this.onCollideObservable.notifyObservers(collidedMesh);
  10182. }
  10183. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10184. };
  10185. scene.addMesh(this);
  10186. }
  10187. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10188. get: function () {
  10189. return AbstractMesh._BILLBOARDMODE_NONE;
  10190. },
  10191. enumerable: true,
  10192. configurable: true
  10193. });
  10194. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10195. get: function () {
  10196. return AbstractMesh._BILLBOARDMODE_X;
  10197. },
  10198. enumerable: true,
  10199. configurable: true
  10200. });
  10201. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10202. get: function () {
  10203. return AbstractMesh._BILLBOARDMODE_Y;
  10204. },
  10205. enumerable: true,
  10206. configurable: true
  10207. });
  10208. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10209. get: function () {
  10210. return AbstractMesh._BILLBOARDMODE_Z;
  10211. },
  10212. enumerable: true,
  10213. configurable: true
  10214. });
  10215. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10216. get: function () {
  10217. return AbstractMesh._BILLBOARDMODE_ALL;
  10218. },
  10219. enumerable: true,
  10220. configurable: true
  10221. });
  10222. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  10223. set: function (callback) {
  10224. if (this._onDisposeObserver) {
  10225. this.onDisposeObservable.remove(this._onDisposeObserver);
  10226. }
  10227. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10228. },
  10229. enumerable: true,
  10230. configurable: true
  10231. });
  10232. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10233. set: function (callback) {
  10234. if (this._onCollideObserver) {
  10235. this.onCollideObservable.remove(this._onCollideObserver);
  10236. }
  10237. this._onCollideObserver = this.onCollideObservable.add(callback);
  10238. },
  10239. enumerable: true,
  10240. configurable: true
  10241. });
  10242. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10243. set: function (callback) {
  10244. if (this._onCollisionPositionChangeObserver) {
  10245. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10246. }
  10247. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10248. },
  10249. enumerable: true,
  10250. configurable: true
  10251. });
  10252. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10253. get: function () {
  10254. return this._skeleton;
  10255. },
  10256. set: function (value) {
  10257. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10258. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10259. }
  10260. if (value && value.needInitialSkinMatrix) {
  10261. value._registerMeshWithPoseMatrix(this);
  10262. }
  10263. this._skeleton = value;
  10264. if (!this._skeleton) {
  10265. this._bonesTransformMatrices = null;
  10266. }
  10267. },
  10268. enumerable: true,
  10269. configurable: true
  10270. });
  10271. /**
  10272. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10273. */
  10274. AbstractMesh.prototype.toString = function (fullDetails) {
  10275. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10276. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10277. if (this._skeleton) {
  10278. ret += ", skeleton: " + this._skeleton.name;
  10279. }
  10280. if (fullDetails) {
  10281. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10282. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10283. }
  10284. return ret;
  10285. };
  10286. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  10287. /**
  10288. * Getting the rotation object.
  10289. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  10290. */
  10291. get: function () {
  10292. return this._rotation;
  10293. },
  10294. set: function (newRotation) {
  10295. this._rotation = newRotation;
  10296. },
  10297. enumerable: true,
  10298. configurable: true
  10299. });
  10300. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  10301. get: function () {
  10302. return this._scaling;
  10303. },
  10304. set: function (newScaling) {
  10305. this._scaling = newScaling;
  10306. if (this.physicsImpostor) {
  10307. this.physicsImpostor.forceUpdate();
  10308. }
  10309. },
  10310. enumerable: true,
  10311. configurable: true
  10312. });
  10313. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  10314. get: function () {
  10315. return this._rotationQuaternion;
  10316. },
  10317. set: function (quaternion) {
  10318. this._rotationQuaternion = quaternion;
  10319. //reset the rotation vector.
  10320. if (quaternion && this.rotation.length()) {
  10321. this.rotation.copyFromFloats(0, 0, 0);
  10322. }
  10323. },
  10324. enumerable: true,
  10325. configurable: true
  10326. });
  10327. // Methods
  10328. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  10329. this._poseMatrix.copyFrom(matrix);
  10330. };
  10331. AbstractMesh.prototype.getPoseMatrix = function () {
  10332. return this._poseMatrix;
  10333. };
  10334. AbstractMesh.prototype.disableEdgesRendering = function () {
  10335. if (this._edgesRenderer !== undefined) {
  10336. this._edgesRenderer.dispose();
  10337. this._edgesRenderer = undefined;
  10338. }
  10339. };
  10340. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  10341. if (epsilon === void 0) { epsilon = 0.95; }
  10342. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  10343. this.disableEdgesRendering();
  10344. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  10345. };
  10346. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10347. get: function () {
  10348. return false;
  10349. },
  10350. enumerable: true,
  10351. configurable: true
  10352. });
  10353. AbstractMesh.prototype.getLOD = function (camera) {
  10354. return this;
  10355. };
  10356. AbstractMesh.prototype.getTotalVertices = function () {
  10357. return 0;
  10358. };
  10359. AbstractMesh.prototype.getIndices = function () {
  10360. return null;
  10361. };
  10362. AbstractMesh.prototype.getVerticesData = function (kind) {
  10363. return null;
  10364. };
  10365. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10366. return false;
  10367. };
  10368. AbstractMesh.prototype.getBoundingInfo = function () {
  10369. if (this._masterMesh) {
  10370. return this._masterMesh.getBoundingInfo();
  10371. }
  10372. if (!this._boundingInfo) {
  10373. this._updateBoundingInfo();
  10374. }
  10375. return this._boundingInfo;
  10376. };
  10377. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10378. this._boundingInfo = boundingInfo;
  10379. };
  10380. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10381. get: function () {
  10382. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10383. },
  10384. enumerable: true,
  10385. configurable: true
  10386. });
  10387. AbstractMesh.prototype._preActivate = function () {
  10388. };
  10389. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10390. };
  10391. AbstractMesh.prototype._activate = function (renderId) {
  10392. this._renderId = renderId;
  10393. };
  10394. AbstractMesh.prototype.getWorldMatrix = function () {
  10395. if (this._masterMesh) {
  10396. return this._masterMesh.getWorldMatrix();
  10397. }
  10398. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10399. this.computeWorldMatrix();
  10400. }
  10401. return this._worldMatrix;
  10402. };
  10403. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10404. get: function () {
  10405. return this._worldMatrix;
  10406. },
  10407. enumerable: true,
  10408. configurable: true
  10409. });
  10410. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10411. get: function () {
  10412. return this._absolutePosition;
  10413. },
  10414. enumerable: true,
  10415. configurable: true
  10416. });
  10417. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10418. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10419. this.computeWorldMatrix(true);
  10420. this._isWorldMatrixFrozen = true;
  10421. };
  10422. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10423. this._isWorldMatrixFrozen = false;
  10424. this.computeWorldMatrix(true);
  10425. };
  10426. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10427. get: function () {
  10428. return this._isWorldMatrixFrozen;
  10429. },
  10430. enumerable: true,
  10431. configurable: true
  10432. });
  10433. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10434. axis.normalize();
  10435. if (!this.rotationQuaternion) {
  10436. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10437. this.rotation = BABYLON.Vector3.Zero();
  10438. }
  10439. var rotationQuaternion;
  10440. if (!space || space === BABYLON.Space.LOCAL) {
  10441. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10442. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  10443. }
  10444. else {
  10445. if (this.parent) {
  10446. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10447. invertParentWorldMatrix.invert();
  10448. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10449. }
  10450. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10451. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  10452. }
  10453. };
  10454. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10455. var displacementVector = axis.scale(distance);
  10456. if (!space || space === BABYLON.Space.LOCAL) {
  10457. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10458. this.setPositionWithLocalVector(tempV3);
  10459. }
  10460. else {
  10461. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10462. }
  10463. };
  10464. AbstractMesh.prototype.getAbsolutePosition = function () {
  10465. this.computeWorldMatrix();
  10466. return this._absolutePosition;
  10467. };
  10468. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10469. if (!absolutePosition) {
  10470. return;
  10471. }
  10472. var absolutePositionX;
  10473. var absolutePositionY;
  10474. var absolutePositionZ;
  10475. if (absolutePosition.x === undefined) {
  10476. if (arguments.length < 3) {
  10477. return;
  10478. }
  10479. absolutePositionX = arguments[0];
  10480. absolutePositionY = arguments[1];
  10481. absolutePositionZ = arguments[2];
  10482. }
  10483. else {
  10484. absolutePositionX = absolutePosition.x;
  10485. absolutePositionY = absolutePosition.y;
  10486. absolutePositionZ = absolutePosition.z;
  10487. }
  10488. if (this.parent) {
  10489. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10490. invertParentWorldMatrix.invert();
  10491. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10492. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10493. }
  10494. else {
  10495. this.position.x = absolutePositionX;
  10496. this.position.y = absolutePositionY;
  10497. this.position.z = absolutePositionZ;
  10498. }
  10499. };
  10500. // ================================== Point of View Movement =================================
  10501. /**
  10502. * Perform relative position change from the point of view of behind the front of the mesh.
  10503. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10504. * Supports definition of mesh facing forward or backward.
  10505. * @param {number} amountRight
  10506. * @param {number} amountUp
  10507. * @param {number} amountForward
  10508. */
  10509. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10510. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10511. };
  10512. /**
  10513. * Calculate relative position change from the point of view of behind the front of the mesh.
  10514. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10515. * Supports definition of mesh facing forward or backward.
  10516. * @param {number} amountRight
  10517. * @param {number} amountUp
  10518. * @param {number} amountForward
  10519. */
  10520. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10521. var rotMatrix = new BABYLON.Matrix();
  10522. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10523. rotQuaternion.toRotationMatrix(rotMatrix);
  10524. var translationDelta = BABYLON.Vector3.Zero();
  10525. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10526. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10527. return translationDelta;
  10528. };
  10529. // ================================== Point of View Rotation =================================
  10530. /**
  10531. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10532. * Supports definition of mesh facing forward or backward.
  10533. * @param {number} flipBack
  10534. * @param {number} twirlClockwise
  10535. * @param {number} tiltRight
  10536. */
  10537. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10538. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10539. };
  10540. /**
  10541. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10542. * Supports definition of mesh facing forward or backward.
  10543. * @param {number} flipBack
  10544. * @param {number} twirlClockwise
  10545. * @param {number} tiltRight
  10546. */
  10547. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10548. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10549. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10550. };
  10551. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10552. this._pivotMatrix = matrix;
  10553. this._cache.pivotMatrixUpdated = true;
  10554. };
  10555. AbstractMesh.prototype.getPivotMatrix = function () {
  10556. return this._pivotMatrix;
  10557. };
  10558. AbstractMesh.prototype._isSynchronized = function () {
  10559. if (this._isDirty) {
  10560. return false;
  10561. }
  10562. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10563. return false;
  10564. if (this._cache.pivotMatrixUpdated) {
  10565. return false;
  10566. }
  10567. if (this.infiniteDistance) {
  10568. return false;
  10569. }
  10570. if (!this._cache.position.equals(this.position))
  10571. return false;
  10572. if (this.rotationQuaternion) {
  10573. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10574. return false;
  10575. }
  10576. if (!this._cache.rotation.equals(this.rotation))
  10577. return false;
  10578. if (!this._cache.scaling.equals(this.scaling))
  10579. return false;
  10580. return true;
  10581. };
  10582. AbstractMesh.prototype._initCache = function () {
  10583. _super.prototype._initCache.call(this);
  10584. this._cache.localMatrixUpdated = false;
  10585. this._cache.position = BABYLON.Vector3.Zero();
  10586. this._cache.scaling = BABYLON.Vector3.Zero();
  10587. this._cache.rotation = BABYLON.Vector3.Zero();
  10588. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10589. this._cache.billboardMode = -1;
  10590. };
  10591. AbstractMesh.prototype.markAsDirty = function (property) {
  10592. if (property === "rotation") {
  10593. this.rotationQuaternion = null;
  10594. }
  10595. this._currentRenderId = Number.MAX_VALUE;
  10596. this._isDirty = true;
  10597. };
  10598. AbstractMesh.prototype._updateBoundingInfo = function () {
  10599. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10600. this._boundingInfo.update(this.worldMatrixFromCache);
  10601. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10602. };
  10603. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10604. if (!this.subMeshes) {
  10605. return;
  10606. }
  10607. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10608. var subMesh = this.subMeshes[subIndex];
  10609. if (!subMesh.IsGlobal) {
  10610. subMesh.updateBoundingInfo(matrix);
  10611. }
  10612. }
  10613. };
  10614. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10615. if (this._isWorldMatrixFrozen) {
  10616. return this._worldMatrix;
  10617. }
  10618. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10619. this._currentRenderId = this.getScene().getRenderId();
  10620. return this._worldMatrix;
  10621. }
  10622. this._cache.position.copyFrom(this.position);
  10623. this._cache.scaling.copyFrom(this.scaling);
  10624. this._cache.pivotMatrixUpdated = false;
  10625. this._cache.billboardMode = this.billboardMode;
  10626. this._currentRenderId = this.getScene().getRenderId();
  10627. this._isDirty = false;
  10628. // Scaling
  10629. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  10630. // Rotation
  10631. //rotate, if quaternion is set and rotation was used
  10632. if (this.rotationQuaternion) {
  10633. var len = this.rotation.length();
  10634. if (len) {
  10635. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  10636. this.rotation.copyFromFloats(0, 0, 0);
  10637. }
  10638. }
  10639. if (this.rotationQuaternion) {
  10640. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  10641. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10642. }
  10643. else {
  10644. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  10645. this._cache.rotation.copyFrom(this.rotation);
  10646. }
  10647. // Translation
  10648. if (this.infiniteDistance && !this.parent) {
  10649. var camera = this.getScene().activeCamera;
  10650. if (camera) {
  10651. var cameraWorldMatrix = camera.getWorldMatrix();
  10652. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10653. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  10654. }
  10655. }
  10656. else {
  10657. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  10658. }
  10659. // Composing transformations
  10660. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  10661. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  10662. // Billboarding
  10663. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10664. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  10665. var localPosition = BABYLON.Tmp.Vector3[0];
  10666. if (this.parent && this.parent.getWorldMatrix) {
  10667. this._markSyncedWithParent();
  10668. var parentMatrix;
  10669. if (this._meshToBoneReferal) {
  10670. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10671. parentMatrix = BABYLON.Tmp.Matrix[6];
  10672. }
  10673. else {
  10674. parentMatrix = this.parent.getWorldMatrix();
  10675. }
  10676. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  10677. localPosition = BABYLON.Tmp.Vector3[1];
  10678. }
  10679. var zero = this.getScene().activeCamera.globalPosition.clone();
  10680. if (this.parent && this.parent.position) {
  10681. localPosition.addInPlace(this.parent.position);
  10682. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  10683. }
  10684. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  10685. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10686. zero.x = localPosition.x + BABYLON.Epsilon;
  10687. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10688. zero.y = localPosition.y + BABYLON.Epsilon;
  10689. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10690. zero.z = localPosition.z + BABYLON.Epsilon;
  10691. }
  10692. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  10693. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  10694. BABYLON.Tmp.Matrix[3].invert();
  10695. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  10696. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  10697. }
  10698. // Local world
  10699. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  10700. // Parent
  10701. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10702. this._markSyncedWithParent();
  10703. if (this._meshToBoneReferal) {
  10704. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10705. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  10706. }
  10707. else {
  10708. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10709. }
  10710. }
  10711. else {
  10712. this._worldMatrix.copyFrom(this._localWorld);
  10713. }
  10714. // Bounding info
  10715. this._updateBoundingInfo();
  10716. // Absolute position
  10717. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10718. // Callbacks
  10719. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  10720. if (!this._poseMatrix) {
  10721. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  10722. }
  10723. return this._worldMatrix;
  10724. };
  10725. /**
  10726. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10727. * @param func: callback function to add
  10728. */
  10729. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10730. this.onAfterWorldMatrixUpdateObservable.add(func);
  10731. };
  10732. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10733. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  10734. };
  10735. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10736. this.computeWorldMatrix();
  10737. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10738. };
  10739. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10740. this.computeWorldMatrix();
  10741. var invLocalWorldMatrix = this._localWorld.clone();
  10742. invLocalWorldMatrix.invert();
  10743. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10744. };
  10745. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10746. this.computeWorldMatrix(true);
  10747. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10748. };
  10749. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  10750. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10751. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10752. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10753. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10754. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10755. /// <returns>Mesh oriented towards targetMesh</returns>
  10756. if (yawCor === void 0) { yawCor = 0; }
  10757. if (pitchCor === void 0) { pitchCor = 0; }
  10758. if (rollCor === void 0) { rollCor = 0; }
  10759. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  10760. var dv = AbstractMesh._lookAtVectorCache;
  10761. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  10762. targetPoint.subtractToRef(pos, dv);
  10763. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10764. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10765. var pitch = Math.atan2(dv.y, len);
  10766. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  10767. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  10768. };
  10769. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  10770. this._meshToBoneReferal = affectedMesh;
  10771. this.parent = bone;
  10772. if (bone.getWorldMatrix().determinant() < 0) {
  10773. this.scalingDeterminant *= -1;
  10774. }
  10775. };
  10776. AbstractMesh.prototype.detachFromBone = function () {
  10777. if (this.parent.getWorldMatrix().determinant() < 0) {
  10778. this.scalingDeterminant *= -1;
  10779. }
  10780. this._meshToBoneReferal = null;
  10781. this.parent = null;
  10782. };
  10783. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10784. return this._boundingInfo.isInFrustum(frustumPlanes);
  10785. };
  10786. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10787. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  10788. ;
  10789. };
  10790. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10791. if (!this._boundingInfo || !mesh._boundingInfo) {
  10792. return false;
  10793. }
  10794. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10795. };
  10796. AbstractMesh.prototype.intersectsPoint = function (point) {
  10797. if (!this._boundingInfo) {
  10798. return false;
  10799. }
  10800. return this._boundingInfo.intersectsPoint(point);
  10801. };
  10802. // Physics
  10803. /**
  10804. * @Deprecated. Use new PhysicsImpostor instead.
  10805. * */
  10806. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10807. //legacy support
  10808. if (impostor.impostor) {
  10809. options = impostor;
  10810. impostor = impostor.impostor;
  10811. }
  10812. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  10813. return this.physicsImpostor.physicsBody;
  10814. };
  10815. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10816. return this.physicsImpostor;
  10817. };
  10818. /**
  10819. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  10820. */
  10821. AbstractMesh.prototype.getPhysicsMass = function () {
  10822. return this.physicsImpostor.getParam("mass");
  10823. };
  10824. /**
  10825. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  10826. */
  10827. AbstractMesh.prototype.getPhysicsFriction = function () {
  10828. return this.physicsImpostor.getParam("friction");
  10829. };
  10830. /**
  10831. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  10832. */
  10833. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10834. return this.physicsImpostor.getParam("restitution");
  10835. };
  10836. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10837. if (!camera) {
  10838. camera = this.getScene().activeCamera;
  10839. }
  10840. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10841. };
  10842. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10843. if (!camera) {
  10844. camera = this.getScene().activeCamera;
  10845. }
  10846. return this.absolutePosition.subtract(camera.position).length();
  10847. };
  10848. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10849. if (!this.physicsImpostor) {
  10850. return;
  10851. }
  10852. this.physicsImpostor.applyImpulse(force, contactPoint);
  10853. };
  10854. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10855. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  10856. return;
  10857. }
  10858. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  10859. mainPivot: pivot1,
  10860. connectedPivot: pivot2,
  10861. nativeParams: options
  10862. });
  10863. };
  10864. /**
  10865. * @Deprecated
  10866. */
  10867. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10868. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  10869. this.updatePhysicsBody();
  10870. };
  10871. /**
  10872. * @Deprecated
  10873. * Calling this function is not needed anymore.
  10874. * The physics engine takes care of transofmration automatically.
  10875. */
  10876. AbstractMesh.prototype.updatePhysicsBody = function () {
  10877. //Unneeded
  10878. };
  10879. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  10880. // Collisions
  10881. get: function () {
  10882. return this._checkCollisions;
  10883. },
  10884. set: function (collisionEnabled) {
  10885. this._checkCollisions = collisionEnabled;
  10886. if (this.getScene().workerCollisions) {
  10887. this.getScene().collisionCoordinator.onMeshUpdated(this);
  10888. }
  10889. },
  10890. enumerable: true,
  10891. configurable: true
  10892. });
  10893. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10894. var globalPosition = this.getAbsolutePosition();
  10895. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10896. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10897. this._collider.radius = this.ellipsoid;
  10898. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  10899. };
  10900. // Submeshes octree
  10901. /**
  10902. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10903. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10904. */
  10905. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10906. if (maxCapacity === void 0) { maxCapacity = 64; }
  10907. if (maxDepth === void 0) { maxDepth = 2; }
  10908. if (!this._submeshesOctree) {
  10909. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10910. }
  10911. this.computeWorldMatrix(true);
  10912. // Update octree
  10913. var bbox = this.getBoundingInfo().boundingBox;
  10914. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10915. return this._submeshesOctree;
  10916. };
  10917. // Collisions
  10918. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10919. this._generatePointsArray();
  10920. // Transformation
  10921. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10922. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10923. subMesh._lastColliderWorldVertices = [];
  10924. subMesh._trianglePlanes = [];
  10925. var start = subMesh.verticesStart;
  10926. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10927. for (var i = start; i < end; i++) {
  10928. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10929. }
  10930. }
  10931. // Collide
  10932. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  10933. if (collider.collisionFound) {
  10934. collider.collidedMesh = this;
  10935. }
  10936. };
  10937. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10938. var subMeshes;
  10939. var len;
  10940. // Octrees
  10941. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10942. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10943. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10944. len = intersections.length;
  10945. subMeshes = intersections.data;
  10946. }
  10947. else {
  10948. subMeshes = this.subMeshes;
  10949. len = subMeshes.length;
  10950. }
  10951. for (var index = 0; index < len; index++) {
  10952. var subMesh = subMeshes[index];
  10953. // Bounding test
  10954. if (len > 1 && !subMesh._checkCollision(collider))
  10955. continue;
  10956. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10957. }
  10958. };
  10959. AbstractMesh.prototype._checkCollision = function (collider) {
  10960. // Bounding box test
  10961. if (!this._boundingInfo._checkCollision(collider))
  10962. return;
  10963. // Transformation matrix
  10964. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10965. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10966. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10967. };
  10968. // Picking
  10969. AbstractMesh.prototype._generatePointsArray = function () {
  10970. return false;
  10971. };
  10972. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10973. var pickingInfo = new BABYLON.PickingInfo();
  10974. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10975. return pickingInfo;
  10976. }
  10977. if (!this._generatePointsArray()) {
  10978. return pickingInfo;
  10979. }
  10980. var intersectInfo = null;
  10981. // Octrees
  10982. var subMeshes;
  10983. var len;
  10984. if (this._submeshesOctree && this.useOctreeForPicking) {
  10985. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10986. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10987. len = intersections.length;
  10988. subMeshes = intersections.data;
  10989. }
  10990. else {
  10991. subMeshes = this.subMeshes;
  10992. len = subMeshes.length;
  10993. }
  10994. for (var index = 0; index < len; index++) {
  10995. var subMesh = subMeshes[index];
  10996. // Bounding test
  10997. if (len > 1 && !subMesh.canIntersects(ray))
  10998. continue;
  10999. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  11000. if (currentIntersectInfo) {
  11001. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11002. intersectInfo = currentIntersectInfo;
  11003. intersectInfo.subMeshId = index;
  11004. if (fastCheck) {
  11005. break;
  11006. }
  11007. }
  11008. }
  11009. }
  11010. if (intersectInfo) {
  11011. // Get picked point
  11012. var world = this.getWorldMatrix();
  11013. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  11014. var direction = ray.direction.clone();
  11015. direction = direction.scale(intersectInfo.distance);
  11016. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  11017. var pickedPoint = worldOrigin.add(worldDirection);
  11018. // Return result
  11019. pickingInfo.hit = true;
  11020. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  11021. pickingInfo.pickedPoint = pickedPoint;
  11022. pickingInfo.pickedMesh = this;
  11023. pickingInfo.bu = intersectInfo.bu;
  11024. pickingInfo.bv = intersectInfo.bv;
  11025. pickingInfo.faceId = intersectInfo.faceId;
  11026. pickingInfo.subMeshId = intersectInfo.subMeshId;
  11027. return pickingInfo;
  11028. }
  11029. return pickingInfo;
  11030. };
  11031. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11032. return null;
  11033. };
  11034. AbstractMesh.prototype.releaseSubMeshes = function () {
  11035. if (this.subMeshes) {
  11036. while (this.subMeshes.length) {
  11037. this.subMeshes[0].dispose();
  11038. }
  11039. }
  11040. else {
  11041. this.subMeshes = new Array();
  11042. }
  11043. };
  11044. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  11045. var _this = this;
  11046. var index;
  11047. // Action manager
  11048. if (this.actionManager) {
  11049. this.actionManager.dispose();
  11050. this.actionManager = null;
  11051. }
  11052. // Skeleton
  11053. this.skeleton = null;
  11054. // Animations
  11055. this.getScene().stopAnimation(this);
  11056. // Physics
  11057. if (this.physicsImpostor) {
  11058. this.physicsImpostor.dispose();
  11059. }
  11060. // Intersections in progress
  11061. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  11062. var other = this._intersectionsInProgress[index];
  11063. var pos = other._intersectionsInProgress.indexOf(this);
  11064. other._intersectionsInProgress.splice(pos, 1);
  11065. }
  11066. this._intersectionsInProgress = [];
  11067. // Lights
  11068. var lights = this.getScene().lights;
  11069. lights.forEach(function (light) {
  11070. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  11071. if (meshIndex !== -1) {
  11072. light.includedOnlyMeshes.splice(meshIndex, 1);
  11073. }
  11074. meshIndex = light.excludedMeshes.indexOf(_this);
  11075. if (meshIndex !== -1) {
  11076. light.excludedMeshes.splice(meshIndex, 1);
  11077. }
  11078. // Shadow generators
  11079. var generator = light.getShadowGenerator();
  11080. if (generator) {
  11081. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  11082. if (meshIndex !== -1) {
  11083. generator.getShadowMap().renderList.splice(meshIndex, 1);
  11084. }
  11085. }
  11086. });
  11087. // Edges
  11088. if (this._edgesRenderer) {
  11089. this._edgesRenderer.dispose();
  11090. this._edgesRenderer = null;
  11091. }
  11092. // SubMeshes
  11093. this.releaseSubMeshes();
  11094. // Engine
  11095. this.getScene().getEngine().unbindAllAttributes();
  11096. // Remove from scene
  11097. this.getScene().removeMesh(this);
  11098. if (!doNotRecurse) {
  11099. // Particles
  11100. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  11101. if (this.getScene().particleSystems[index].emitter === this) {
  11102. this.getScene().particleSystems[index].dispose();
  11103. index--;
  11104. }
  11105. }
  11106. // Children
  11107. var objects = this.getDescendants(true);
  11108. for (index = 0; index < objects.length; index++) {
  11109. objects[index].dispose();
  11110. }
  11111. }
  11112. else {
  11113. var childMeshes = this.getChildMeshes(true);
  11114. for (index = 0; index < childMeshes.length; index++) {
  11115. var child = childMeshes[index];
  11116. child.parent = null;
  11117. child.computeWorldMatrix(true);
  11118. }
  11119. }
  11120. _super.prototype.dispose.call(this);
  11121. this.onAfterWorldMatrixUpdateObservable.clear();
  11122. this.onCollideObservable.clear();
  11123. this.onCollisionPositionChangeObservable.clear();
  11124. this._isDisposed = true;
  11125. // Callback
  11126. this.onDisposeObservable.notifyObservers(this);
  11127. this.onDisposeObservable.clear();
  11128. };
  11129. // Statics
  11130. AbstractMesh._BILLBOARDMODE_NONE = 0;
  11131. AbstractMesh._BILLBOARDMODE_X = 1;
  11132. AbstractMesh._BILLBOARDMODE_Y = 2;
  11133. AbstractMesh._BILLBOARDMODE_Z = 4;
  11134. AbstractMesh._BILLBOARDMODE_ALL = 7;
  11135. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  11136. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  11137. return AbstractMesh;
  11138. }(BABYLON.Node));
  11139. BABYLON.AbstractMesh = AbstractMesh;
  11140. })(BABYLON || (BABYLON = {}));
  11141. var BABYLON;
  11142. (function (BABYLON) {
  11143. var Light = (function (_super) {
  11144. __extends(Light, _super);
  11145. function Light(name, scene) {
  11146. _super.call(this, name, scene);
  11147. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  11148. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  11149. this.intensity = 1.0;
  11150. this.range = Number.MAX_VALUE;
  11151. this.includeOnlyWithLayerMask = 0;
  11152. this.includedOnlyMeshes = new Array();
  11153. this.excludedMeshes = new Array();
  11154. this.excludeWithLayerMask = 0;
  11155. this.lightmapMode = 0;
  11156. // PBR Properties.
  11157. this.radius = 0.00001;
  11158. this._excludedMeshesIds = new Array();
  11159. this._includedOnlyMeshesIds = new Array();
  11160. scene.addLight(this);
  11161. }
  11162. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  11163. /**
  11164. * If every light affecting the material is in this lightmapMode,
  11165. * material.lightmapTexture adds or multiplies
  11166. * (depends on material.useLightmapAsShadowmap)
  11167. * after every other light calculations.
  11168. */
  11169. get: function () {
  11170. return Light._LIGHTMAP_DEFAULT;
  11171. },
  11172. enumerable: true,
  11173. configurable: true
  11174. });
  11175. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  11176. /**
  11177. * material.lightmapTexture as only diffuse lighting from this light
  11178. * adds pnly specular lighting from this light
  11179. * adds dynamic shadows
  11180. */
  11181. get: function () {
  11182. return Light._LIGHTMAP_SPECULAR;
  11183. },
  11184. enumerable: true,
  11185. configurable: true
  11186. });
  11187. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  11188. /**
  11189. * material.lightmapTexture as only lighting
  11190. * no light calculation from this light
  11191. * only adds dynamic shadows from this light
  11192. */
  11193. get: function () {
  11194. return Light._LIGHTMAP_SHADOWSONLY;
  11195. },
  11196. enumerable: true,
  11197. configurable: true
  11198. });
  11199. /**
  11200. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11201. */
  11202. Light.prototype.toString = function (fullDetails) {
  11203. var ret = "Name: " + this.name;
  11204. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  11205. if (this.animations) {
  11206. for (var i = 0; i < this.animations.length; i++) {
  11207. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11208. }
  11209. }
  11210. if (fullDetails) {
  11211. }
  11212. return ret;
  11213. };
  11214. Light.prototype.getShadowGenerator = function () {
  11215. return this._shadowGenerator;
  11216. };
  11217. Light.prototype.getAbsolutePosition = function () {
  11218. return BABYLON.Vector3.Zero();
  11219. };
  11220. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  11221. };
  11222. Light.prototype._getWorldMatrix = function () {
  11223. return BABYLON.Matrix.Identity();
  11224. };
  11225. Light.prototype.canAffectMesh = function (mesh) {
  11226. if (!mesh) {
  11227. return true;
  11228. }
  11229. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  11230. return false;
  11231. }
  11232. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  11233. return false;
  11234. }
  11235. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  11236. return false;
  11237. }
  11238. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  11239. return false;
  11240. }
  11241. return true;
  11242. };
  11243. Light.prototype.getWorldMatrix = function () {
  11244. this._currentRenderId = this.getScene().getRenderId();
  11245. var worldMatrix = this._getWorldMatrix();
  11246. if (this.parent && this.parent.getWorldMatrix) {
  11247. if (!this._parentedWorldMatrix) {
  11248. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  11249. }
  11250. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  11251. this._markSyncedWithParent();
  11252. return this._parentedWorldMatrix;
  11253. }
  11254. return worldMatrix;
  11255. };
  11256. Light.prototype.dispose = function () {
  11257. if (this._shadowGenerator) {
  11258. this._shadowGenerator.dispose();
  11259. this._shadowGenerator = null;
  11260. }
  11261. // Animations
  11262. this.getScene().stopAnimation(this);
  11263. // Remove from scene
  11264. this.getScene().removeLight(this);
  11265. _super.prototype.dispose.call(this);
  11266. };
  11267. Light.prototype.getTypeID = function () {
  11268. return 0;
  11269. };
  11270. Light.prototype.clone = function (name) {
  11271. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  11272. };
  11273. Light.prototype.serialize = function () {
  11274. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11275. // Type
  11276. serializationObject.type = this.getTypeID();
  11277. // Parent
  11278. if (this.parent) {
  11279. serializationObject.parentId = this.parent.id;
  11280. }
  11281. // Inclusion / exclusions
  11282. if (this.excludedMeshes.length > 0) {
  11283. serializationObject.excludedMeshesIds = [];
  11284. this.excludedMeshes.forEach(function (mesh) {
  11285. serializationObject.excludedMeshesIds.push(mesh.id);
  11286. });
  11287. }
  11288. if (this.includedOnlyMeshes.length > 0) {
  11289. serializationObject.includedOnlyMeshesIds = [];
  11290. this.includedOnlyMeshes.forEach(function (mesh) {
  11291. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  11292. });
  11293. }
  11294. // Animations
  11295. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11296. serializationObject.ranges = this.serializeAnimationRanges();
  11297. return serializationObject;
  11298. };
  11299. Light.GetConstructorFromName = function (type, name, scene) {
  11300. switch (type) {
  11301. case 0:
  11302. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  11303. case 1:
  11304. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  11305. case 2:
  11306. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  11307. case 3:
  11308. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  11309. }
  11310. };
  11311. Light.Parse = function (parsedLight, scene) {
  11312. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  11313. // Inclusion / exclusions
  11314. if (parsedLight.excludedMeshesIds) {
  11315. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  11316. }
  11317. if (parsedLight.includedOnlyMeshesIds) {
  11318. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  11319. }
  11320. // Parent
  11321. if (parsedLight.parentId) {
  11322. light._waitingParentId = parsedLight.parentId;
  11323. }
  11324. // Animations
  11325. if (parsedLight.animations) {
  11326. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  11327. var parsedAnimation = parsedLight.animations[animationIndex];
  11328. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11329. }
  11330. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  11331. }
  11332. if (parsedLight.autoAnimate) {
  11333. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  11334. }
  11335. return light;
  11336. };
  11337. //lightmapMode Consts
  11338. Light._LIGHTMAP_DEFAULT = 0;
  11339. Light._LIGHTMAP_SPECULAR = 1;
  11340. Light._LIGHTMAP_SHADOWSONLY = 2;
  11341. __decorate([
  11342. BABYLON.serializeAsColor3()
  11343. ], Light.prototype, "diffuse", void 0);
  11344. __decorate([
  11345. BABYLON.serializeAsColor3()
  11346. ], Light.prototype, "specular", void 0);
  11347. __decorate([
  11348. BABYLON.serialize()
  11349. ], Light.prototype, "intensity", void 0);
  11350. __decorate([
  11351. BABYLON.serialize()
  11352. ], Light.prototype, "range", void 0);
  11353. __decorate([
  11354. BABYLON.serialize()
  11355. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  11356. __decorate([
  11357. BABYLON.serialize()
  11358. ], Light.prototype, "excludeWithLayerMask", void 0);
  11359. __decorate([
  11360. BABYLON.serialize()
  11361. ], Light.prototype, "lightmapMode", void 0);
  11362. __decorate([
  11363. BABYLON.serialize()
  11364. ], Light.prototype, "radius", void 0);
  11365. return Light;
  11366. }(BABYLON.Node));
  11367. BABYLON.Light = Light;
  11368. })(BABYLON || (BABYLON = {}));
  11369. var BABYLON;
  11370. (function (BABYLON) {
  11371. var PointLight = (function (_super) {
  11372. __extends(PointLight, _super);
  11373. function PointLight(name, position, scene) {
  11374. _super.call(this, name, scene);
  11375. this.position = position;
  11376. }
  11377. PointLight.prototype.getAbsolutePosition = function () {
  11378. return this.transformedPosition ? this.transformedPosition : this.position;
  11379. };
  11380. PointLight.prototype.computeTransformedPosition = function () {
  11381. if (this.parent && this.parent.getWorldMatrix) {
  11382. if (!this.transformedPosition) {
  11383. this.transformedPosition = BABYLON.Vector3.Zero();
  11384. }
  11385. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11386. return true;
  11387. }
  11388. return false;
  11389. };
  11390. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  11391. if (this.parent && this.parent.getWorldMatrix) {
  11392. this.computeTransformedPosition();
  11393. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  11394. return;
  11395. }
  11396. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  11397. };
  11398. PointLight.prototype.needCube = function () {
  11399. return true;
  11400. };
  11401. PointLight.prototype.supportsVSM = function () {
  11402. return false;
  11403. };
  11404. PointLight.prototype.needRefreshPerFrame = function () {
  11405. return false;
  11406. };
  11407. PointLight.prototype.getShadowDirection = function (faceIndex) {
  11408. switch (faceIndex) {
  11409. case 0:
  11410. return new BABYLON.Vector3(1, 0, 0);
  11411. case 1:
  11412. return new BABYLON.Vector3(-1, 0, 0);
  11413. case 2:
  11414. return new BABYLON.Vector3(0, -1, 0);
  11415. case 3:
  11416. return new BABYLON.Vector3(0, 1, 0);
  11417. case 4:
  11418. return new BABYLON.Vector3(0, 0, 1);
  11419. case 5:
  11420. return new BABYLON.Vector3(0, 0, -1);
  11421. }
  11422. return BABYLON.Vector3.Zero();
  11423. };
  11424. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11425. var activeCamera = this.getScene().activeCamera;
  11426. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11427. };
  11428. PointLight.prototype._getWorldMatrix = function () {
  11429. if (!this._worldMatrix) {
  11430. this._worldMatrix = BABYLON.Matrix.Identity();
  11431. }
  11432. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11433. return this._worldMatrix;
  11434. };
  11435. PointLight.prototype.getTypeID = function () {
  11436. return 0;
  11437. };
  11438. __decorate([
  11439. BABYLON.serializeAsVector3()
  11440. ], PointLight.prototype, "position", void 0);
  11441. return PointLight;
  11442. }(BABYLON.Light));
  11443. BABYLON.PointLight = PointLight;
  11444. })(BABYLON || (BABYLON = {}));
  11445. var BABYLON;
  11446. (function (BABYLON) {
  11447. var SpotLight = (function (_super) {
  11448. __extends(SpotLight, _super);
  11449. function SpotLight(name, position, direction, angle, exponent, scene) {
  11450. _super.call(this, name, scene);
  11451. this.position = position;
  11452. this.direction = direction;
  11453. this.angle = angle;
  11454. this.exponent = exponent;
  11455. }
  11456. SpotLight.prototype.getAbsolutePosition = function () {
  11457. return this.transformedPosition ? this.transformedPosition : this.position;
  11458. };
  11459. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11460. var activeCamera = this.getScene().activeCamera;
  11461. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11462. };
  11463. SpotLight.prototype.needCube = function () {
  11464. return false;
  11465. };
  11466. SpotLight.prototype.supportsVSM = function () {
  11467. return true;
  11468. };
  11469. SpotLight.prototype.needRefreshPerFrame = function () {
  11470. return false;
  11471. };
  11472. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  11473. return this.direction;
  11474. };
  11475. SpotLight.prototype.setDirectionToTarget = function (target) {
  11476. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11477. return this.direction;
  11478. };
  11479. SpotLight.prototype.computeTransformedPosition = function () {
  11480. if (this.parent && this.parent.getWorldMatrix) {
  11481. if (!this.transformedPosition) {
  11482. this.transformedPosition = BABYLON.Vector3.Zero();
  11483. }
  11484. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11485. return true;
  11486. }
  11487. return false;
  11488. };
  11489. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  11490. var normalizeDirection;
  11491. if (this.parent && this.parent.getWorldMatrix) {
  11492. if (!this._transformedDirection) {
  11493. this._transformedDirection = BABYLON.Vector3.Zero();
  11494. }
  11495. this.computeTransformedPosition();
  11496. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11497. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  11498. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  11499. }
  11500. else {
  11501. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  11502. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11503. }
  11504. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  11505. };
  11506. SpotLight.prototype._getWorldMatrix = function () {
  11507. if (!this._worldMatrix) {
  11508. this._worldMatrix = BABYLON.Matrix.Identity();
  11509. }
  11510. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11511. return this._worldMatrix;
  11512. };
  11513. SpotLight.prototype.getTypeID = function () {
  11514. return 2;
  11515. };
  11516. __decorate([
  11517. BABYLON.serializeAsVector3()
  11518. ], SpotLight.prototype, "position", void 0);
  11519. __decorate([
  11520. BABYLON.serializeAsVector3()
  11521. ], SpotLight.prototype, "direction", void 0);
  11522. __decorate([
  11523. BABYLON.serialize()
  11524. ], SpotLight.prototype, "angle", void 0);
  11525. __decorate([
  11526. BABYLON.serialize()
  11527. ], SpotLight.prototype, "exponent", void 0);
  11528. return SpotLight;
  11529. }(BABYLON.Light));
  11530. BABYLON.SpotLight = SpotLight;
  11531. })(BABYLON || (BABYLON = {}));
  11532. var BABYLON;
  11533. (function (BABYLON) {
  11534. var HemisphericLight = (function (_super) {
  11535. __extends(HemisphericLight, _super);
  11536. function HemisphericLight(name, direction, scene) {
  11537. _super.call(this, name, scene);
  11538. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  11539. this.direction = direction;
  11540. }
  11541. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  11542. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  11543. return this.direction;
  11544. };
  11545. HemisphericLight.prototype.getShadowGenerator = function () {
  11546. return null;
  11547. };
  11548. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  11549. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11550. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  11551. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  11552. };
  11553. HemisphericLight.prototype._getWorldMatrix = function () {
  11554. if (!this._worldMatrix) {
  11555. this._worldMatrix = BABYLON.Matrix.Identity();
  11556. }
  11557. return this._worldMatrix;
  11558. };
  11559. HemisphericLight.prototype.getTypeID = function () {
  11560. return 3;
  11561. };
  11562. __decorate([
  11563. BABYLON.serializeAsColor3()
  11564. ], HemisphericLight.prototype, "groundColor", void 0);
  11565. __decorate([
  11566. BABYLON.serializeAsVector3()
  11567. ], HemisphericLight.prototype, "direction", void 0);
  11568. return HemisphericLight;
  11569. }(BABYLON.Light));
  11570. BABYLON.HemisphericLight = HemisphericLight;
  11571. })(BABYLON || (BABYLON = {}));
  11572. var BABYLON;
  11573. (function (BABYLON) {
  11574. var DirectionalLight = (function (_super) {
  11575. __extends(DirectionalLight, _super);
  11576. function DirectionalLight(name, direction, scene) {
  11577. _super.call(this, name, scene);
  11578. this.shadowOrthoScale = 0.5;
  11579. this.autoUpdateExtends = true;
  11580. // Cache
  11581. this._orthoLeft = Number.MAX_VALUE;
  11582. this._orthoRight = Number.MIN_VALUE;
  11583. this._orthoTop = Number.MIN_VALUE;
  11584. this._orthoBottom = Number.MAX_VALUE;
  11585. this.position = direction.scale(-1);
  11586. this.direction = direction;
  11587. }
  11588. DirectionalLight.prototype.getAbsolutePosition = function () {
  11589. return this.transformedPosition ? this.transformedPosition : this.position;
  11590. };
  11591. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  11592. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11593. return this.direction;
  11594. };
  11595. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11596. var activeCamera = this.getScene().activeCamera;
  11597. // Check extends
  11598. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  11599. var tempVector3 = BABYLON.Vector3.Zero();
  11600. this._orthoLeft = Number.MAX_VALUE;
  11601. this._orthoRight = Number.MIN_VALUE;
  11602. this._orthoTop = Number.MIN_VALUE;
  11603. this._orthoBottom = Number.MAX_VALUE;
  11604. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  11605. var mesh = renderList[meshIndex];
  11606. if (!mesh) {
  11607. continue;
  11608. }
  11609. var boundingInfo = mesh.getBoundingInfo();
  11610. if (!boundingInfo) {
  11611. continue;
  11612. }
  11613. var boundingBox = boundingInfo.boundingBox;
  11614. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  11615. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  11616. if (tempVector3.x < this._orthoLeft)
  11617. this._orthoLeft = tempVector3.x;
  11618. if (tempVector3.y < this._orthoBottom)
  11619. this._orthoBottom = tempVector3.y;
  11620. if (tempVector3.x > this._orthoRight)
  11621. this._orthoRight = tempVector3.x;
  11622. if (tempVector3.y > this._orthoTop)
  11623. this._orthoTop = tempVector3.y;
  11624. }
  11625. }
  11626. }
  11627. var xOffset = this._orthoRight - this._orthoLeft;
  11628. var yOffset = this._orthoTop - this._orthoBottom;
  11629. 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);
  11630. };
  11631. DirectionalLight.prototype.supportsVSM = function () {
  11632. return true;
  11633. };
  11634. DirectionalLight.prototype.needRefreshPerFrame = function () {
  11635. return true;
  11636. };
  11637. DirectionalLight.prototype.needCube = function () {
  11638. return false;
  11639. };
  11640. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  11641. return this.direction;
  11642. };
  11643. DirectionalLight.prototype.computeTransformedPosition = function () {
  11644. if (this.parent && this.parent.getWorldMatrix) {
  11645. if (!this.transformedPosition) {
  11646. this.transformedPosition = BABYLON.Vector3.Zero();
  11647. }
  11648. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11649. return true;
  11650. }
  11651. return false;
  11652. };
  11653. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  11654. if (this.parent && this.parent.getWorldMatrix) {
  11655. if (!this._transformedDirection) {
  11656. this._transformedDirection = BABYLON.Vector3.Zero();
  11657. }
  11658. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11659. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  11660. return;
  11661. }
  11662. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  11663. };
  11664. DirectionalLight.prototype._getWorldMatrix = function () {
  11665. if (!this._worldMatrix) {
  11666. this._worldMatrix = BABYLON.Matrix.Identity();
  11667. }
  11668. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11669. return this._worldMatrix;
  11670. };
  11671. DirectionalLight.prototype.getTypeID = function () {
  11672. return 1;
  11673. };
  11674. __decorate([
  11675. BABYLON.serializeAsVector3()
  11676. ], DirectionalLight.prototype, "position", void 0);
  11677. __decorate([
  11678. BABYLON.serializeAsVector3()
  11679. ], DirectionalLight.prototype, "direction", void 0);
  11680. __decorate([
  11681. BABYLON.serialize()
  11682. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  11683. __decorate([
  11684. BABYLON.serialize()
  11685. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  11686. return DirectionalLight;
  11687. }(BABYLON.Light));
  11688. BABYLON.DirectionalLight = DirectionalLight;
  11689. })(BABYLON || (BABYLON = {}));
  11690. var BABYLON;
  11691. (function (BABYLON) {
  11692. var ShadowGenerator = (function () {
  11693. function ShadowGenerator(mapSize, light) {
  11694. var _this = this;
  11695. // Members
  11696. this._filter = ShadowGenerator.FILTER_NONE;
  11697. this.blurScale = 2;
  11698. this._blurBoxOffset = 0;
  11699. this._bias = 0.00005;
  11700. this._lightDirection = BABYLON.Vector3.Zero();
  11701. this.forceBackFacesOnly = false;
  11702. this._darkness = 0;
  11703. this._transparencyShadow = false;
  11704. this._viewMatrix = BABYLON.Matrix.Zero();
  11705. this._projectionMatrix = BABYLON.Matrix.Zero();
  11706. this._transformMatrix = BABYLON.Matrix.Zero();
  11707. this._worldViewProjection = BABYLON.Matrix.Zero();
  11708. this._currentFaceIndex = 0;
  11709. this._currentFaceIndexCache = 0;
  11710. this._useFullFloat = true;
  11711. this._light = light;
  11712. this._scene = light.getScene();
  11713. this._mapSize = mapSize;
  11714. light._shadowGenerator = this;
  11715. // Texture type fallback from float to int if not supported.
  11716. var textureType;
  11717. var caps = this._scene.getEngine().getCaps();
  11718. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  11719. this._useFullFloat = true;
  11720. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  11721. }
  11722. else {
  11723. this._useFullFloat = false;
  11724. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  11725. }
  11726. // Render target
  11727. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  11728. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11729. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11730. this._shadowMap.anisotropicFilteringLevel = 1;
  11731. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11732. this._shadowMap.renderParticles = false;
  11733. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  11734. _this._currentFaceIndex = faceIndex;
  11735. });
  11736. this._shadowMap.onAfterUnbindObservable.add(function () {
  11737. if (!_this.useBlurVarianceShadowMap) {
  11738. return;
  11739. }
  11740. if (!_this._shadowMap2) {
  11741. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  11742. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11743. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11744. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  11745. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  11746. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  11747. effect.setTexture("textureSampler", _this._shadowMap);
  11748. });
  11749. _this.blurBoxOffset = 1;
  11750. }
  11751. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  11752. });
  11753. // Custom render function
  11754. var renderSubMesh = function (subMesh) {
  11755. var mesh = subMesh.getRenderingMesh();
  11756. var scene = _this._scene;
  11757. var engine = scene.getEngine();
  11758. // Culling
  11759. engine.setState(subMesh.getMaterial().backFaceCulling);
  11760. // Managing instances
  11761. var batch = mesh._getInstancesRenderList(subMesh._id);
  11762. if (batch.mustReturn) {
  11763. return;
  11764. }
  11765. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11766. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  11767. engine.enableEffect(_this._effect);
  11768. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  11769. var material = subMesh.getMaterial();
  11770. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  11771. _this._effect.setVector3("lightPosition", _this.getLight().position);
  11772. if (_this.getLight().needCube()) {
  11773. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  11774. }
  11775. // Alpha test
  11776. if (material && material.needAlphaTesting()) {
  11777. var alphaTexture = material.getAlphaTestTexture();
  11778. _this._effect.setTexture("diffuseSampler", alphaTexture);
  11779. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  11780. }
  11781. // Bones
  11782. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11783. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  11784. }
  11785. if (_this.forceBackFacesOnly) {
  11786. engine.setState(true, 0, false, true);
  11787. }
  11788. // Draw
  11789. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  11790. if (_this.forceBackFacesOnly) {
  11791. engine.setState(true, 0, false, false);
  11792. }
  11793. }
  11794. else {
  11795. // Need to reset refresh rate of the shadowMap
  11796. _this._shadowMap.resetRefreshCounter();
  11797. }
  11798. };
  11799. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  11800. var index;
  11801. for (index = 0; index < opaqueSubMeshes.length; index++) {
  11802. renderSubMesh(opaqueSubMeshes.data[index]);
  11803. }
  11804. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  11805. renderSubMesh(alphaTestSubMeshes.data[index]);
  11806. }
  11807. if (_this._transparencyShadow) {
  11808. for (index = 0; index < transparentSubMeshes.length; index++) {
  11809. renderSubMesh(transparentSubMeshes.data[index]);
  11810. }
  11811. }
  11812. };
  11813. this._shadowMap.onClearObservable.add(function (engine) {
  11814. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  11815. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  11816. }
  11817. else {
  11818. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  11819. }
  11820. });
  11821. }
  11822. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  11823. // Static
  11824. get: function () {
  11825. return ShadowGenerator._FILTER_NONE;
  11826. },
  11827. enumerable: true,
  11828. configurable: true
  11829. });
  11830. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  11831. get: function () {
  11832. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  11833. },
  11834. enumerable: true,
  11835. configurable: true
  11836. });
  11837. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  11838. get: function () {
  11839. return ShadowGenerator._FILTER_POISSONSAMPLING;
  11840. },
  11841. enumerable: true,
  11842. configurable: true
  11843. });
  11844. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  11845. get: function () {
  11846. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  11847. },
  11848. enumerable: true,
  11849. configurable: true
  11850. });
  11851. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  11852. get: function () {
  11853. return this._bias;
  11854. },
  11855. set: function (bias) {
  11856. this._bias = bias;
  11857. },
  11858. enumerable: true,
  11859. configurable: true
  11860. });
  11861. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  11862. get: function () {
  11863. return this._blurBoxOffset;
  11864. },
  11865. set: function (value) {
  11866. var _this = this;
  11867. if (this._blurBoxOffset === value) {
  11868. return;
  11869. }
  11870. this._blurBoxOffset = value;
  11871. if (this._boxBlurPostprocess) {
  11872. this._boxBlurPostprocess.dispose();
  11873. }
  11874. 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);
  11875. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  11876. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  11877. });
  11878. },
  11879. enumerable: true,
  11880. configurable: true
  11881. });
  11882. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  11883. get: function () {
  11884. return this._filter;
  11885. },
  11886. set: function (value) {
  11887. if (this._filter === value) {
  11888. return;
  11889. }
  11890. this._filter = value;
  11891. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  11892. this._shadowMap.anisotropicFilteringLevel = 16;
  11893. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  11894. }
  11895. else {
  11896. this._shadowMap.anisotropicFilteringLevel = 1;
  11897. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11898. }
  11899. },
  11900. enumerable: true,
  11901. configurable: true
  11902. });
  11903. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  11904. get: function () {
  11905. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  11906. },
  11907. set: function (value) {
  11908. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11909. },
  11910. enumerable: true,
  11911. configurable: true
  11912. });
  11913. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  11914. get: function () {
  11915. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  11916. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  11917. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  11918. },
  11919. set: function (value) {
  11920. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  11921. },
  11922. enumerable: true,
  11923. configurable: true
  11924. });
  11925. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  11926. get: function () {
  11927. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  11928. },
  11929. set: function (value) {
  11930. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11931. },
  11932. enumerable: true,
  11933. configurable: true
  11934. });
  11935. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  11936. var defines = [];
  11937. if (this._useFullFloat) {
  11938. defines.push("#define FULLFLOAT");
  11939. }
  11940. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  11941. defines.push("#define VSM");
  11942. }
  11943. if (this.getLight().needCube()) {
  11944. defines.push("#define CUBEMAP");
  11945. }
  11946. var attribs = [BABYLON.VertexBuffer.PositionKind];
  11947. var mesh = subMesh.getMesh();
  11948. var material = subMesh.getMaterial();
  11949. // Alpha test
  11950. if (material && material.needAlphaTesting()) {
  11951. defines.push("#define ALPHATEST");
  11952. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11953. attribs.push(BABYLON.VertexBuffer.UVKind);
  11954. defines.push("#define UV1");
  11955. }
  11956. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11957. var alphaTexture = material.getAlphaTestTexture();
  11958. if (alphaTexture.coordinatesIndex === 1) {
  11959. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11960. defines.push("#define UV2");
  11961. }
  11962. }
  11963. }
  11964. // Bones
  11965. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11966. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11967. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11968. if (mesh.numBoneInfluencers > 4) {
  11969. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  11970. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  11971. }
  11972. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  11973. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11974. }
  11975. else {
  11976. defines.push("#define NUM_BONE_INFLUENCERS 0");
  11977. }
  11978. // Instances
  11979. if (useInstances) {
  11980. defines.push("#define INSTANCES");
  11981. attribs.push("world0");
  11982. attribs.push("world1");
  11983. attribs.push("world2");
  11984. attribs.push("world3");
  11985. }
  11986. // Get correct effect
  11987. var join = defines.join("\n");
  11988. if (this._cachedDefines !== join) {
  11989. this._cachedDefines = join;
  11990. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  11991. }
  11992. return this._effect.isReady();
  11993. };
  11994. ShadowGenerator.prototype.getShadowMap = function () {
  11995. return this._shadowMap;
  11996. };
  11997. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  11998. if (this._shadowMap2) {
  11999. return this._shadowMap2;
  12000. }
  12001. return this._shadowMap;
  12002. };
  12003. ShadowGenerator.prototype.getLight = function () {
  12004. return this._light;
  12005. };
  12006. // Methods
  12007. ShadowGenerator.prototype.getTransformMatrix = function () {
  12008. var scene = this._scene;
  12009. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  12010. return this._transformMatrix;
  12011. }
  12012. this._currentRenderID = scene.getRenderId();
  12013. this._currentFaceIndexCache = this._currentFaceIndex;
  12014. var lightPosition = this._light.position;
  12015. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  12016. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  12017. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  12018. }
  12019. if (this._light.computeTransformedPosition()) {
  12020. lightPosition = this._light.transformedPosition;
  12021. }
  12022. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  12023. this._cachedPosition = lightPosition.clone();
  12024. this._cachedDirection = this._lightDirection.clone();
  12025. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  12026. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  12027. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12028. }
  12029. return this._transformMatrix;
  12030. };
  12031. ShadowGenerator.prototype.getDarkness = function () {
  12032. return this._darkness;
  12033. };
  12034. ShadowGenerator.prototype.setDarkness = function (darkness) {
  12035. if (darkness >= 1.0)
  12036. this._darkness = 1.0;
  12037. else if (darkness <= 0.0)
  12038. this._darkness = 0.0;
  12039. else
  12040. this._darkness = darkness;
  12041. };
  12042. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  12043. this._transparencyShadow = hasShadow;
  12044. };
  12045. ShadowGenerator.prototype._packHalf = function (depth) {
  12046. var scale = depth * 255.0;
  12047. var fract = scale - Math.floor(scale);
  12048. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  12049. };
  12050. ShadowGenerator.prototype.dispose = function () {
  12051. this._shadowMap.dispose();
  12052. if (this._shadowMap2) {
  12053. this._shadowMap2.dispose();
  12054. }
  12055. if (this._downSamplePostprocess) {
  12056. this._downSamplePostprocess.dispose();
  12057. }
  12058. if (this._boxBlurPostprocess) {
  12059. this._boxBlurPostprocess.dispose();
  12060. }
  12061. };
  12062. ShadowGenerator.prototype.serialize = function () {
  12063. var serializationObject = {};
  12064. serializationObject.lightId = this._light.id;
  12065. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  12066. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  12067. serializationObject.usePoissonSampling = this.usePoissonSampling;
  12068. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  12069. serializationObject.renderList = [];
  12070. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  12071. var mesh = this.getShadowMap().renderList[meshIndex];
  12072. serializationObject.renderList.push(mesh.id);
  12073. }
  12074. return serializationObject;
  12075. };
  12076. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  12077. //casting to point light, as light is missing the position attr and typescript complains.
  12078. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  12079. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  12080. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  12081. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  12082. meshes.forEach(function (mesh) {
  12083. shadowGenerator.getShadowMap().renderList.push(mesh);
  12084. });
  12085. }
  12086. if (parsedShadowGenerator.usePoissonSampling) {
  12087. shadowGenerator.usePoissonSampling = true;
  12088. }
  12089. else if (parsedShadowGenerator.useVarianceShadowMap) {
  12090. shadowGenerator.useVarianceShadowMap = true;
  12091. }
  12092. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  12093. shadowGenerator.useBlurVarianceShadowMap = true;
  12094. if (parsedShadowGenerator.blurScale) {
  12095. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  12096. }
  12097. if (parsedShadowGenerator.blurBoxOffset) {
  12098. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  12099. }
  12100. }
  12101. if (parsedShadowGenerator.bias !== undefined) {
  12102. shadowGenerator.bias = parsedShadowGenerator.bias;
  12103. }
  12104. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  12105. return shadowGenerator;
  12106. };
  12107. ShadowGenerator._FILTER_NONE = 0;
  12108. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  12109. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  12110. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  12111. return ShadowGenerator;
  12112. }());
  12113. BABYLON.ShadowGenerator = ShadowGenerator;
  12114. })(BABYLON || (BABYLON = {}));
  12115. var BABYLON;
  12116. (function (BABYLON) {
  12117. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  12118. if (boxMin.x > sphereCenter.x + sphereRadius)
  12119. return false;
  12120. if (sphereCenter.x - sphereRadius > boxMax.x)
  12121. return false;
  12122. if (boxMin.y > sphereCenter.y + sphereRadius)
  12123. return false;
  12124. if (sphereCenter.y - sphereRadius > boxMax.y)
  12125. return false;
  12126. if (boxMin.z > sphereCenter.z + sphereRadius)
  12127. return false;
  12128. if (sphereCenter.z - sphereRadius > boxMax.z)
  12129. return false;
  12130. return true;
  12131. };
  12132. var getLowestRoot = (function () {
  12133. var result = { root: 0, found: false };
  12134. return function (a, b, c, maxR) {
  12135. result.root = 0;
  12136. result.found = false;
  12137. var determinant = b * b - 4.0 * a * c;
  12138. if (determinant < 0)
  12139. return result;
  12140. var sqrtD = Math.sqrt(determinant);
  12141. var r1 = (-b - sqrtD) / (2.0 * a);
  12142. var r2 = (-b + sqrtD) / (2.0 * a);
  12143. if (r1 > r2) {
  12144. var temp = r2;
  12145. r2 = r1;
  12146. r1 = temp;
  12147. }
  12148. if (r1 > 0 && r1 < maxR) {
  12149. result.root = r1;
  12150. result.found = true;
  12151. return result;
  12152. }
  12153. if (r2 > 0 && r2 < maxR) {
  12154. result.root = r2;
  12155. result.found = true;
  12156. return result;
  12157. }
  12158. return result;
  12159. };
  12160. })();
  12161. var Collider = (function () {
  12162. function Collider() {
  12163. this.radius = new BABYLON.Vector3(1, 1, 1);
  12164. this.retry = 0;
  12165. this.basePointWorld = BABYLON.Vector3.Zero();
  12166. this.velocityWorld = BABYLON.Vector3.Zero();
  12167. this.normalizedVelocity = BABYLON.Vector3.Zero();
  12168. this._collisionPoint = BABYLON.Vector3.Zero();
  12169. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  12170. this._tempVector = BABYLON.Vector3.Zero();
  12171. this._tempVector2 = BABYLON.Vector3.Zero();
  12172. this._tempVector3 = BABYLON.Vector3.Zero();
  12173. this._tempVector4 = BABYLON.Vector3.Zero();
  12174. this._edge = BABYLON.Vector3.Zero();
  12175. this._baseToVertex = BABYLON.Vector3.Zero();
  12176. this._destinationPoint = BABYLON.Vector3.Zero();
  12177. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  12178. this._displacementVector = BABYLON.Vector3.Zero();
  12179. }
  12180. // Methods
  12181. Collider.prototype._initialize = function (source, dir, e) {
  12182. this.velocity = dir;
  12183. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  12184. this.basePoint = source;
  12185. source.multiplyToRef(this.radius, this.basePointWorld);
  12186. dir.multiplyToRef(this.radius, this.velocityWorld);
  12187. this.velocityWorldLength = this.velocityWorld.length();
  12188. this.epsilon = e;
  12189. this.collisionFound = false;
  12190. };
  12191. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  12192. pa.subtractToRef(point, this._tempVector);
  12193. pb.subtractToRef(point, this._tempVector2);
  12194. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  12195. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12196. if (d < 0)
  12197. return false;
  12198. pc.subtractToRef(point, this._tempVector3);
  12199. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  12200. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12201. if (d < 0)
  12202. return false;
  12203. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  12204. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12205. return d >= 0;
  12206. };
  12207. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  12208. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  12209. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  12210. if (distance > this.velocityWorldLength + max + sphereRadius) {
  12211. return false;
  12212. }
  12213. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  12214. return false;
  12215. return true;
  12216. };
  12217. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  12218. var t0;
  12219. var embeddedInPlane = false;
  12220. //defensive programming, actually not needed.
  12221. if (!trianglePlaneArray) {
  12222. trianglePlaneArray = [];
  12223. }
  12224. if (!trianglePlaneArray[faceIndex]) {
  12225. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  12226. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  12227. }
  12228. var trianglePlane = trianglePlaneArray[faceIndex];
  12229. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  12230. return;
  12231. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  12232. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  12233. if (normalDotVelocity == 0) {
  12234. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  12235. return;
  12236. embeddedInPlane = true;
  12237. t0 = 0;
  12238. }
  12239. else {
  12240. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12241. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12242. if (t0 > t1) {
  12243. var temp = t1;
  12244. t1 = t0;
  12245. t0 = temp;
  12246. }
  12247. if (t0 > 1.0 || t1 < 0.0)
  12248. return;
  12249. if (t0 < 0)
  12250. t0 = 0;
  12251. if (t0 > 1.0)
  12252. t0 = 1.0;
  12253. }
  12254. this._collisionPoint.copyFromFloats(0, 0, 0);
  12255. var found = false;
  12256. var t = 1.0;
  12257. if (!embeddedInPlane) {
  12258. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  12259. this.velocity.scaleToRef(t0, this._tempVector);
  12260. this._planeIntersectionPoint.addInPlace(this._tempVector);
  12261. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  12262. found = true;
  12263. t = t0;
  12264. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  12265. }
  12266. }
  12267. if (!found) {
  12268. var velocitySquaredLength = this.velocity.lengthSquared();
  12269. var a = velocitySquaredLength;
  12270. this.basePoint.subtractToRef(p1, this._tempVector);
  12271. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12272. var c = this._tempVector.lengthSquared() - 1.0;
  12273. var lowestRoot = getLowestRoot(a, b, c, t);
  12274. if (lowestRoot.found) {
  12275. t = lowestRoot.root;
  12276. found = true;
  12277. this._collisionPoint.copyFrom(p1);
  12278. }
  12279. this.basePoint.subtractToRef(p2, this._tempVector);
  12280. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12281. c = this._tempVector.lengthSquared() - 1.0;
  12282. lowestRoot = getLowestRoot(a, b, c, t);
  12283. if (lowestRoot.found) {
  12284. t = lowestRoot.root;
  12285. found = true;
  12286. this._collisionPoint.copyFrom(p2);
  12287. }
  12288. this.basePoint.subtractToRef(p3, this._tempVector);
  12289. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12290. c = this._tempVector.lengthSquared() - 1.0;
  12291. lowestRoot = getLowestRoot(a, b, c, t);
  12292. if (lowestRoot.found) {
  12293. t = lowestRoot.root;
  12294. found = true;
  12295. this._collisionPoint.copyFrom(p3);
  12296. }
  12297. p2.subtractToRef(p1, this._edge);
  12298. p1.subtractToRef(this.basePoint, this._baseToVertex);
  12299. var edgeSquaredLength = this._edge.lengthSquared();
  12300. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12301. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12302. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12303. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12304. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12305. lowestRoot = getLowestRoot(a, b, c, t);
  12306. if (lowestRoot.found) {
  12307. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12308. if (f >= 0.0 && f <= 1.0) {
  12309. t = lowestRoot.root;
  12310. found = true;
  12311. this._edge.scaleInPlace(f);
  12312. p1.addToRef(this._edge, this._collisionPoint);
  12313. }
  12314. }
  12315. p3.subtractToRef(p2, this._edge);
  12316. p2.subtractToRef(this.basePoint, this._baseToVertex);
  12317. edgeSquaredLength = this._edge.lengthSquared();
  12318. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12319. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12320. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12321. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12322. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12323. lowestRoot = getLowestRoot(a, b, c, t);
  12324. if (lowestRoot.found) {
  12325. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12326. if (f >= 0.0 && f <= 1.0) {
  12327. t = lowestRoot.root;
  12328. found = true;
  12329. this._edge.scaleInPlace(f);
  12330. p2.addToRef(this._edge, this._collisionPoint);
  12331. }
  12332. }
  12333. p1.subtractToRef(p3, this._edge);
  12334. p3.subtractToRef(this.basePoint, this._baseToVertex);
  12335. edgeSquaredLength = this._edge.lengthSquared();
  12336. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12337. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12338. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12339. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12340. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12341. lowestRoot = getLowestRoot(a, b, c, t);
  12342. if (lowestRoot.found) {
  12343. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12344. if (f >= 0.0 && f <= 1.0) {
  12345. t = lowestRoot.root;
  12346. found = true;
  12347. this._edge.scaleInPlace(f);
  12348. p3.addToRef(this._edge, this._collisionPoint);
  12349. }
  12350. }
  12351. }
  12352. if (found) {
  12353. var distToCollision = t * this.velocity.length();
  12354. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  12355. if (!this.intersectionPoint) {
  12356. this.intersectionPoint = this._collisionPoint.clone();
  12357. }
  12358. else {
  12359. this.intersectionPoint.copyFrom(this._collisionPoint);
  12360. }
  12361. this.nearestDistance = distToCollision;
  12362. this.collisionFound = true;
  12363. }
  12364. }
  12365. };
  12366. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  12367. for (var i = indexStart; i < indexEnd; i += 3) {
  12368. var p1 = pts[indices[i] - decal];
  12369. var p2 = pts[indices[i + 1] - decal];
  12370. var p3 = pts[indices[i + 2] - decal];
  12371. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  12372. }
  12373. };
  12374. Collider.prototype._getResponse = function (pos, vel) {
  12375. pos.addToRef(vel, this._destinationPoint);
  12376. vel.scaleInPlace((this.nearestDistance / vel.length()));
  12377. this.basePoint.addToRef(vel, pos);
  12378. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  12379. this._slidePlaneNormal.normalize();
  12380. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  12381. pos.addInPlace(this._displacementVector);
  12382. this.intersectionPoint.addInPlace(this._displacementVector);
  12383. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  12384. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  12385. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  12386. };
  12387. return Collider;
  12388. }());
  12389. BABYLON.Collider = Collider;
  12390. })(BABYLON || (BABYLON = {}));
  12391. var BABYLON;
  12392. (function (BABYLON) {
  12393. //WebWorker code will be inserted to this variable.
  12394. BABYLON.CollisionWorker = "";
  12395. (function (WorkerTaskType) {
  12396. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  12397. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  12398. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  12399. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  12400. var WorkerTaskType = BABYLON.WorkerTaskType;
  12401. (function (WorkerReplyType) {
  12402. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  12403. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  12404. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  12405. var WorkerReplyType = BABYLON.WorkerReplyType;
  12406. var CollisionCoordinatorWorker = (function () {
  12407. function CollisionCoordinatorWorker() {
  12408. var _this = this;
  12409. this._scaledPosition = BABYLON.Vector3.Zero();
  12410. this._scaledVelocity = BABYLON.Vector3.Zero();
  12411. this.onMeshUpdated = function (mesh) {
  12412. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  12413. };
  12414. this.onGeometryUpdated = function (geometry) {
  12415. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  12416. };
  12417. this._afterRender = function () {
  12418. if (!_this._init)
  12419. return;
  12420. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  12421. return;
  12422. }
  12423. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  12424. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  12425. if (_this._runningUpdated > 4) {
  12426. return;
  12427. }
  12428. ++_this._runningUpdated;
  12429. var payload = {
  12430. updatedMeshes: _this._addUpdateMeshesList,
  12431. updatedGeometries: _this._addUpdateGeometriesList,
  12432. removedGeometries: _this._toRemoveGeometryArray,
  12433. removedMeshes: _this._toRemoveMeshesArray
  12434. };
  12435. var message = {
  12436. payload: payload,
  12437. taskType: WorkerTaskType.UPDATE
  12438. };
  12439. var serializable = [];
  12440. for (var id in payload.updatedGeometries) {
  12441. if (payload.updatedGeometries.hasOwnProperty(id)) {
  12442. //prepare transferables
  12443. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  12444. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  12445. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  12446. }
  12447. }
  12448. _this._worker.postMessage(message, serializable);
  12449. _this._addUpdateMeshesList = {};
  12450. _this._addUpdateGeometriesList = {};
  12451. _this._toRemoveGeometryArray = [];
  12452. _this._toRemoveMeshesArray = [];
  12453. };
  12454. this._onMessageFromWorker = function (e) {
  12455. var returnData = e.data;
  12456. if (returnData.error != WorkerReplyType.SUCCESS) {
  12457. //TODO what errors can be returned from the worker?
  12458. BABYLON.Tools.Warn("error returned from worker!");
  12459. return;
  12460. }
  12461. switch (returnData.taskType) {
  12462. case WorkerTaskType.INIT:
  12463. _this._init = true;
  12464. //Update the worked with ALL of the scene's current state
  12465. _this._scene.meshes.forEach(function (mesh) {
  12466. _this.onMeshAdded(mesh);
  12467. });
  12468. _this._scene.getGeometries().forEach(function (geometry) {
  12469. _this.onGeometryAdded(geometry);
  12470. });
  12471. break;
  12472. case WorkerTaskType.UPDATE:
  12473. _this._runningUpdated--;
  12474. break;
  12475. case WorkerTaskType.COLLIDE:
  12476. _this._runningCollisionTask = false;
  12477. var returnPayload = returnData.payload;
  12478. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  12479. return;
  12480. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  12481. //cleanup
  12482. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  12483. break;
  12484. }
  12485. };
  12486. this._collisionsCallbackArray = [];
  12487. this._init = false;
  12488. this._runningUpdated = 0;
  12489. this._runningCollisionTask = false;
  12490. this._addUpdateMeshesList = {};
  12491. this._addUpdateGeometriesList = {};
  12492. this._toRemoveGeometryArray = [];
  12493. this._toRemoveMeshesArray = [];
  12494. }
  12495. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12496. if (!this._init)
  12497. return;
  12498. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  12499. return;
  12500. position.divideToRef(collider.radius, this._scaledPosition);
  12501. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12502. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  12503. var payload = {
  12504. collider: {
  12505. position: this._scaledPosition.asArray(),
  12506. velocity: this._scaledVelocity.asArray(),
  12507. radius: collider.radius.asArray()
  12508. },
  12509. collisionId: collisionIndex,
  12510. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  12511. maximumRetry: maximumRetry
  12512. };
  12513. var message = {
  12514. payload: payload,
  12515. taskType: WorkerTaskType.COLLIDE
  12516. };
  12517. this._worker.postMessage(message);
  12518. };
  12519. CollisionCoordinatorWorker.prototype.init = function (scene) {
  12520. this._scene = scene;
  12521. this._scene.registerAfterRender(this._afterRender);
  12522. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  12523. this._worker = new Worker(workerUrl);
  12524. this._worker.onmessage = this._onMessageFromWorker;
  12525. var message = {
  12526. payload: {},
  12527. taskType: WorkerTaskType.INIT
  12528. };
  12529. this._worker.postMessage(message);
  12530. };
  12531. CollisionCoordinatorWorker.prototype.destroy = function () {
  12532. this._scene.unregisterAfterRender(this._afterRender);
  12533. this._worker.terminate();
  12534. };
  12535. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  12536. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  12537. this.onMeshUpdated(mesh);
  12538. };
  12539. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  12540. this._toRemoveMeshesArray.push(mesh.uniqueId);
  12541. };
  12542. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  12543. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  12544. geometry.onGeometryUpdated = this.onGeometryUpdated;
  12545. this.onGeometryUpdated(geometry);
  12546. };
  12547. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  12548. this._toRemoveGeometryArray.push(geometry.id);
  12549. };
  12550. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  12551. var submeshes = [];
  12552. if (mesh.subMeshes) {
  12553. submeshes = mesh.subMeshes.map(function (sm, idx) {
  12554. return {
  12555. position: idx,
  12556. verticesStart: sm.verticesStart,
  12557. verticesCount: sm.verticesCount,
  12558. indexStart: sm.indexStart,
  12559. indexCount: sm.indexCount,
  12560. hasMaterial: !!sm.getMaterial(),
  12561. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12562. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  12563. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12564. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  12565. };
  12566. });
  12567. }
  12568. var geometryId = null;
  12569. if (mesh instanceof BABYLON.Mesh) {
  12570. geometryId = mesh.geometry ? mesh.geometry.id : null;
  12571. }
  12572. else if (mesh instanceof BABYLON.InstancedMesh) {
  12573. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  12574. }
  12575. return {
  12576. uniqueId: mesh.uniqueId,
  12577. id: mesh.id,
  12578. name: mesh.name,
  12579. geometryId: geometryId,
  12580. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12581. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  12582. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12583. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  12584. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  12585. subMeshes: submeshes,
  12586. checkCollisions: mesh.checkCollisions
  12587. };
  12588. };
  12589. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  12590. return {
  12591. id: geometry.id,
  12592. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  12593. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  12594. indices: new Int32Array(geometry.getIndices() || []),
  12595. };
  12596. };
  12597. return CollisionCoordinatorWorker;
  12598. }());
  12599. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  12600. var CollisionCoordinatorLegacy = (function () {
  12601. function CollisionCoordinatorLegacy() {
  12602. this._scaledPosition = BABYLON.Vector3.Zero();
  12603. this._scaledVelocity = BABYLON.Vector3.Zero();
  12604. this._finalPosition = BABYLON.Vector3.Zero();
  12605. }
  12606. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12607. position.divideToRef(collider.radius, this._scaledPosition);
  12608. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12609. collider.collidedMesh = null;
  12610. collider.retry = 0;
  12611. collider.initialVelocity = this._scaledVelocity;
  12612. collider.initialPosition = this._scaledPosition;
  12613. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  12614. this._finalPosition.multiplyInPlace(collider.radius);
  12615. //run the callback
  12616. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  12617. };
  12618. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  12619. this._scene = scene;
  12620. };
  12621. CollisionCoordinatorLegacy.prototype.destroy = function () {
  12622. //Legacy need no destruction method.
  12623. };
  12624. //No update in legacy mode
  12625. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  12626. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  12627. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  12628. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  12629. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  12630. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  12631. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  12632. if (excludedMesh === void 0) { excludedMesh = null; }
  12633. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  12634. if (collider.retry >= maximumRetry) {
  12635. finalPosition.copyFrom(position);
  12636. return;
  12637. }
  12638. collider._initialize(position, velocity, closeDistance);
  12639. // Check all meshes
  12640. for (var index = 0; index < this._scene.meshes.length; index++) {
  12641. var mesh = this._scene.meshes[index];
  12642. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  12643. mesh._checkCollision(collider);
  12644. }
  12645. }
  12646. if (!collider.collisionFound) {
  12647. position.addToRef(velocity, finalPosition);
  12648. return;
  12649. }
  12650. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  12651. collider._getResponse(position, velocity);
  12652. }
  12653. if (velocity.length() <= closeDistance) {
  12654. finalPosition.copyFrom(position);
  12655. return;
  12656. }
  12657. collider.retry++;
  12658. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  12659. };
  12660. return CollisionCoordinatorLegacy;
  12661. }());
  12662. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  12663. })(BABYLON || (BABYLON = {}));
  12664. var BABYLON;
  12665. (function (BABYLON) {
  12666. var Camera = (function (_super) {
  12667. __extends(Camera, _super);
  12668. function Camera(name, position, scene) {
  12669. _super.call(this, name, scene);
  12670. this.upVector = BABYLON.Vector3.Up();
  12671. this.orthoLeft = null;
  12672. this.orthoRight = null;
  12673. this.orthoBottom = null;
  12674. this.orthoTop = null;
  12675. this.fov = 0.8;
  12676. this.minZ = 1.0;
  12677. this.maxZ = 10000.0;
  12678. this.inertia = 0.9;
  12679. this.mode = Camera.PERSPECTIVE_CAMERA;
  12680. this.isIntermediate = false;
  12681. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  12682. this.layerMask = 0x0FFFFFFF;
  12683. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  12684. // Camera rig members
  12685. this.cameraRigMode = Camera.RIG_MODE_NONE;
  12686. this._rigCameras = new Array();
  12687. // Cache
  12688. this._computedViewMatrix = BABYLON.Matrix.Identity();
  12689. this._projectionMatrix = new BABYLON.Matrix();
  12690. this._doNotComputeProjectionMatrix = false;
  12691. this._postProcesses = new Array();
  12692. this._transformMatrix = BABYLON.Matrix.Zero();
  12693. this._webvrViewMatrix = BABYLON.Matrix.Identity();
  12694. this._activeMeshes = new BABYLON.SmartArray(256);
  12695. this._globalPosition = BABYLON.Vector3.Zero();
  12696. this._refreshFrustumPlanes = true;
  12697. scene.addCamera(this);
  12698. if (!scene.activeCamera) {
  12699. scene.activeCamera = this;
  12700. }
  12701. this.position = position;
  12702. }
  12703. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  12704. get: function () {
  12705. return Camera._PERSPECTIVE_CAMERA;
  12706. },
  12707. enumerable: true,
  12708. configurable: true
  12709. });
  12710. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  12711. get: function () {
  12712. return Camera._ORTHOGRAPHIC_CAMERA;
  12713. },
  12714. enumerable: true,
  12715. configurable: true
  12716. });
  12717. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  12718. get: function () {
  12719. return Camera._FOVMODE_VERTICAL_FIXED;
  12720. },
  12721. enumerable: true,
  12722. configurable: true
  12723. });
  12724. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  12725. get: function () {
  12726. return Camera._FOVMODE_HORIZONTAL_FIXED;
  12727. },
  12728. enumerable: true,
  12729. configurable: true
  12730. });
  12731. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  12732. get: function () {
  12733. return Camera._RIG_MODE_NONE;
  12734. },
  12735. enumerable: true,
  12736. configurable: true
  12737. });
  12738. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  12739. get: function () {
  12740. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  12741. },
  12742. enumerable: true,
  12743. configurable: true
  12744. });
  12745. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  12746. get: function () {
  12747. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  12748. },
  12749. enumerable: true,
  12750. configurable: true
  12751. });
  12752. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  12753. get: function () {
  12754. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12755. },
  12756. enumerable: true,
  12757. configurable: true
  12758. });
  12759. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  12760. get: function () {
  12761. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  12762. },
  12763. enumerable: true,
  12764. configurable: true
  12765. });
  12766. Object.defineProperty(Camera, "RIG_MODE_VR", {
  12767. get: function () {
  12768. return Camera._RIG_MODE_VR;
  12769. },
  12770. enumerable: true,
  12771. configurable: true
  12772. });
  12773. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  12774. get: function () {
  12775. return Camera._RIG_MODE_WEBVR;
  12776. },
  12777. enumerable: true,
  12778. configurable: true
  12779. });
  12780. /**
  12781. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12782. */
  12783. Camera.prototype.toString = function (fullDetails) {
  12784. var ret = "Name: " + this.name;
  12785. ret += ", type: " + this.getTypeName();
  12786. if (this.animations) {
  12787. for (var i = 0; i < this.animations.length; i++) {
  12788. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12789. }
  12790. }
  12791. if (fullDetails) {
  12792. }
  12793. return ret;
  12794. };
  12795. Object.defineProperty(Camera.prototype, "globalPosition", {
  12796. get: function () {
  12797. return this._globalPosition;
  12798. },
  12799. enumerable: true,
  12800. configurable: true
  12801. });
  12802. Camera.prototype.getActiveMeshes = function () {
  12803. return this._activeMeshes;
  12804. };
  12805. Camera.prototype.isActiveMesh = function (mesh) {
  12806. return (this._activeMeshes.indexOf(mesh) !== -1);
  12807. };
  12808. //Cache
  12809. Camera.prototype._initCache = function () {
  12810. _super.prototype._initCache.call(this);
  12811. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12812. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12813. this._cache.mode = undefined;
  12814. this._cache.minZ = undefined;
  12815. this._cache.maxZ = undefined;
  12816. this._cache.fov = undefined;
  12817. this._cache.fovMode = undefined;
  12818. this._cache.aspectRatio = undefined;
  12819. this._cache.orthoLeft = undefined;
  12820. this._cache.orthoRight = undefined;
  12821. this._cache.orthoBottom = undefined;
  12822. this._cache.orthoTop = undefined;
  12823. this._cache.renderWidth = undefined;
  12824. this._cache.renderHeight = undefined;
  12825. };
  12826. Camera.prototype._updateCache = function (ignoreParentClass) {
  12827. if (!ignoreParentClass) {
  12828. _super.prototype._updateCache.call(this);
  12829. }
  12830. var engine = this.getEngine();
  12831. this._cache.position.copyFrom(this.position);
  12832. this._cache.upVector.copyFrom(this.upVector);
  12833. this._cache.mode = this.mode;
  12834. this._cache.minZ = this.minZ;
  12835. this._cache.maxZ = this.maxZ;
  12836. this._cache.fov = this.fov;
  12837. this._cache.fovMode = this.fovMode;
  12838. this._cache.aspectRatio = engine.getAspectRatio(this);
  12839. this._cache.orthoLeft = this.orthoLeft;
  12840. this._cache.orthoRight = this.orthoRight;
  12841. this._cache.orthoBottom = this.orthoBottom;
  12842. this._cache.orthoTop = this.orthoTop;
  12843. this._cache.renderWidth = engine.getRenderWidth();
  12844. this._cache.renderHeight = engine.getRenderHeight();
  12845. };
  12846. Camera.prototype._updateFromScene = function () {
  12847. this.updateCache();
  12848. this.update();
  12849. };
  12850. // Synchronized
  12851. Camera.prototype._isSynchronized = function () {
  12852. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  12853. };
  12854. Camera.prototype._isSynchronizedViewMatrix = function () {
  12855. if (!_super.prototype._isSynchronized.call(this))
  12856. return false;
  12857. return this._cache.position.equals(this.position)
  12858. && this._cache.upVector.equals(this.upVector)
  12859. && this.isSynchronizedWithParent();
  12860. };
  12861. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  12862. var check = this._cache.mode === this.mode
  12863. && this._cache.minZ === this.minZ
  12864. && this._cache.maxZ === this.maxZ;
  12865. if (!check) {
  12866. return false;
  12867. }
  12868. var engine = this.getEngine();
  12869. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12870. check = this._cache.fov === this.fov
  12871. && this._cache.fovMode === this.fovMode
  12872. && this._cache.aspectRatio === engine.getAspectRatio(this);
  12873. }
  12874. else {
  12875. check = this._cache.orthoLeft === this.orthoLeft
  12876. && this._cache.orthoRight === this.orthoRight
  12877. && this._cache.orthoBottom === this.orthoBottom
  12878. && this._cache.orthoTop === this.orthoTop
  12879. && this._cache.renderWidth === engine.getRenderWidth()
  12880. && this._cache.renderHeight === engine.getRenderHeight();
  12881. }
  12882. return check;
  12883. };
  12884. // Controls
  12885. Camera.prototype.attachControl = function (element, noPreventDefault) {
  12886. };
  12887. Camera.prototype.detachControl = function (element) {
  12888. };
  12889. Camera.prototype.update = function () {
  12890. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12891. this._updateRigCameras();
  12892. }
  12893. this._checkInputs();
  12894. };
  12895. Camera.prototype._checkInputs = function () {
  12896. };
  12897. Camera.prototype._cascadePostProcessesToRigCams = function () {
  12898. // invalidate framebuffer
  12899. if (this._postProcesses.length > 0) {
  12900. this._postProcesses[0].markTextureDirty();
  12901. }
  12902. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  12903. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  12904. var cam = this._rigCameras[i];
  12905. var rigPostProcess = cam._rigPostProcess;
  12906. // for VR rig, there does not have to be a post process
  12907. if (rigPostProcess) {
  12908. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  12909. if (isPass) {
  12910. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  12911. cam.isIntermediate = this._postProcesses.length === 0;
  12912. }
  12913. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  12914. rigPostProcess.markTextureDirty();
  12915. }
  12916. else {
  12917. cam._postProcesses = this._postProcesses.slice(0);
  12918. }
  12919. }
  12920. };
  12921. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  12922. if (insertAt === void 0) { insertAt = null; }
  12923. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  12924. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  12925. return 0;
  12926. }
  12927. if (insertAt == null || insertAt < 0) {
  12928. this._postProcesses.push(postProcess);
  12929. }
  12930. else {
  12931. this._postProcesses.splice(insertAt, 0, postProcess);
  12932. }
  12933. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12934. return this._postProcesses.indexOf(postProcess);
  12935. };
  12936. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  12937. if (atIndices === void 0) { atIndices = null; }
  12938. var result = [];
  12939. var i;
  12940. var index;
  12941. if (!atIndices) {
  12942. var idx = this._postProcesses.indexOf(postProcess);
  12943. if (idx !== -1) {
  12944. this._postProcesses.splice(idx, 1);
  12945. }
  12946. }
  12947. else {
  12948. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  12949. // iterate descending, so can just splice as we go
  12950. for (i = atIndices.length - 1; i >= 0; i--) {
  12951. if (this._postProcesses[atIndices[i]] !== postProcess) {
  12952. result.push(i);
  12953. continue;
  12954. }
  12955. this._postProcesses.splice(index, 1);
  12956. }
  12957. }
  12958. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12959. return result;
  12960. };
  12961. Camera.prototype.getWorldMatrix = function () {
  12962. if (!this._worldMatrix) {
  12963. this._worldMatrix = BABYLON.Matrix.Identity();
  12964. }
  12965. var viewMatrix = this.getViewMatrix();
  12966. viewMatrix.invertToRef(this._worldMatrix);
  12967. return this._worldMatrix;
  12968. };
  12969. Camera.prototype._getViewMatrix = function () {
  12970. return BABYLON.Matrix.Identity();
  12971. };
  12972. Camera.prototype.getViewMatrix = function (force) {
  12973. this._computedViewMatrix = this._computeViewMatrix(force);
  12974. if (!force && this._isSynchronizedViewMatrix()) {
  12975. return this._computedViewMatrix;
  12976. }
  12977. this._refreshFrustumPlanes = true;
  12978. if (!this.parent || !this.parent.getWorldMatrix) {
  12979. this._globalPosition.copyFrom(this.position);
  12980. }
  12981. else {
  12982. if (!this._worldMatrix) {
  12983. this._worldMatrix = BABYLON.Matrix.Identity();
  12984. }
  12985. this._computedViewMatrix.invertToRef(this._worldMatrix);
  12986. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  12987. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  12988. this._computedViewMatrix.invert();
  12989. this._markSyncedWithParent();
  12990. }
  12991. this._currentRenderId = this.getScene().getRenderId();
  12992. return this._computedViewMatrix;
  12993. };
  12994. Camera.prototype._computeViewMatrix = function (force) {
  12995. if (!force && this._isSynchronizedViewMatrix()) {
  12996. return this._computedViewMatrix;
  12997. }
  12998. this._computedViewMatrix = this._getViewMatrix();
  12999. this._currentRenderId = this.getScene().getRenderId();
  13000. return this._computedViewMatrix;
  13001. };
  13002. Camera.prototype.freezeProjectionMatrix = function (projection) {
  13003. this._doNotComputeProjectionMatrix = true;
  13004. if (projection !== undefined) {
  13005. this._projectionMatrix = projection;
  13006. }
  13007. };
  13008. ;
  13009. Camera.prototype.unfreezeProjectionMatrix = function () {
  13010. this._doNotComputeProjectionMatrix = false;
  13011. };
  13012. ;
  13013. Camera.prototype.getProjectionMatrix = function (force) {
  13014. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  13015. return this._projectionMatrix;
  13016. }
  13017. this._refreshFrustumPlanes = true;
  13018. var engine = this.getEngine();
  13019. var scene = this.getScene();
  13020. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13021. if (this.minZ <= 0) {
  13022. this.minZ = 0.1;
  13023. }
  13024. if (scene.useRightHandedSystem) {
  13025. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13026. }
  13027. else {
  13028. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13029. }
  13030. return this._projectionMatrix;
  13031. }
  13032. var halfWidth = engine.getRenderWidth() / 2.0;
  13033. var halfHeight = engine.getRenderHeight() / 2.0;
  13034. if (scene.useRightHandedSystem) {
  13035. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13036. }
  13037. else {
  13038. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13039. }
  13040. return this._projectionMatrix;
  13041. };
  13042. Camera.prototype.getTranformationMatrix = function () {
  13043. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13044. return this._transformMatrix;
  13045. };
  13046. Camera.prototype.updateFrustumPlanes = function () {
  13047. if (!this._refreshFrustumPlanes) {
  13048. return;
  13049. }
  13050. this.getTranformationMatrix();
  13051. if (!this._frustumPlanes) {
  13052. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13053. }
  13054. else {
  13055. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13056. }
  13057. this._refreshFrustumPlanes = false;
  13058. };
  13059. Camera.prototype.isInFrustum = function (target) {
  13060. this.updateFrustumPlanes();
  13061. return target.isInFrustum(this._frustumPlanes);
  13062. };
  13063. Camera.prototype.isCompletelyInFrustum = function (target) {
  13064. this.updateFrustumPlanes();
  13065. return target.isCompletelyInFrustum(this._frustumPlanes);
  13066. };
  13067. Camera.prototype.dispose = function () {
  13068. // Animations
  13069. this.getScene().stopAnimation(this);
  13070. // Remove from scene
  13071. this.getScene().removeCamera(this);
  13072. while (this._rigCameras.length > 0) {
  13073. this._rigCameras.pop().dispose();
  13074. }
  13075. // Postprocesses
  13076. for (var i = 0; i < this._postProcesses.length; ++i) {
  13077. this._postProcesses[i].dispose(this);
  13078. }
  13079. _super.prototype.dispose.call(this);
  13080. };
  13081. // ---- Camera rigs section ----
  13082. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  13083. while (this._rigCameras.length > 0) {
  13084. this._rigCameras.pop().dispose();
  13085. }
  13086. this.cameraRigMode = mode;
  13087. this._cameraRigParams = {};
  13088. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  13089. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  13090. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  13091. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  13092. // create the rig cameras, unless none
  13093. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13094. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  13095. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  13096. }
  13097. switch (this.cameraRigMode) {
  13098. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13099. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13100. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  13101. break;
  13102. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13103. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13104. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13105. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13106. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13107. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  13108. break;
  13109. case Camera.RIG_MODE_VR:
  13110. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  13111. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  13112. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13113. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13114. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  13115. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  13116. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  13117. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  13118. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13119. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13120. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  13121. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  13122. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  13123. if (metrics.compensateDistortion) {
  13124. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  13125. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  13126. }
  13127. break;
  13128. case Camera.RIG_MODE_WEBVR:
  13129. if (rigParams.vrDisplay) {
  13130. //var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  13131. //var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  13132. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13133. this._rigCameras[0].setCameraRigParameter("left", true);
  13134. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  13135. //this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  13136. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13137. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13138. //this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  13139. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13140. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  13141. //this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  13142. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13143. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13144. }
  13145. break;
  13146. }
  13147. this._cascadePostProcessesToRigCams();
  13148. this.
  13149. update();
  13150. };
  13151. Camera.prototype._getVRProjectionMatrix = function () {
  13152. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13153. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  13154. return this._projectionMatrix;
  13155. };
  13156. Camera.prototype._getWebVRProjectionMatrix = function () {
  13157. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  13158. //babylon compatible matrix
  13159. [8, 9, 10, 11].forEach(function (num) {
  13160. projectionArray[num] *= -1;
  13161. });
  13162. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  13163. return this._projectionMatrix;
  13164. };
  13165. //Can be used, but we'll use the free camera's view matrix calculation
  13166. Camera.prototype._getWebVRViewMatrix = function () {
  13167. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  13168. //babylon compatible matrix
  13169. [8, 9, 10, 11].forEach(function (num) {
  13170. projectionArray[num] *= -1;
  13171. });
  13172. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._webvrViewMatrix);
  13173. return this._webvrViewMatrix;
  13174. };
  13175. Camera.prototype.setCameraRigParameter = function (name, value) {
  13176. if (!this._cameraRigParams) {
  13177. this._cameraRigParams = {};
  13178. }
  13179. this._cameraRigParams[name] = value;
  13180. //provisionnally:
  13181. if (name === "interaxialDistance") {
  13182. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  13183. }
  13184. };
  13185. /**
  13186. * needs to be overridden by children so sub has required properties to be copied
  13187. */
  13188. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  13189. return null;
  13190. };
  13191. /**
  13192. * May need to be overridden by children
  13193. */
  13194. Camera.prototype._updateRigCameras = function () {
  13195. for (var i = 0; i < this._rigCameras.length; i++) {
  13196. this._rigCameras[i].minZ = this.minZ;
  13197. this._rigCameras[i].maxZ = this.maxZ;
  13198. this._rigCameras[i].fov = this.fov;
  13199. }
  13200. // only update viewport when ANAGLYPH
  13201. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  13202. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  13203. }
  13204. };
  13205. Camera.prototype._setupInputs = function () {
  13206. };
  13207. Camera.prototype.serialize = function () {
  13208. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13209. // Type
  13210. serializationObject.type = this.getTypeName();
  13211. // Parent
  13212. if (this.parent) {
  13213. serializationObject.parentId = this.parent.id;
  13214. }
  13215. if (this.inputs) {
  13216. this.inputs.serialize(serializationObject);
  13217. }
  13218. // Animations
  13219. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13220. serializationObject.ranges = this.serializeAnimationRanges();
  13221. return serializationObject;
  13222. };
  13223. Camera.prototype.getTypeName = function () {
  13224. return "Camera";
  13225. };
  13226. Camera.prototype.clone = function (name) {
  13227. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  13228. };
  13229. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  13230. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  13231. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  13232. switch (type) {
  13233. case "ArcRotateCamera":
  13234. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  13235. case "DeviceOrientationCamera":
  13236. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  13237. case "FollowCamera":
  13238. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  13239. case "ArcFollowCamera":
  13240. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  13241. case "GamepadCamera":
  13242. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13243. case "TouchCamera":
  13244. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  13245. case "VirtualJoysticksCamera":
  13246. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  13247. case "WebVRFreeCamera":
  13248. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13249. case "VRDeviceOrientationFreeCamera":
  13250. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13251. case "AnaglyphArcRotateCamera":
  13252. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13253. case "AnaglyphFreeCamera":
  13254. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13255. case "AnaglyphGamepadCamera":
  13256. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13257. case "AnaglyphUniversalCamera":
  13258. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13259. case "StereoscopicArcRotateCamera":
  13260. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13261. case "StereoscopicFreeCamera":
  13262. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13263. case "StereoscopicGamepadCamera":
  13264. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13265. case "StereoscopicUniversalCamera":
  13266. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13267. case "FreeCamera":
  13268. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13269. default:
  13270. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13271. }
  13272. };
  13273. Camera.Parse = function (parsedCamera, scene) {
  13274. var type = parsedCamera.type;
  13275. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13276. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13277. // Parent
  13278. if (parsedCamera.parentId) {
  13279. camera._waitingParentId = parsedCamera.parentId;
  13280. }
  13281. //If camera has an input manager, let it parse inputs settings
  13282. if (camera.inputs) {
  13283. camera.inputs.parse(parsedCamera);
  13284. camera._setupInputs();
  13285. }
  13286. // Target
  13287. if (parsedCamera.target) {
  13288. if (camera.setTarget) {
  13289. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13290. }
  13291. }
  13292. // Apply 3d rig, when found
  13293. if (parsedCamera.cameraRigMode) {
  13294. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13295. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13296. }
  13297. // Animations
  13298. if (parsedCamera.animations) {
  13299. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13300. var parsedAnimation = parsedCamera.animations[animationIndex];
  13301. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13302. }
  13303. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13304. }
  13305. if (parsedCamera.autoAnimate) {
  13306. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13307. }
  13308. return camera;
  13309. };
  13310. // Statics
  13311. Camera._PERSPECTIVE_CAMERA = 0;
  13312. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13313. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13314. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13315. Camera._RIG_MODE_NONE = 0;
  13316. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13317. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13318. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13319. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13320. Camera._RIG_MODE_VR = 20;
  13321. Camera._RIG_MODE_WEBVR = 21;
  13322. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13323. __decorate([
  13324. BABYLON.serializeAsVector3()
  13325. ], Camera.prototype, "position", void 0);
  13326. __decorate([
  13327. BABYLON.serializeAsVector3()
  13328. ], Camera.prototype, "upVector", void 0);
  13329. __decorate([
  13330. BABYLON.serialize()
  13331. ], Camera.prototype, "orthoLeft", void 0);
  13332. __decorate([
  13333. BABYLON.serialize()
  13334. ], Camera.prototype, "orthoRight", void 0);
  13335. __decorate([
  13336. BABYLON.serialize()
  13337. ], Camera.prototype, "orthoBottom", void 0);
  13338. __decorate([
  13339. BABYLON.serialize()
  13340. ], Camera.prototype, "orthoTop", void 0);
  13341. __decorate([
  13342. BABYLON.serialize()
  13343. ], Camera.prototype, "fov", void 0);
  13344. __decorate([
  13345. BABYLON.serialize()
  13346. ], Camera.prototype, "minZ", void 0);
  13347. __decorate([
  13348. BABYLON.serialize()
  13349. ], Camera.prototype, "maxZ", void 0);
  13350. __decorate([
  13351. BABYLON.serialize()
  13352. ], Camera.prototype, "inertia", void 0);
  13353. __decorate([
  13354. BABYLON.serialize()
  13355. ], Camera.prototype, "mode", void 0);
  13356. __decorate([
  13357. BABYLON.serialize()
  13358. ], Camera.prototype, "layerMask", void 0);
  13359. __decorate([
  13360. BABYLON.serialize()
  13361. ], Camera.prototype, "fovMode", void 0);
  13362. __decorate([
  13363. BABYLON.serialize()
  13364. ], Camera.prototype, "cameraRigMode", void 0);
  13365. __decorate([
  13366. BABYLON.serialize()
  13367. ], Camera.prototype, "interaxialDistance", void 0);
  13368. __decorate([
  13369. BABYLON.serialize()
  13370. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13371. return Camera;
  13372. }(BABYLON.Node));
  13373. BABYLON.Camera = Camera;
  13374. })(BABYLON || (BABYLON = {}));
  13375. var BABYLON;
  13376. (function (BABYLON) {
  13377. BABYLON.CameraInputTypes = {};
  13378. var CameraInputsManager = (function () {
  13379. function CameraInputsManager(camera) {
  13380. this.attached = {};
  13381. this.camera = camera;
  13382. this.checkInputs = function () { };
  13383. }
  13384. CameraInputsManager.prototype.add = function (input) {
  13385. var type = input.getSimpleName();
  13386. if (this.attached[type]) {
  13387. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  13388. return;
  13389. }
  13390. this.attached[type] = input;
  13391. input.camera = this.camera;
  13392. //for checkInputs, we are dynamically creating a function
  13393. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  13394. if (input.checkInputs) {
  13395. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13396. }
  13397. if (this.attachedElement) {
  13398. input.attachControl(this.attachedElement);
  13399. }
  13400. };
  13401. CameraInputsManager.prototype.remove = function (inputToRemove) {
  13402. for (var cam in this.attached) {
  13403. var input = this.attached[cam];
  13404. if (input === inputToRemove) {
  13405. input.detachControl(this.attachedElement);
  13406. delete this.attached[cam];
  13407. this.rebuildInputCheck();
  13408. }
  13409. }
  13410. };
  13411. CameraInputsManager.prototype.removeByType = function (inputType) {
  13412. for (var cam in this.attached) {
  13413. var input = this.attached[cam];
  13414. if (input.getTypeName() === inputType) {
  13415. input.detachControl(this.attachedElement);
  13416. delete this.attached[cam];
  13417. this.rebuildInputCheck();
  13418. }
  13419. }
  13420. };
  13421. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  13422. var current = this.checkInputs;
  13423. return function () {
  13424. current();
  13425. fn();
  13426. };
  13427. };
  13428. CameraInputsManager.prototype.attachInput = function (input) {
  13429. input.attachControl(this.attachedElement, this.noPreventDefault);
  13430. };
  13431. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  13432. if (this.attachedElement) {
  13433. return;
  13434. }
  13435. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  13436. this.attachedElement = element;
  13437. this.noPreventDefault = noPreventDefault;
  13438. for (var cam in this.attached) {
  13439. var input = this.attached[cam];
  13440. this.attached[cam].attachControl(element, noPreventDefault);
  13441. }
  13442. };
  13443. CameraInputsManager.prototype.detachElement = function (element) {
  13444. if (this.attachedElement !== element) {
  13445. return;
  13446. }
  13447. for (var cam in this.attached) {
  13448. var input = this.attached[cam];
  13449. this.attached[cam].detachControl(element);
  13450. }
  13451. this.attachedElement = null;
  13452. };
  13453. CameraInputsManager.prototype.rebuildInputCheck = function () {
  13454. this.checkInputs = function () { };
  13455. for (var cam in this.attached) {
  13456. var input = this.attached[cam];
  13457. if (input.checkInputs) {
  13458. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13459. }
  13460. }
  13461. };
  13462. CameraInputsManager.prototype.clear = function () {
  13463. if (this.attachedElement) {
  13464. this.detachElement(this.attachedElement);
  13465. }
  13466. this.attached = {};
  13467. this.attachedElement = null;
  13468. this.checkInputs = function () { };
  13469. };
  13470. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  13471. var inputs = {};
  13472. for (var cam in this.attached) {
  13473. var input = this.attached[cam];
  13474. var res = BABYLON.SerializationHelper.Serialize(input);
  13475. inputs[input.getTypeName()] = res;
  13476. }
  13477. serializedCamera.inputsmgr = inputs;
  13478. };
  13479. CameraInputsManager.prototype.parse = function (parsedCamera) {
  13480. var parsedInputs = parsedCamera.inputsmgr;
  13481. if (parsedInputs) {
  13482. this.clear();
  13483. for (var n in parsedInputs) {
  13484. var construct = BABYLON.CameraInputTypes[n];
  13485. if (construct) {
  13486. var parsedinput = parsedInputs[n];
  13487. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  13488. this.add(input);
  13489. }
  13490. }
  13491. }
  13492. else {
  13493. //2016-03-08 this part is for managing backward compatibility
  13494. for (var n in this.attached) {
  13495. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  13496. if (construct) {
  13497. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  13498. this.remove(this.attached[n]);
  13499. this.add(input);
  13500. }
  13501. }
  13502. }
  13503. };
  13504. return CameraInputsManager;
  13505. }());
  13506. BABYLON.CameraInputsManager = CameraInputsManager;
  13507. })(BABYLON || (BABYLON = {}));
  13508. var BABYLON;
  13509. (function (BABYLON) {
  13510. var FreeCameraMouseInput = (function () {
  13511. function FreeCameraMouseInput(touchEnabled) {
  13512. if (touchEnabled === void 0) { touchEnabled = true; }
  13513. this.touchEnabled = touchEnabled;
  13514. this.buttons = [0, 1, 2];
  13515. this.angularSensibility = 2000.0;
  13516. }
  13517. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  13518. var _this = this;
  13519. var engine = this.camera.getEngine();
  13520. if (!this._pointerInput) {
  13521. this._pointerInput = function (p, s) {
  13522. var evt = p.event;
  13523. if (!_this.touchEnabled && evt.pointerType === "touch") {
  13524. return;
  13525. }
  13526. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  13527. return;
  13528. }
  13529. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13530. try {
  13531. evt.srcElement.setPointerCapture(evt.pointerId);
  13532. }
  13533. catch (e) {
  13534. }
  13535. _this.previousPosition = {
  13536. x: evt.clientX,
  13537. y: evt.clientY
  13538. };
  13539. if (!noPreventDefault) {
  13540. evt.preventDefault();
  13541. element.focus();
  13542. }
  13543. }
  13544. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13545. try {
  13546. evt.srcElement.releasePointerCapture(evt.pointerId);
  13547. }
  13548. catch (e) {
  13549. }
  13550. _this.previousPosition = null;
  13551. if (!noPreventDefault) {
  13552. evt.preventDefault();
  13553. }
  13554. }
  13555. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13556. if (!_this.previousPosition || engine.isPointerLock) {
  13557. return;
  13558. }
  13559. var offsetX = evt.clientX - _this.previousPosition.x;
  13560. var offsetY = evt.clientY - _this.previousPosition.y;
  13561. if (_this.camera.getScene().useRightHandedSystem) {
  13562. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13563. }
  13564. else {
  13565. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13566. }
  13567. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13568. _this.previousPosition = {
  13569. x: evt.clientX,
  13570. y: evt.clientY
  13571. };
  13572. if (!noPreventDefault) {
  13573. evt.preventDefault();
  13574. }
  13575. }
  13576. };
  13577. }
  13578. this._onMouseMove = function (evt) {
  13579. if (!engine.isPointerLock) {
  13580. return;
  13581. }
  13582. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13583. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13584. if (_this.camera.getScene().useRightHandedSystem) {
  13585. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13586. }
  13587. else {
  13588. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13589. }
  13590. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13591. _this.previousPosition = null;
  13592. if (!noPreventDefault) {
  13593. evt.preventDefault();
  13594. }
  13595. };
  13596. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13597. element.addEventListener("mousemove", this._onMouseMove, false);
  13598. };
  13599. FreeCameraMouseInput.prototype.detachControl = function (element) {
  13600. if (this._observer && element) {
  13601. this.camera.getScene().onPointerObservable.remove(this._observer);
  13602. element.removeEventListener("mousemove", this._onMouseMove);
  13603. this._observer = null;
  13604. this._onMouseMove = null;
  13605. this.previousPosition = null;
  13606. }
  13607. };
  13608. FreeCameraMouseInput.prototype.getTypeName = function () {
  13609. return "FreeCameraMouseInput";
  13610. };
  13611. FreeCameraMouseInput.prototype.getSimpleName = function () {
  13612. return "mouse";
  13613. };
  13614. __decorate([
  13615. BABYLON.serialize()
  13616. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  13617. __decorate([
  13618. BABYLON.serialize()
  13619. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  13620. return FreeCameraMouseInput;
  13621. }());
  13622. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  13623. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  13624. })(BABYLON || (BABYLON = {}));
  13625. var BABYLON;
  13626. (function (BABYLON) {
  13627. var FreeCameraKeyboardMoveInput = (function () {
  13628. function FreeCameraKeyboardMoveInput() {
  13629. this._keys = [];
  13630. this.keysUp = [38];
  13631. this.keysDown = [40];
  13632. this.keysLeft = [37];
  13633. this.keysRight = [39];
  13634. }
  13635. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13636. var _this = this;
  13637. if (!this._onKeyDown) {
  13638. element.tabIndex = 1;
  13639. this._onKeyDown = function (evt) {
  13640. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13641. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13642. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13643. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13644. var index = _this._keys.indexOf(evt.keyCode);
  13645. if (index === -1) {
  13646. _this._keys.push(evt.keyCode);
  13647. }
  13648. if (!noPreventDefault) {
  13649. evt.preventDefault();
  13650. }
  13651. }
  13652. };
  13653. this._onKeyUp = function (evt) {
  13654. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13655. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13656. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13657. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13658. var index = _this._keys.indexOf(evt.keyCode);
  13659. if (index >= 0) {
  13660. _this._keys.splice(index, 1);
  13661. }
  13662. if (!noPreventDefault) {
  13663. evt.preventDefault();
  13664. }
  13665. }
  13666. };
  13667. element.addEventListener("keydown", this._onKeyDown, false);
  13668. element.addEventListener("keyup", this._onKeyUp, false);
  13669. BABYLON.Tools.RegisterTopRootEvents([
  13670. { name: "blur", handler: this._onLostFocus }
  13671. ]);
  13672. }
  13673. };
  13674. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13675. if (this._onKeyDown) {
  13676. element.removeEventListener("keydown", this._onKeyDown);
  13677. element.removeEventListener("keyup", this._onKeyUp);
  13678. BABYLON.Tools.UnregisterTopRootEvents([
  13679. { name: "blur", handler: this._onLostFocus }
  13680. ]);
  13681. this._keys = [];
  13682. this._onKeyDown = null;
  13683. this._onKeyUp = null;
  13684. }
  13685. };
  13686. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13687. if (this._onKeyDown) {
  13688. var camera = this.camera;
  13689. // Keyboard
  13690. for (var index = 0; index < this._keys.length; index++) {
  13691. var keyCode = this._keys[index];
  13692. var speed = camera._computeLocalCameraSpeed();
  13693. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13694. camera._localDirection.copyFromFloats(-speed, 0, 0);
  13695. }
  13696. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13697. camera._localDirection.copyFromFloats(0, 0, speed);
  13698. }
  13699. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13700. camera._localDirection.copyFromFloats(speed, 0, 0);
  13701. }
  13702. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13703. camera._localDirection.copyFromFloats(0, 0, -speed);
  13704. }
  13705. if (camera.getScene().useRightHandedSystem) {
  13706. camera._localDirection.z *= -1;
  13707. }
  13708. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  13709. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  13710. camera.cameraDirection.addInPlace(camera._transformedDirection);
  13711. }
  13712. }
  13713. };
  13714. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13715. return "FreeCameraKeyboardMoveInput";
  13716. };
  13717. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  13718. this._keys = [];
  13719. };
  13720. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13721. return "keyboard";
  13722. };
  13723. __decorate([
  13724. BABYLON.serialize()
  13725. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13726. __decorate([
  13727. BABYLON.serialize()
  13728. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13729. __decorate([
  13730. BABYLON.serialize()
  13731. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13732. __decorate([
  13733. BABYLON.serialize()
  13734. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13735. return FreeCameraKeyboardMoveInput;
  13736. }());
  13737. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  13738. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  13739. })(BABYLON || (BABYLON = {}));
  13740. var BABYLON;
  13741. (function (BABYLON) {
  13742. var FreeCameraTouchInput = (function () {
  13743. function FreeCameraTouchInput() {
  13744. this._offsetX = null;
  13745. this._offsetY = null;
  13746. this._pointerCount = 0;
  13747. this._pointerPressed = [];
  13748. this.touchAngularSensibility = 200000.0;
  13749. this.touchMoveSensibility = 250.0;
  13750. }
  13751. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  13752. var _this = this;
  13753. var previousPosition;
  13754. if (this._pointerInput === undefined) {
  13755. this._onLostFocus = function (evt) {
  13756. _this._offsetX = null;
  13757. _this._offsetY = null;
  13758. };
  13759. this._pointerInput = function (p, s) {
  13760. var evt = p.event;
  13761. if (evt.pointerType === "mouse") {
  13762. return;
  13763. }
  13764. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13765. if (!noPreventDefault) {
  13766. evt.preventDefault();
  13767. }
  13768. _this._pointerPressed.push(evt.pointerId);
  13769. if (_this._pointerPressed.length !== 1) {
  13770. return;
  13771. }
  13772. previousPosition = {
  13773. x: evt.clientX,
  13774. y: evt.clientY
  13775. };
  13776. }
  13777. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13778. if (!noPreventDefault) {
  13779. evt.preventDefault();
  13780. }
  13781. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13782. if (index === -1) {
  13783. return;
  13784. }
  13785. _this._pointerPressed.splice(index, 1);
  13786. if (index != 0) {
  13787. return;
  13788. }
  13789. previousPosition = null;
  13790. _this._offsetX = null;
  13791. _this._offsetY = null;
  13792. }
  13793. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13794. if (!noPreventDefault) {
  13795. evt.preventDefault();
  13796. }
  13797. if (!previousPosition) {
  13798. return;
  13799. }
  13800. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13801. if (index != 0) {
  13802. return;
  13803. }
  13804. _this._offsetX = evt.clientX - previousPosition.x;
  13805. _this._offsetY = -(evt.clientY - previousPosition.y);
  13806. }
  13807. };
  13808. }
  13809. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13810. element.addEventListener("blur", this._onLostFocus);
  13811. };
  13812. FreeCameraTouchInput.prototype.detachControl = function (element) {
  13813. if (this._pointerInput && element) {
  13814. this.camera.getScene().onPointerObservable.remove(this._observer);
  13815. this._observer = null;
  13816. element.removeEventListener("blur", this._onLostFocus);
  13817. this._onLostFocus = null;
  13818. this._pointerPressed = [];
  13819. this._offsetX = null;
  13820. this._offsetY = null;
  13821. this._pointerCount = 0;
  13822. }
  13823. };
  13824. FreeCameraTouchInput.prototype.checkInputs = function () {
  13825. if (this._offsetX) {
  13826. var camera = this.camera;
  13827. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  13828. if (this._pointerPressed.length > 1) {
  13829. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  13830. }
  13831. else {
  13832. var speed = camera._computeLocalCameraSpeed();
  13833. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  13834. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  13835. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  13836. }
  13837. }
  13838. };
  13839. FreeCameraTouchInput.prototype.getTypeName = function () {
  13840. return "FreeCameraTouchInput";
  13841. };
  13842. FreeCameraTouchInput.prototype.getSimpleName = function () {
  13843. return "touch";
  13844. };
  13845. __decorate([
  13846. BABYLON.serialize()
  13847. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  13848. __decorate([
  13849. BABYLON.serialize()
  13850. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  13851. return FreeCameraTouchInput;
  13852. }());
  13853. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  13854. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  13855. })(BABYLON || (BABYLON = {}));
  13856. var BABYLON;
  13857. (function (BABYLON) {
  13858. var FreeCameraDeviceOrientationInput = (function () {
  13859. function FreeCameraDeviceOrientationInput() {
  13860. var _this = this;
  13861. this._screenOrientationAngle = 0;
  13862. this._screenQuaternion = new BABYLON.Quaternion();
  13863. this._alpha = 0;
  13864. this._beta = 0;
  13865. this._gamma = 0;
  13866. this._orientationChanged = function () {
  13867. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  13868. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  13869. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  13870. };
  13871. this._deviceOrientation = function (evt) {
  13872. _this._alpha = evt.alpha;
  13873. _this._beta = evt.beta;
  13874. _this._gamma = evt.gamma;
  13875. };
  13876. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  13877. this._orientationChanged();
  13878. }
  13879. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  13880. get: function () {
  13881. return this._camera;
  13882. },
  13883. set: function (camera) {
  13884. this._camera = camera;
  13885. if (!this._camera.rotationQuaternion)
  13886. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  13887. },
  13888. enumerable: true,
  13889. configurable: true
  13890. });
  13891. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13892. window.addEventListener("orientationchange", this._orientationChanged);
  13893. window.addEventListener("deviceorientation", this._deviceOrientation);
  13894. //In certain cases, the attach control is called AFTER orientation was changed,
  13895. //So this is needed.
  13896. this._orientationChanged();
  13897. };
  13898. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  13899. window.removeEventListener("orientationchange", this._orientationChanged);
  13900. window.removeEventListener("deviceorientation", this._deviceOrientation);
  13901. };
  13902. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  13903. //if no device orientation provided, don't update the rotation.
  13904. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  13905. if (!this._alpha)
  13906. return;
  13907. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  13908. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  13909. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  13910. //Mirror on XY Plane
  13911. this._camera.rotationQuaternion.z *= -1;
  13912. this._camera.rotationQuaternion.w *= -1;
  13913. };
  13914. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  13915. return "FreeCameraDeviceOrientationInput";
  13916. };
  13917. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  13918. return "deviceOrientation";
  13919. };
  13920. return FreeCameraDeviceOrientationInput;
  13921. }());
  13922. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  13923. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  13924. })(BABYLON || (BABYLON = {}));
  13925. var BABYLON;
  13926. (function (BABYLON) {
  13927. var FreeCameraGamepadInput = (function () {
  13928. function FreeCameraGamepadInput() {
  13929. this.gamepadAngularSensibility = 200;
  13930. this.gamepadMoveSensibility = 40;
  13931. }
  13932. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13933. var _this = this;
  13934. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13935. };
  13936. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  13937. if (this._gamepads) {
  13938. this._gamepads.dispose();
  13939. }
  13940. this.gamepad = null;
  13941. };
  13942. FreeCameraGamepadInput.prototype.checkInputs = function () {
  13943. if (this.gamepad) {
  13944. var camera = this.camera;
  13945. var LSValues = this.gamepad.leftStick;
  13946. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  13947. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13948. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  13949. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  13950. var RSValues = this.gamepad.rightStick;
  13951. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  13952. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  13953. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  13954. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  13955. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  13956. var speed = camera._computeLocalCameraSpeed() * 50.0;
  13957. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  13958. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  13959. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  13960. }
  13961. };
  13962. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13963. // Only the first gamepad can control the camera
  13964. if (gamepad.index === 0) {
  13965. this.gamepad = gamepad;
  13966. }
  13967. };
  13968. FreeCameraGamepadInput.prototype.getTypeName = function () {
  13969. return "FreeCameraGamepadInput";
  13970. };
  13971. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  13972. return "gamepad";
  13973. };
  13974. __decorate([
  13975. BABYLON.serialize()
  13976. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  13977. __decorate([
  13978. BABYLON.serialize()
  13979. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13980. return FreeCameraGamepadInput;
  13981. }());
  13982. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  13983. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  13984. })(BABYLON || (BABYLON = {}));
  13985. var BABYLON;
  13986. (function (BABYLON) {
  13987. var ArcRotateCameraKeyboardMoveInput = (function () {
  13988. function ArcRotateCameraKeyboardMoveInput() {
  13989. this._keys = [];
  13990. this.keysUp = [38];
  13991. this.keysDown = [40];
  13992. this.keysLeft = [37];
  13993. this.keysRight = [39];
  13994. }
  13995. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13996. var _this = this;
  13997. element.tabIndex = 1;
  13998. this._onKeyDown = function (evt) {
  13999. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14000. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14001. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14002. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14003. var index = _this._keys.indexOf(evt.keyCode);
  14004. if (index === -1) {
  14005. _this._keys.push(evt.keyCode);
  14006. }
  14007. if (evt.preventDefault) {
  14008. if (!noPreventDefault) {
  14009. evt.preventDefault();
  14010. }
  14011. }
  14012. }
  14013. };
  14014. this._onKeyUp = function (evt) {
  14015. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14016. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14017. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14018. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14019. var index = _this._keys.indexOf(evt.keyCode);
  14020. if (index >= 0) {
  14021. _this._keys.splice(index, 1);
  14022. }
  14023. if (evt.preventDefault) {
  14024. if (!noPreventDefault) {
  14025. evt.preventDefault();
  14026. }
  14027. }
  14028. }
  14029. };
  14030. this._onLostFocus = function () {
  14031. _this._keys = [];
  14032. };
  14033. element.addEventListener("keydown", this._onKeyDown, false);
  14034. element.addEventListener("keyup", this._onKeyUp, false);
  14035. BABYLON.Tools.RegisterTopRootEvents([
  14036. { name: "blur", handler: this._onLostFocus }
  14037. ]);
  14038. };
  14039. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  14040. if (element) {
  14041. element.removeEventListener("keydown", this._onKeyDown);
  14042. element.removeEventListener("keyup", this._onKeyUp);
  14043. }
  14044. BABYLON.Tools.UnregisterTopRootEvents([
  14045. { name: "blur", handler: this._onLostFocus }
  14046. ]);
  14047. this._keys = [];
  14048. this._onKeyDown = null;
  14049. this._onKeyUp = null;
  14050. this._onLostFocus = null;
  14051. };
  14052. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  14053. if (this._onKeyDown) {
  14054. var camera = this.camera;
  14055. for (var index = 0; index < this._keys.length; index++) {
  14056. var keyCode = this._keys[index];
  14057. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14058. camera.inertialAlphaOffset -= 0.01;
  14059. }
  14060. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14061. camera.inertialBetaOffset -= 0.01;
  14062. }
  14063. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14064. camera.inertialAlphaOffset += 0.01;
  14065. }
  14066. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14067. camera.inertialBetaOffset += 0.01;
  14068. }
  14069. }
  14070. }
  14071. };
  14072. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14073. return "ArcRotateCameraKeyboardMoveInput";
  14074. };
  14075. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14076. return "keyboard";
  14077. };
  14078. __decorate([
  14079. BABYLON.serialize()
  14080. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14081. __decorate([
  14082. BABYLON.serialize()
  14083. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14084. __decorate([
  14085. BABYLON.serialize()
  14086. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14087. __decorate([
  14088. BABYLON.serialize()
  14089. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14090. return ArcRotateCameraKeyboardMoveInput;
  14091. }());
  14092. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  14093. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  14094. })(BABYLON || (BABYLON = {}));
  14095. var BABYLON;
  14096. (function (BABYLON) {
  14097. var ArcRotateCameraMouseWheelInput = (function () {
  14098. function ArcRotateCameraMouseWheelInput() {
  14099. this.wheelPrecision = 3.0;
  14100. }
  14101. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  14102. var _this = this;
  14103. this._wheel = function (p, s) {
  14104. //sanity check - this should be a PointerWheel event.
  14105. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  14106. return;
  14107. var event = p.event;
  14108. var delta = 0;
  14109. if (event.wheelDelta) {
  14110. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  14111. }
  14112. else if (event.detail) {
  14113. delta = -event.detail / _this.wheelPrecision;
  14114. }
  14115. if (delta)
  14116. _this.camera.inertialRadiusOffset += delta;
  14117. if (event.preventDefault) {
  14118. if (!noPreventDefault) {
  14119. event.preventDefault();
  14120. }
  14121. }
  14122. };
  14123. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  14124. };
  14125. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  14126. if (this._observer && element) {
  14127. this.camera.getScene().onPointerObservable.remove(this._observer);
  14128. this._observer = null;
  14129. this._wheel = null;
  14130. }
  14131. };
  14132. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  14133. return "ArcRotateCameraMouseWheelInput";
  14134. };
  14135. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  14136. return "mousewheel";
  14137. };
  14138. __decorate([
  14139. BABYLON.serialize()
  14140. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  14141. return ArcRotateCameraMouseWheelInput;
  14142. }());
  14143. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  14144. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  14145. })(BABYLON || (BABYLON = {}));
  14146. var BABYLON;
  14147. (function (BABYLON) {
  14148. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14149. var ArcRotateCameraPointersInput = (function () {
  14150. function ArcRotateCameraPointersInput() {
  14151. this.buttons = [0, 1, 2];
  14152. this.angularSensibilityX = 1000.0;
  14153. this.angularSensibilityY = 1000.0;
  14154. this.pinchPrecision = 6.0;
  14155. this.panningSensibility = 50.0;
  14156. this._isPanClick = false;
  14157. this.pinchInwards = true;
  14158. }
  14159. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  14160. var _this = this;
  14161. var engine = this.camera.getEngine();
  14162. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  14163. var pointA, pointB;
  14164. var previousPinchDistance = 0;
  14165. this._pointerInput = function (p, s) {
  14166. var evt = p.event;
  14167. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  14168. return;
  14169. }
  14170. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14171. try {
  14172. evt.srcElement.setPointerCapture(evt.pointerId);
  14173. }
  14174. catch (e) {
  14175. }
  14176. // Manage panning with pan button click
  14177. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  14178. // manage pointers
  14179. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  14180. if (pointA === undefined) {
  14181. pointA = cacheSoloPointer;
  14182. }
  14183. else if (pointB === undefined) {
  14184. pointB = cacheSoloPointer;
  14185. }
  14186. if (!noPreventDefault) {
  14187. evt.preventDefault();
  14188. element.focus();
  14189. }
  14190. }
  14191. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14192. try {
  14193. evt.srcElement.releasePointerCapture(evt.pointerId);
  14194. }
  14195. catch (e) {
  14196. }
  14197. cacheSoloPointer = null;
  14198. previousPinchDistance = 0;
  14199. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  14200. //but emptying completly pointers collection is required to fix a bug on iPhone :
  14201. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  14202. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  14203. pointA = pointB = undefined;
  14204. if (!noPreventDefault) {
  14205. evt.preventDefault();
  14206. }
  14207. }
  14208. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14209. if (!noPreventDefault) {
  14210. evt.preventDefault();
  14211. }
  14212. // One button down
  14213. if (pointA && pointB === undefined) {
  14214. if (_this.panningSensibility !== 0 &&
  14215. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  14216. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  14217. _this.camera
  14218. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  14219. _this.camera
  14220. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  14221. }
  14222. else {
  14223. var offsetX = evt.clientX - cacheSoloPointer.x;
  14224. var offsetY = evt.clientY - cacheSoloPointer.y;
  14225. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14226. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14227. }
  14228. cacheSoloPointer.x = evt.clientX;
  14229. cacheSoloPointer.y = evt.clientY;
  14230. }
  14231. else if (pointA && pointB) {
  14232. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  14233. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  14234. ed.x = evt.clientX;
  14235. ed.y = evt.clientY;
  14236. var direction = _this.pinchInwards ? 1 : -1;
  14237. var distX = pointA.x - pointB.x;
  14238. var distY = pointA.y - pointB.y;
  14239. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  14240. if (previousPinchDistance === 0) {
  14241. previousPinchDistance = pinchSquaredDistance;
  14242. return;
  14243. }
  14244. if (pinchSquaredDistance !== previousPinchDistance) {
  14245. _this.camera
  14246. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  14247. (_this.pinchPrecision *
  14248. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  14249. direction);
  14250. previousPinchDistance = pinchSquaredDistance;
  14251. }
  14252. }
  14253. }
  14254. };
  14255. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14256. this._onContextMenu = function (evt) {
  14257. evt.preventDefault();
  14258. };
  14259. if (!this.camera._useCtrlForPanning) {
  14260. element.addEventListener("contextmenu", this._onContextMenu, false);
  14261. }
  14262. this._onLostFocus = function () {
  14263. //this._keys = [];
  14264. pointA = pointB = undefined;
  14265. previousPinchDistance = 0;
  14266. cacheSoloPointer = null;
  14267. };
  14268. this._onMouseMove = function (evt) {
  14269. if (!engine.isPointerLock) {
  14270. return;
  14271. }
  14272. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  14273. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  14274. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14275. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14276. if (!noPreventDefault) {
  14277. evt.preventDefault();
  14278. }
  14279. };
  14280. this._onGestureStart = function (e) {
  14281. if (window.MSGesture === undefined) {
  14282. return;
  14283. }
  14284. if (!_this._MSGestureHandler) {
  14285. _this._MSGestureHandler = new MSGesture();
  14286. _this._MSGestureHandler.target = element;
  14287. }
  14288. _this._MSGestureHandler.addPointer(e.pointerId);
  14289. };
  14290. this._onGesture = function (e) {
  14291. _this.camera.radius *= e.scale;
  14292. if (e.preventDefault) {
  14293. if (!noPreventDefault) {
  14294. e.stopPropagation();
  14295. e.preventDefault();
  14296. }
  14297. }
  14298. };
  14299. element.addEventListener("mousemove", this._onMouseMove, false);
  14300. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  14301. element.addEventListener("MSGestureChange", this._onGesture, false);
  14302. element.addEventListener("keydown", this._onKeyDown, false);
  14303. element.addEventListener("keyup", this._onKeyUp, false);
  14304. BABYLON.Tools.RegisterTopRootEvents([
  14305. { name: "blur", handler: this._onLostFocus }
  14306. ]);
  14307. };
  14308. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  14309. if (element && this._observer) {
  14310. this.camera.getScene().onPointerObservable.remove(this._observer);
  14311. this._observer = null;
  14312. element.removeEventListener("contextmenu", this._onContextMenu);
  14313. element.removeEventListener("mousemove", this._onMouseMove);
  14314. element.removeEventListener("MSPointerDown", this._onGestureStart);
  14315. element.removeEventListener("MSGestureChange", this._onGesture);
  14316. element.removeEventListener("keydown", this._onKeyDown);
  14317. element.removeEventListener("keyup", this._onKeyUp);
  14318. this._isPanClick = false;
  14319. this.pinchInwards = true;
  14320. this._onKeyDown = null;
  14321. this._onKeyUp = null;
  14322. this._onMouseMove = null;
  14323. this._onGestureStart = null;
  14324. this._onGesture = null;
  14325. this._MSGestureHandler = null;
  14326. this._onLostFocus = null;
  14327. this._onContextMenu = null;
  14328. }
  14329. BABYLON.Tools.UnregisterTopRootEvents([
  14330. { name: "blur", handler: this._onLostFocus }
  14331. ]);
  14332. };
  14333. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  14334. return "ArcRotateCameraPointersInput";
  14335. };
  14336. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  14337. return "pointers";
  14338. };
  14339. __decorate([
  14340. BABYLON.serialize()
  14341. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  14342. __decorate([
  14343. BABYLON.serialize()
  14344. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  14345. __decorate([
  14346. BABYLON.serialize()
  14347. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  14348. __decorate([
  14349. BABYLON.serialize()
  14350. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  14351. __decorate([
  14352. BABYLON.serialize()
  14353. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  14354. return ArcRotateCameraPointersInput;
  14355. }());
  14356. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  14357. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  14358. })(BABYLON || (BABYLON = {}));
  14359. var BABYLON;
  14360. (function (BABYLON) {
  14361. var ArcRotateCameraGamepadInput = (function () {
  14362. function ArcRotateCameraGamepadInput() {
  14363. this.gamepadRotationSensibility = 80;
  14364. this.gamepadMoveSensibility = 40;
  14365. }
  14366. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14367. var _this = this;
  14368. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14369. };
  14370. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  14371. if (this._gamepads) {
  14372. this._gamepads.dispose();
  14373. }
  14374. this.gamepad = null;
  14375. };
  14376. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  14377. if (this.gamepad) {
  14378. var camera = this.camera;
  14379. var RSValues = this.gamepad.rightStick;
  14380. if (RSValues.x != 0) {
  14381. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  14382. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  14383. camera.inertialAlphaOffset += normalizedRX;
  14384. }
  14385. }
  14386. if (RSValues.y != 0) {
  14387. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  14388. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  14389. camera.inertialBetaOffset += normalizedRY;
  14390. }
  14391. }
  14392. var LSValues = this.gamepad.leftStick;
  14393. if (LSValues.y != 0) {
  14394. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14395. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  14396. this.camera.inertialRadiusOffset -= normalizedLY;
  14397. }
  14398. }
  14399. }
  14400. };
  14401. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14402. // Only the first gamepad can control the camera
  14403. if (gamepad.index === 0) {
  14404. this.gamepad = gamepad;
  14405. }
  14406. };
  14407. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  14408. return "ArcRotateCameraGamepadInput";
  14409. };
  14410. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  14411. return "gamepad";
  14412. };
  14413. __decorate([
  14414. BABYLON.serialize()
  14415. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  14416. __decorate([
  14417. BABYLON.serialize()
  14418. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14419. return ArcRotateCameraGamepadInput;
  14420. }());
  14421. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  14422. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  14423. })(BABYLON || (BABYLON = {}));
  14424. var BABYLON;
  14425. (function (BABYLON) {
  14426. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  14427. function ArcRotateCameraVRDeviceOrientationInput() {
  14428. this.alphaCorrection = 1;
  14429. this.betaCorrection = 1;
  14430. this.gammaCorrection = 1;
  14431. this._alpha = 0;
  14432. this._beta = 0;
  14433. this._gamma = 0;
  14434. this._dirty = false;
  14435. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  14436. }
  14437. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14438. this.camera.attachControl(element, noPreventDefault);
  14439. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  14440. };
  14441. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  14442. var camera = this.camera;
  14443. this._alpha = +evt.alpha | 0;
  14444. this._beta = +evt.beta | 0;
  14445. this._gamma = +evt.gamma | 0;
  14446. this._dirty = true;
  14447. };
  14448. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  14449. if (this._dirty) {
  14450. this._dirty = false;
  14451. if (this._gamma < 0) {
  14452. this._gamma = 180 + this._gamma;
  14453. }
  14454. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  14455. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  14456. }
  14457. };
  14458. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  14459. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  14460. };
  14461. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  14462. return "ArcRotateCameraVRDeviceOrientationInput";
  14463. };
  14464. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  14465. return "VRDeviceOrientation";
  14466. };
  14467. return ArcRotateCameraVRDeviceOrientationInput;
  14468. }());
  14469. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  14470. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  14471. })(BABYLON || (BABYLON = {}));
  14472. var BABYLON;
  14473. (function (BABYLON) {
  14474. var TargetCamera = (function (_super) {
  14475. __extends(TargetCamera, _super);
  14476. function TargetCamera(name, position, scene) {
  14477. _super.call(this, name, position, scene);
  14478. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14479. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14480. this.rotation = new BABYLON.Vector3(0, 0, 0);
  14481. this.speed = 2.0;
  14482. this.noRotationConstraint = false;
  14483. this.lockedTarget = null;
  14484. this._currentTarget = BABYLON.Vector3.Zero();
  14485. this._viewMatrix = BABYLON.Matrix.Zero();
  14486. this._camMatrix = BABYLON.Matrix.Zero();
  14487. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  14488. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  14489. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  14490. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  14491. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  14492. this._lookAtTemp = BABYLON.Matrix.Zero();
  14493. this._tempMatrix = BABYLON.Matrix.Zero();
  14494. }
  14495. TargetCamera.prototype.getFrontPosition = function (distance) {
  14496. var direction = this.getTarget().subtract(this.position);
  14497. direction.normalize();
  14498. direction.scaleInPlace(distance);
  14499. return this.globalPosition.add(direction);
  14500. };
  14501. TargetCamera.prototype._getLockedTargetPosition = function () {
  14502. if (!this.lockedTarget) {
  14503. return null;
  14504. }
  14505. return this.lockedTarget.position || this.lockedTarget;
  14506. };
  14507. // Cache
  14508. TargetCamera.prototype._initCache = function () {
  14509. _super.prototype._initCache.call(this);
  14510. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14511. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14512. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14513. };
  14514. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  14515. if (!ignoreParentClass) {
  14516. _super.prototype._updateCache.call(this);
  14517. }
  14518. var lockedTargetPosition = this._getLockedTargetPosition();
  14519. if (!lockedTargetPosition) {
  14520. this._cache.lockedTarget = null;
  14521. }
  14522. else {
  14523. if (!this._cache.lockedTarget) {
  14524. this._cache.lockedTarget = lockedTargetPosition.clone();
  14525. }
  14526. else {
  14527. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  14528. }
  14529. }
  14530. this._cache.rotation.copyFrom(this.rotation);
  14531. if (this.rotationQuaternion)
  14532. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14533. };
  14534. // Synchronized
  14535. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  14536. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  14537. return false;
  14538. }
  14539. var lockedTargetPosition = this._getLockedTargetPosition();
  14540. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  14541. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  14542. };
  14543. // Methods
  14544. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  14545. var engine = this.getEngine();
  14546. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  14547. };
  14548. // Target
  14549. TargetCamera.prototype.setTarget = function (target) {
  14550. this.upVector.normalize();
  14551. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  14552. this._camMatrix.invert();
  14553. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  14554. var vDir = target.subtract(this.position);
  14555. if (vDir.x >= 0.0) {
  14556. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  14557. }
  14558. else {
  14559. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  14560. }
  14561. this.rotation.z = 0;
  14562. if (isNaN(this.rotation.x)) {
  14563. this.rotation.x = 0;
  14564. }
  14565. if (isNaN(this.rotation.y)) {
  14566. this.rotation.y = 0;
  14567. }
  14568. if (isNaN(this.rotation.z)) {
  14569. this.rotation.z = 0;
  14570. }
  14571. if (this.rotationQuaternion) {
  14572. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  14573. }
  14574. };
  14575. TargetCamera.prototype.getTarget = function () {
  14576. return this._currentTarget;
  14577. };
  14578. TargetCamera.prototype._decideIfNeedsToMove = function () {
  14579. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14580. };
  14581. TargetCamera.prototype._updatePosition = function () {
  14582. this.position.addInPlace(this.cameraDirection);
  14583. };
  14584. TargetCamera.prototype._checkInputs = function () {
  14585. var needToMove = this._decideIfNeedsToMove();
  14586. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  14587. // Move
  14588. if (needToMove) {
  14589. this._updatePosition();
  14590. }
  14591. // Rotate
  14592. if (needToRotate) {
  14593. this.rotation.x += this.cameraRotation.x;
  14594. this.rotation.y += this.cameraRotation.y;
  14595. if (!this.noRotationConstraint) {
  14596. var limit = (Math.PI / 2) * 0.95;
  14597. if (this.rotation.x > limit)
  14598. this.rotation.x = limit;
  14599. if (this.rotation.x < -limit)
  14600. this.rotation.x = -limit;
  14601. }
  14602. }
  14603. // Inertia
  14604. if (needToMove) {
  14605. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  14606. this.cameraDirection.x = 0;
  14607. }
  14608. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  14609. this.cameraDirection.y = 0;
  14610. }
  14611. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  14612. this.cameraDirection.z = 0;
  14613. }
  14614. this.cameraDirection.scaleInPlace(this.inertia);
  14615. }
  14616. if (needToRotate) {
  14617. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  14618. this.cameraRotation.x = 0;
  14619. }
  14620. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  14621. this.cameraRotation.y = 0;
  14622. }
  14623. this.cameraRotation.scaleInPlace(this.inertia);
  14624. }
  14625. _super.prototype._checkInputs.call(this);
  14626. };
  14627. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  14628. if (this.rotationQuaternion) {
  14629. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  14630. //update the up vector!
  14631. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  14632. }
  14633. else {
  14634. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  14635. }
  14636. };
  14637. TargetCamera.prototype._getViewMatrix = function () {
  14638. if (!this.lockedTarget) {
  14639. // Compute
  14640. this._updateCameraRotationMatrix();
  14641. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  14642. // Computing target and final matrix
  14643. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  14644. }
  14645. else {
  14646. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  14647. }
  14648. if (this.getScene().useRightHandedSystem) {
  14649. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14650. }
  14651. else {
  14652. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14653. }
  14654. return this._viewMatrix;
  14655. };
  14656. /**
  14657. * @override
  14658. * Override Camera.createRigCamera
  14659. */
  14660. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14661. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  14662. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  14663. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  14664. if (!this.rotationQuaternion) {
  14665. this.rotationQuaternion = new BABYLON.Quaternion();
  14666. }
  14667. rigCamera._cameraRigParams = {};
  14668. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  14669. }
  14670. return rigCamera;
  14671. }
  14672. return null;
  14673. };
  14674. /**
  14675. * @override
  14676. * Override Camera._updateRigCameras
  14677. */
  14678. TargetCamera.prototype._updateRigCameras = function () {
  14679. var camLeft = this._rigCameras[0];
  14680. var camRight = this._rigCameras[1];
  14681. switch (this.cameraRigMode) {
  14682. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14683. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14684. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14685. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14686. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  14687. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  14688. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  14689. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  14690. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  14691. camLeft.setTarget(this.getTarget());
  14692. camRight.setTarget(this.getTarget());
  14693. break;
  14694. case BABYLON.Camera.RIG_MODE_VR:
  14695. case BABYLON.Camera.RIG_MODE_WEBVR:
  14696. if (camLeft.rotationQuaternion) {
  14697. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14698. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14699. }
  14700. else {
  14701. camLeft.rotation.copyFrom(this.rotation);
  14702. camRight.rotation.copyFrom(this.rotation);
  14703. }
  14704. camLeft.position.copyFrom(this.position);
  14705. camRight.position.copyFrom(this.position);
  14706. break;
  14707. }
  14708. _super.prototype._updateRigCameras.call(this);
  14709. };
  14710. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  14711. if (!this._rigCamTransformMatrix) {
  14712. this._rigCamTransformMatrix = new BABYLON.Matrix();
  14713. }
  14714. var target = this.getTarget();
  14715. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  14716. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  14717. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  14718. };
  14719. TargetCamera.prototype.getTypeName = function () {
  14720. return "TargetCamera";
  14721. };
  14722. __decorate([
  14723. BABYLON.serializeAsVector3()
  14724. ], TargetCamera.prototype, "rotation", void 0);
  14725. __decorate([
  14726. BABYLON.serialize()
  14727. ], TargetCamera.prototype, "speed", void 0);
  14728. __decorate([
  14729. BABYLON.serializeAsMeshReference("lockedTargetId")
  14730. ], TargetCamera.prototype, "lockedTarget", void 0);
  14731. return TargetCamera;
  14732. }(BABYLON.Camera));
  14733. BABYLON.TargetCamera = TargetCamera;
  14734. })(BABYLON || (BABYLON = {}));
  14735. var BABYLON;
  14736. (function (BABYLON) {
  14737. var FreeCamera = (function (_super) {
  14738. __extends(FreeCamera, _super);
  14739. function FreeCamera(name, position, scene) {
  14740. var _this = this;
  14741. _super.call(this, name, position, scene);
  14742. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14743. this.checkCollisions = false;
  14744. this.applyGravity = false;
  14745. this._collider = new BABYLON.Collider();
  14746. this._needMoveForGravity = false;
  14747. this._oldPosition = BABYLON.Vector3.Zero();
  14748. this._diffPosition = BABYLON.Vector3.Zero();
  14749. this._newPosition = BABYLON.Vector3.Zero();
  14750. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14751. if (collidedMesh === void 0) { collidedMesh = null; }
  14752. //TODO move this to the collision coordinator!
  14753. if (_this.getScene().workerCollisions)
  14754. newPosition.multiplyInPlace(_this._collider.radius);
  14755. var updatePosition = function (newPos) {
  14756. _this._newPosition.copyFrom(newPos);
  14757. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  14758. var oldPosition = _this.position.clone();
  14759. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  14760. _this.position.addInPlace(_this._diffPosition);
  14761. if (_this.onCollide && collidedMesh) {
  14762. _this.onCollide(collidedMesh);
  14763. }
  14764. }
  14765. };
  14766. updatePosition(newPosition);
  14767. };
  14768. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  14769. this.inputs.addKeyboard().addMouse();
  14770. }
  14771. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  14772. //-- begin properties for backward compatibility for inputs
  14773. get: function () {
  14774. var mouse = this.inputs.attached["mouse"];
  14775. if (mouse)
  14776. return mouse.angularSensibility;
  14777. },
  14778. set: function (value) {
  14779. var mouse = this.inputs.attached["mouse"];
  14780. if (mouse)
  14781. mouse.angularSensibility = value;
  14782. },
  14783. enumerable: true,
  14784. configurable: true
  14785. });
  14786. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  14787. get: function () {
  14788. var keyboard = this.inputs.attached["keyboard"];
  14789. if (keyboard)
  14790. return keyboard.keysUp;
  14791. },
  14792. set: function (value) {
  14793. var keyboard = this.inputs.attached["keyboard"];
  14794. if (keyboard)
  14795. keyboard.keysUp = value;
  14796. },
  14797. enumerable: true,
  14798. configurable: true
  14799. });
  14800. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  14801. get: function () {
  14802. var keyboard = this.inputs.attached["keyboard"];
  14803. if (keyboard)
  14804. return keyboard.keysDown;
  14805. },
  14806. set: function (value) {
  14807. var keyboard = this.inputs.attached["keyboard"];
  14808. if (keyboard)
  14809. keyboard.keysDown = value;
  14810. },
  14811. enumerable: true,
  14812. configurable: true
  14813. });
  14814. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  14815. get: function () {
  14816. var keyboard = this.inputs.attached["keyboard"];
  14817. if (keyboard)
  14818. return keyboard.keysLeft;
  14819. },
  14820. set: function (value) {
  14821. var keyboard = this.inputs.attached["keyboard"];
  14822. if (keyboard)
  14823. keyboard.keysLeft = value;
  14824. },
  14825. enumerable: true,
  14826. configurable: true
  14827. });
  14828. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  14829. get: function () {
  14830. var keyboard = this.inputs.attached["keyboard"];
  14831. if (keyboard)
  14832. return keyboard.keysRight;
  14833. },
  14834. set: function (value) {
  14835. var keyboard = this.inputs.attached["keyboard"];
  14836. if (keyboard)
  14837. keyboard.keysRight = value;
  14838. },
  14839. enumerable: true,
  14840. configurable: true
  14841. });
  14842. // Controls
  14843. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  14844. this.inputs.attachElement(element, noPreventDefault);
  14845. };
  14846. FreeCamera.prototype.detachControl = function (element) {
  14847. this.inputs.detachElement(element);
  14848. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14849. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14850. };
  14851. FreeCamera.prototype._collideWithWorld = function (velocity) {
  14852. var globalPosition;
  14853. if (this.parent) {
  14854. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  14855. }
  14856. else {
  14857. globalPosition = this.position;
  14858. }
  14859. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  14860. this._collider.radius = this.ellipsoid;
  14861. //no need for clone, as long as gravity is not on.
  14862. var actualVelocity = velocity;
  14863. //add gravity to the velocity to prevent the dual-collision checking
  14864. if (this.applyGravity) {
  14865. //this prevents mending with cameraDirection, a global variable of the free camera class.
  14866. actualVelocity = velocity.add(this.getScene().gravity);
  14867. }
  14868. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14869. };
  14870. FreeCamera.prototype._checkInputs = function () {
  14871. if (!this._localDirection) {
  14872. this._localDirection = BABYLON.Vector3.Zero();
  14873. this._transformedDirection = BABYLON.Vector3.Zero();
  14874. }
  14875. this.inputs.checkInputs();
  14876. _super.prototype._checkInputs.call(this);
  14877. };
  14878. FreeCamera.prototype._decideIfNeedsToMove = function () {
  14879. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14880. };
  14881. FreeCamera.prototype._updatePosition = function () {
  14882. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  14883. this._collideWithWorld(this.cameraDirection);
  14884. }
  14885. else {
  14886. this.position.addInPlace(this.cameraDirection);
  14887. }
  14888. };
  14889. FreeCamera.prototype.dispose = function () {
  14890. this.inputs.clear();
  14891. _super.prototype.dispose.call(this);
  14892. };
  14893. FreeCamera.prototype.getTypeName = function () {
  14894. return "FreeCamera";
  14895. };
  14896. __decorate([
  14897. BABYLON.serializeAsVector3()
  14898. ], FreeCamera.prototype, "ellipsoid", void 0);
  14899. __decorate([
  14900. BABYLON.serialize()
  14901. ], FreeCamera.prototype, "checkCollisions", void 0);
  14902. __decorate([
  14903. BABYLON.serialize()
  14904. ], FreeCamera.prototype, "applyGravity", void 0);
  14905. return FreeCamera;
  14906. }(BABYLON.TargetCamera));
  14907. BABYLON.FreeCamera = FreeCamera;
  14908. })(BABYLON || (BABYLON = {}));
  14909. var BABYLON;
  14910. (function (BABYLON) {
  14911. var FreeCameraInputsManager = (function (_super) {
  14912. __extends(FreeCameraInputsManager, _super);
  14913. function FreeCameraInputsManager(camera) {
  14914. _super.call(this, camera);
  14915. }
  14916. FreeCameraInputsManager.prototype.addKeyboard = function () {
  14917. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  14918. return this;
  14919. };
  14920. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  14921. if (touchEnabled === void 0) { touchEnabled = true; }
  14922. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  14923. return this;
  14924. };
  14925. FreeCameraInputsManager.prototype.addGamepad = function () {
  14926. this.add(new BABYLON.FreeCameraGamepadInput());
  14927. return this;
  14928. };
  14929. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  14930. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  14931. return this;
  14932. };
  14933. FreeCameraInputsManager.prototype.addTouch = function () {
  14934. this.add(new BABYLON.FreeCameraTouchInput());
  14935. return this;
  14936. };
  14937. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  14938. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  14939. return this;
  14940. };
  14941. return FreeCameraInputsManager;
  14942. }(BABYLON.CameraInputsManager));
  14943. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  14944. })(BABYLON || (BABYLON = {}));
  14945. var BABYLON;
  14946. (function (BABYLON) {
  14947. var FollowCamera = (function (_super) {
  14948. __extends(FollowCamera, _super);
  14949. function FollowCamera(name, position, scene, target) {
  14950. _super.call(this, name, position, scene);
  14951. this.radius = 12;
  14952. this.rotationOffset = 0;
  14953. this.heightOffset = 4;
  14954. this.cameraAcceleration = 0.05;
  14955. this.maxCameraSpeed = 20;
  14956. this.target = target;
  14957. }
  14958. FollowCamera.prototype.getRadians = function (degrees) {
  14959. return degrees * Math.PI / 180;
  14960. };
  14961. FollowCamera.prototype.follow = function (cameraTarget) {
  14962. if (!cameraTarget)
  14963. return;
  14964. var yRotation;
  14965. if (cameraTarget.rotationQuaternion) {
  14966. var rotMatrix = new BABYLON.Matrix();
  14967. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  14968. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  14969. }
  14970. else {
  14971. yRotation = cameraTarget.rotation.y;
  14972. }
  14973. var radians = this.getRadians(this.rotationOffset) + yRotation;
  14974. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  14975. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  14976. var dx = targetX - this.position.x;
  14977. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  14978. var dz = (targetZ) - this.position.z;
  14979. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  14980. var vy = dy * this.cameraAcceleration;
  14981. var vz = dz * this.cameraAcceleration * 2;
  14982. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  14983. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14984. }
  14985. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  14986. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14987. }
  14988. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  14989. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14990. }
  14991. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  14992. this.setTarget(cameraTarget.position);
  14993. };
  14994. FollowCamera.prototype._checkInputs = function () {
  14995. _super.prototype._checkInputs.call(this);
  14996. this.follow(this.target);
  14997. };
  14998. FollowCamera.prototype.getTypeName = function () {
  14999. return "FollowCamera";
  15000. };
  15001. __decorate([
  15002. BABYLON.serialize()
  15003. ], FollowCamera.prototype, "radius", void 0);
  15004. __decorate([
  15005. BABYLON.serialize()
  15006. ], FollowCamera.prototype, "rotationOffset", void 0);
  15007. __decorate([
  15008. BABYLON.serialize()
  15009. ], FollowCamera.prototype, "heightOffset", void 0);
  15010. __decorate([
  15011. BABYLON.serialize()
  15012. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  15013. __decorate([
  15014. BABYLON.serialize()
  15015. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  15016. __decorate([
  15017. BABYLON.serializeAsMeshReference("lockedTargetId")
  15018. ], FollowCamera.prototype, "target", void 0);
  15019. return FollowCamera;
  15020. }(BABYLON.TargetCamera));
  15021. BABYLON.FollowCamera = FollowCamera;
  15022. var ArcFollowCamera = (function (_super) {
  15023. __extends(ArcFollowCamera, _super);
  15024. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  15025. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  15026. this.alpha = alpha;
  15027. this.beta = beta;
  15028. this.radius = radius;
  15029. this.target = target;
  15030. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  15031. this.follow();
  15032. }
  15033. ArcFollowCamera.prototype.follow = function () {
  15034. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  15035. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  15036. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  15037. this.position = this.target.position.add(this._cartesianCoordinates);
  15038. this.setTarget(this.target.position);
  15039. };
  15040. ArcFollowCamera.prototype._checkInputs = function () {
  15041. _super.prototype._checkInputs.call(this);
  15042. this.follow();
  15043. };
  15044. ArcFollowCamera.prototype.getTypeName = function () {
  15045. return "ArcFollowCamera";
  15046. };
  15047. return ArcFollowCamera;
  15048. }(BABYLON.TargetCamera));
  15049. BABYLON.ArcFollowCamera = ArcFollowCamera;
  15050. })(BABYLON || (BABYLON = {}));
  15051. var BABYLON;
  15052. (function (BABYLON) {
  15053. // We're mainly based on the logic defined into the FreeCamera code
  15054. var TouchCamera = (function (_super) {
  15055. __extends(TouchCamera, _super);
  15056. //-- end properties for backward compatibility for inputs
  15057. function TouchCamera(name, position, scene) {
  15058. _super.call(this, name, position, scene);
  15059. this.inputs.addTouch();
  15060. this._setupInputs();
  15061. }
  15062. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  15063. //-- Begin properties for backward compatibility for inputs
  15064. get: function () {
  15065. var touch = this.inputs.attached["touch"];
  15066. if (touch)
  15067. return touch.touchAngularSensibility;
  15068. },
  15069. set: function (value) {
  15070. var touch = this.inputs.attached["touch"];
  15071. if (touch)
  15072. touch.touchAngularSensibility = value;
  15073. },
  15074. enumerable: true,
  15075. configurable: true
  15076. });
  15077. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  15078. get: function () {
  15079. var touch = this.inputs.attached["touch"];
  15080. if (touch)
  15081. return touch.touchMoveSensibility;
  15082. },
  15083. set: function (value) {
  15084. var touch = this.inputs.attached["touch"];
  15085. if (touch)
  15086. touch.touchMoveSensibility = value;
  15087. },
  15088. enumerable: true,
  15089. configurable: true
  15090. });
  15091. TouchCamera.prototype.getTypeName = function () {
  15092. return "TouchCamera";
  15093. };
  15094. TouchCamera.prototype._setupInputs = function () {
  15095. var mouse = this.inputs.attached["mouse"];
  15096. if (mouse) {
  15097. mouse.touchEnabled = false;
  15098. }
  15099. };
  15100. return TouchCamera;
  15101. }(BABYLON.FreeCamera));
  15102. BABYLON.TouchCamera = TouchCamera;
  15103. })(BABYLON || (BABYLON = {}));
  15104. var BABYLON;
  15105. (function (BABYLON) {
  15106. var ArcRotateCamera = (function (_super) {
  15107. __extends(ArcRotateCamera, _super);
  15108. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  15109. var _this = this;
  15110. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  15111. this.inertialAlphaOffset = 0;
  15112. this.inertialBetaOffset = 0;
  15113. this.inertialRadiusOffset = 0;
  15114. this.lowerAlphaLimit = null;
  15115. this.upperAlphaLimit = null;
  15116. this.lowerBetaLimit = 0.01;
  15117. this.upperBetaLimit = Math.PI;
  15118. this.lowerRadiusLimit = null;
  15119. this.upperRadiusLimit = null;
  15120. this.inertialPanningX = 0;
  15121. this.inertialPanningY = 0;
  15122. //-- end properties for backward compatibility for inputs
  15123. this.zoomOnFactor = 1;
  15124. this.targetScreenOffset = BABYLON.Vector2.Zero();
  15125. this.allowUpsideDown = true;
  15126. this._viewMatrix = new BABYLON.Matrix();
  15127. // Panning
  15128. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  15129. this.checkCollisions = false;
  15130. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15131. this._collider = new BABYLON.Collider();
  15132. this._previousPosition = BABYLON.Vector3.Zero();
  15133. this._collisionVelocity = BABYLON.Vector3.Zero();
  15134. this._newPosition = BABYLON.Vector3.Zero();
  15135. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15136. if (collidedMesh === void 0) { collidedMesh = null; }
  15137. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  15138. newPosition.multiplyInPlace(_this._collider.radius);
  15139. }
  15140. if (!collidedMesh) {
  15141. _this._previousPosition.copyFrom(_this.position);
  15142. }
  15143. else {
  15144. _this.setPosition(newPosition);
  15145. if (_this.onCollide) {
  15146. _this.onCollide(collidedMesh);
  15147. }
  15148. }
  15149. // Recompute because of constraints
  15150. var cosa = Math.cos(_this.alpha);
  15151. var sina = Math.sin(_this.alpha);
  15152. var cosb = Math.cos(_this.beta);
  15153. var sinb = Math.sin(_this.beta);
  15154. if (sinb === 0) {
  15155. sinb = 0.0001;
  15156. }
  15157. var target = _this._getTargetPosition();
  15158. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  15159. _this.position.copyFrom(_this._newPosition);
  15160. var up = _this.upVector;
  15161. if (_this.allowUpsideDown && _this.beta < 0) {
  15162. up = up.clone();
  15163. up = up.negate();
  15164. }
  15165. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  15166. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  15167. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  15168. _this._collisionTriggered = false;
  15169. };
  15170. if (!target) {
  15171. this.target = BABYLON.Vector3.Zero();
  15172. }
  15173. else {
  15174. this.target = target;
  15175. }
  15176. this.alpha = alpha;
  15177. this.beta = beta;
  15178. this.radius = radius;
  15179. this.getViewMatrix();
  15180. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  15181. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  15182. }
  15183. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  15184. //-- begin properties for backward compatibility for inputs
  15185. get: function () {
  15186. var pointers = this.inputs.attached["pointers"];
  15187. if (pointers)
  15188. return pointers.angularSensibilityX;
  15189. },
  15190. set: function (value) {
  15191. var pointers = this.inputs.attached["pointers"];
  15192. if (pointers) {
  15193. pointers.angularSensibilityX = value;
  15194. }
  15195. },
  15196. enumerable: true,
  15197. configurable: true
  15198. });
  15199. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  15200. get: function () {
  15201. var pointers = this.inputs.attached["pointers"];
  15202. if (pointers)
  15203. return pointers.angularSensibilityY;
  15204. },
  15205. set: function (value) {
  15206. var pointers = this.inputs.attached["pointers"];
  15207. if (pointers) {
  15208. pointers.angularSensibilityY = value;
  15209. }
  15210. },
  15211. enumerable: true,
  15212. configurable: true
  15213. });
  15214. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  15215. get: function () {
  15216. var pointers = this.inputs.attached["pointers"];
  15217. if (pointers)
  15218. return pointers.pinchPrecision;
  15219. },
  15220. set: function (value) {
  15221. var pointers = this.inputs.attached["pointers"];
  15222. if (pointers) {
  15223. pointers.pinchPrecision = value;
  15224. }
  15225. },
  15226. enumerable: true,
  15227. configurable: true
  15228. });
  15229. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  15230. get: function () {
  15231. var pointers = this.inputs.attached["pointers"];
  15232. if (pointers)
  15233. return pointers.panningSensibility;
  15234. },
  15235. set: function (value) {
  15236. var pointers = this.inputs.attached["pointers"];
  15237. if (pointers) {
  15238. pointers.panningSensibility = value;
  15239. }
  15240. },
  15241. enumerable: true,
  15242. configurable: true
  15243. });
  15244. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  15245. get: function () {
  15246. var keyboard = this.inputs.attached["keyboard"];
  15247. if (keyboard)
  15248. return keyboard.keysUp;
  15249. },
  15250. set: function (value) {
  15251. var keyboard = this.inputs.attached["keyboard"];
  15252. if (keyboard)
  15253. keyboard.keysUp = value;
  15254. },
  15255. enumerable: true,
  15256. configurable: true
  15257. });
  15258. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  15259. get: function () {
  15260. var keyboard = this.inputs.attached["keyboard"];
  15261. if (keyboard)
  15262. return keyboard.keysDown;
  15263. },
  15264. set: function (value) {
  15265. var keyboard = this.inputs.attached["keyboard"];
  15266. if (keyboard)
  15267. keyboard.keysDown = value;
  15268. },
  15269. enumerable: true,
  15270. configurable: true
  15271. });
  15272. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  15273. get: function () {
  15274. var keyboard = this.inputs.attached["keyboard"];
  15275. if (keyboard)
  15276. return keyboard.keysLeft;
  15277. },
  15278. set: function (value) {
  15279. var keyboard = this.inputs.attached["keyboard"];
  15280. if (keyboard)
  15281. keyboard.keysLeft = value;
  15282. },
  15283. enumerable: true,
  15284. configurable: true
  15285. });
  15286. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  15287. get: function () {
  15288. var keyboard = this.inputs.attached["keyboard"];
  15289. if (keyboard)
  15290. return keyboard.keysRight;
  15291. },
  15292. set: function (value) {
  15293. var keyboard = this.inputs.attached["keyboard"];
  15294. if (keyboard)
  15295. keyboard.keysRight = value;
  15296. },
  15297. enumerable: true,
  15298. configurable: true
  15299. });
  15300. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  15301. get: function () {
  15302. var mousewheel = this.inputs.attached["mousewheel"];
  15303. if (mousewheel)
  15304. return mousewheel.wheelPrecision;
  15305. },
  15306. set: function (value) {
  15307. var mousewheel = this.inputs.attached["mousewheel"];
  15308. if (mousewheel)
  15309. mousewheel.wheelPrecision = value;
  15310. },
  15311. enumerable: true,
  15312. configurable: true
  15313. });
  15314. // Cache
  15315. ArcRotateCamera.prototype._initCache = function () {
  15316. _super.prototype._initCache.call(this);
  15317. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15318. this._cache.alpha = undefined;
  15319. this._cache.beta = undefined;
  15320. this._cache.radius = undefined;
  15321. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  15322. };
  15323. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  15324. if (!ignoreParentClass) {
  15325. _super.prototype._updateCache.call(this);
  15326. }
  15327. this._cache.target.copyFrom(this._getTargetPosition());
  15328. this._cache.alpha = this.alpha;
  15329. this._cache.beta = this.beta;
  15330. this._cache.radius = this.radius;
  15331. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  15332. };
  15333. ArcRotateCamera.prototype._getTargetPosition = function () {
  15334. if (this.target.getAbsolutePosition) {
  15335. var pos = this.target.getAbsolutePosition();
  15336. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  15337. }
  15338. return this.target;
  15339. };
  15340. // Synchronized
  15341. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  15342. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  15343. return false;
  15344. return this._cache.target.equals(this.target)
  15345. && this._cache.alpha === this.alpha
  15346. && this._cache.beta === this.beta
  15347. && this._cache.radius === this.radius
  15348. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  15349. };
  15350. // Methods
  15351. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  15352. var _this = this;
  15353. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  15354. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  15355. this._useCtrlForPanning = useCtrlForPanning;
  15356. this._panningMouseButton = panningMouseButton;
  15357. this.inputs.attachElement(element, noPreventDefault);
  15358. this._reset = function () {
  15359. _this.inertialAlphaOffset = 0;
  15360. _this.inertialBetaOffset = 0;
  15361. _this.inertialRadiusOffset = 0;
  15362. };
  15363. };
  15364. ArcRotateCamera.prototype.detachControl = function (element) {
  15365. this.inputs.detachElement(element);
  15366. if (this._reset) {
  15367. this._reset();
  15368. }
  15369. };
  15370. ArcRotateCamera.prototype._checkInputs = function () {
  15371. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  15372. if (this._collisionTriggered) {
  15373. return;
  15374. }
  15375. this.inputs.checkInputs();
  15376. // Inertia
  15377. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  15378. this.beta += this.inertialBetaOffset;
  15379. if (this.getScene().useRightHandedSystem) {
  15380. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15381. }
  15382. else {
  15383. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15384. }
  15385. this.radius -= this.inertialRadiusOffset;
  15386. this.inertialAlphaOffset *= this.inertia;
  15387. this.inertialBetaOffset *= this.inertia;
  15388. this.inertialRadiusOffset *= this.inertia;
  15389. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  15390. this.inertialAlphaOffset = 0;
  15391. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  15392. this.inertialBetaOffset = 0;
  15393. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  15394. this.inertialRadiusOffset = 0;
  15395. }
  15396. // Panning inertia
  15397. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  15398. if (!this._localDirection) {
  15399. this._localDirection = BABYLON.Vector3.Zero();
  15400. this._transformedDirection = BABYLON.Vector3.Zero();
  15401. }
  15402. this.inertialPanningX *= this.inertia;
  15403. this.inertialPanningY *= this.inertia;
  15404. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  15405. this.inertialPanningX = 0;
  15406. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  15407. this.inertialPanningY = 0;
  15408. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  15409. this._localDirection.multiplyInPlace(this.panningAxis);
  15410. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  15411. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  15412. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  15413. if (!this.panningAxis.y) {
  15414. this._transformedDirection.y = 0;
  15415. }
  15416. if (!this.target.getAbsolutePosition) {
  15417. this.target.addInPlace(this._transformedDirection);
  15418. }
  15419. }
  15420. // Limits
  15421. this._checkLimits();
  15422. _super.prototype._checkInputs.call(this);
  15423. };
  15424. ArcRotateCamera.prototype._checkLimits = function () {
  15425. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  15426. if (this.allowUpsideDown && this.beta > Math.PI) {
  15427. this.beta = this.beta - (2 * Math.PI);
  15428. }
  15429. }
  15430. else {
  15431. if (this.beta < this.lowerBetaLimit) {
  15432. this.beta = this.lowerBetaLimit;
  15433. }
  15434. }
  15435. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  15436. if (this.allowUpsideDown && this.beta < -Math.PI) {
  15437. this.beta = this.beta + (2 * Math.PI);
  15438. }
  15439. }
  15440. else {
  15441. if (this.beta > this.upperBetaLimit) {
  15442. this.beta = this.upperBetaLimit;
  15443. }
  15444. }
  15445. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  15446. this.alpha = this.lowerAlphaLimit;
  15447. }
  15448. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  15449. this.alpha = this.upperAlphaLimit;
  15450. }
  15451. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  15452. this.radius = this.lowerRadiusLimit;
  15453. }
  15454. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  15455. this.radius = this.upperRadiusLimit;
  15456. }
  15457. };
  15458. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  15459. var radiusv3 = this.position.subtract(this._getTargetPosition());
  15460. this.radius = radiusv3.length();
  15461. // Alpha
  15462. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  15463. if (radiusv3.z < 0) {
  15464. this.alpha = 2 * Math.PI - this.alpha;
  15465. }
  15466. // Beta
  15467. this.beta = Math.acos(radiusv3.y / this.radius);
  15468. this._checkLimits();
  15469. };
  15470. ArcRotateCamera.prototype.setPosition = function (position) {
  15471. if (this.position.equals(position)) {
  15472. return;
  15473. }
  15474. this.position.copyFrom(position);
  15475. this.rebuildAnglesAndRadius();
  15476. };
  15477. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter) {
  15478. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  15479. if (this._getTargetPosition().equals(target)) {
  15480. return;
  15481. }
  15482. if (toBoundingCenter && target.getBoundingInfo) {
  15483. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  15484. }
  15485. else {
  15486. this._targetBoundingCenter = null;
  15487. }
  15488. this.target = target;
  15489. this.rebuildAnglesAndRadius();
  15490. };
  15491. ArcRotateCamera.prototype._getViewMatrix = function () {
  15492. // Compute
  15493. var cosa = Math.cos(this.alpha);
  15494. var sina = Math.sin(this.alpha);
  15495. var cosb = Math.cos(this.beta);
  15496. var sinb = Math.sin(this.beta);
  15497. if (sinb === 0) {
  15498. sinb = 0.0001;
  15499. }
  15500. var target = this._getTargetPosition();
  15501. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  15502. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  15503. this._collider.radius = this.collisionRadius;
  15504. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  15505. this._collisionTriggered = true;
  15506. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15507. }
  15508. else {
  15509. this.position.copyFrom(this._newPosition);
  15510. var up = this.upVector;
  15511. if (this.allowUpsideDown && this.beta < 0) {
  15512. up = up.clone();
  15513. up = up.negate();
  15514. }
  15515. if (this.getScene().useRightHandedSystem) {
  15516. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  15517. }
  15518. else {
  15519. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  15520. }
  15521. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  15522. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  15523. }
  15524. return this._viewMatrix;
  15525. };
  15526. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  15527. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15528. meshes = meshes || this.getScene().meshes;
  15529. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  15530. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  15531. this.radius = distance * this.zoomOnFactor;
  15532. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  15533. };
  15534. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  15535. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15536. var meshesOrMinMaxVector;
  15537. var distance;
  15538. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  15539. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  15540. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  15541. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  15542. }
  15543. else {
  15544. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  15545. distance = meshesOrMinMaxVectorAndDistance.distance;
  15546. }
  15547. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  15548. if (!doNotUpdateMaxZ) {
  15549. this.maxZ = distance * 2;
  15550. }
  15551. };
  15552. /**
  15553. * @override
  15554. * Override Camera.createRigCamera
  15555. */
  15556. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15557. var alphaShift;
  15558. switch (this.cameraRigMode) {
  15559. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15560. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15561. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15562. case BABYLON.Camera.RIG_MODE_VR:
  15563. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  15564. break;
  15565. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15566. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  15567. break;
  15568. }
  15569. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  15570. rigCam._cameraRigParams = {};
  15571. return rigCam;
  15572. };
  15573. /**
  15574. * @override
  15575. * Override Camera._updateRigCameras
  15576. */
  15577. ArcRotateCamera.prototype._updateRigCameras = function () {
  15578. var camLeft = this._rigCameras[0];
  15579. var camRight = this._rigCameras[1];
  15580. camLeft.beta = camRight.beta = this.beta;
  15581. camLeft.radius = camRight.radius = this.radius;
  15582. switch (this.cameraRigMode) {
  15583. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15584. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15585. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15586. case BABYLON.Camera.RIG_MODE_VR:
  15587. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15588. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15589. break;
  15590. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15591. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15592. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15593. break;
  15594. }
  15595. _super.prototype._updateRigCameras.call(this);
  15596. };
  15597. ArcRotateCamera.prototype.dispose = function () {
  15598. this.inputs.clear();
  15599. _super.prototype.dispose.call(this);
  15600. };
  15601. ArcRotateCamera.prototype.getTypeName = function () {
  15602. return "ArcRotateCamera";
  15603. };
  15604. __decorate([
  15605. BABYLON.serialize()
  15606. ], ArcRotateCamera.prototype, "alpha", void 0);
  15607. __decorate([
  15608. BABYLON.serialize()
  15609. ], ArcRotateCamera.prototype, "beta", void 0);
  15610. __decorate([
  15611. BABYLON.serialize()
  15612. ], ArcRotateCamera.prototype, "radius", void 0);
  15613. __decorate([
  15614. BABYLON.serializeAsVector3()
  15615. ], ArcRotateCamera.prototype, "target", void 0);
  15616. __decorate([
  15617. BABYLON.serialize()
  15618. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  15619. __decorate([
  15620. BABYLON.serialize()
  15621. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  15622. __decorate([
  15623. BABYLON.serialize()
  15624. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  15625. __decorate([
  15626. BABYLON.serialize()
  15627. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  15628. __decorate([
  15629. BABYLON.serialize()
  15630. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  15631. __decorate([
  15632. BABYLON.serialize()
  15633. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  15634. __decorate([
  15635. BABYLON.serialize()
  15636. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  15637. __decorate([
  15638. BABYLON.serialize()
  15639. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  15640. __decorate([
  15641. BABYLON.serialize()
  15642. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  15643. __decorate([
  15644. BABYLON.serialize()
  15645. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  15646. __decorate([
  15647. BABYLON.serialize()
  15648. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  15649. __decorate([
  15650. BABYLON.serialize()
  15651. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  15652. __decorate([
  15653. BABYLON.serialize()
  15654. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  15655. return ArcRotateCamera;
  15656. }(BABYLON.TargetCamera));
  15657. BABYLON.ArcRotateCamera = ArcRotateCamera;
  15658. })(BABYLON || (BABYLON = {}));
  15659. var BABYLON;
  15660. (function (BABYLON) {
  15661. var ArcRotateCameraInputsManager = (function (_super) {
  15662. __extends(ArcRotateCameraInputsManager, _super);
  15663. function ArcRotateCameraInputsManager(camera) {
  15664. _super.call(this, camera);
  15665. }
  15666. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  15667. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  15668. return this;
  15669. };
  15670. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  15671. this.add(new BABYLON.ArcRotateCameraPointersInput());
  15672. return this;
  15673. };
  15674. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  15675. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  15676. return this;
  15677. };
  15678. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  15679. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  15680. return this;
  15681. };
  15682. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  15683. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  15684. return this;
  15685. };
  15686. return ArcRotateCameraInputsManager;
  15687. }(BABYLON.CameraInputsManager));
  15688. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  15689. })(BABYLON || (BABYLON = {}));
  15690. var BABYLON;
  15691. (function (BABYLON) {
  15692. var RenderingManager = (function () {
  15693. function RenderingManager(scene) {
  15694. this._renderingGroups = new Array();
  15695. this._autoClearDepthStencil = {};
  15696. this._customOpaqueSortCompareFn = {};
  15697. this._customAlphaTestSortCompareFn = {};
  15698. this._customTransparentSortCompareFn = {};
  15699. this._renderinGroupInfo = null;
  15700. this._scene = scene;
  15701. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15702. this._autoClearDepthStencil[i] = true;
  15703. }
  15704. }
  15705. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  15706. if (this._scene._activeParticleSystems.length === 0) {
  15707. return;
  15708. }
  15709. // Particles
  15710. var activeCamera = this._scene.activeCamera;
  15711. this._scene._particlesDuration.beginMonitoring();
  15712. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15713. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15714. if (particleSystem.renderingGroupId !== index) {
  15715. continue;
  15716. }
  15717. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15718. continue;
  15719. }
  15720. this._clearDepthStencilBuffer();
  15721. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15722. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15723. }
  15724. }
  15725. this._scene._particlesDuration.endMonitoring(false);
  15726. };
  15727. RenderingManager.prototype._renderSprites = function (index) {
  15728. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  15729. return;
  15730. }
  15731. // Sprites
  15732. var activeCamera = this._scene.activeCamera;
  15733. this._scene._spritesDuration.beginMonitoring();
  15734. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  15735. var spriteManager = this._scene.spriteManagers[id];
  15736. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15737. this._clearDepthStencilBuffer();
  15738. spriteManager.render();
  15739. }
  15740. }
  15741. this._scene._spritesDuration.endMonitoring(false);
  15742. };
  15743. RenderingManager.prototype._clearDepthStencilBuffer = function () {
  15744. if (this._depthStencilBufferAlreadyCleaned) {
  15745. return;
  15746. }
  15747. this._scene.getEngine().clear(0, false, true, true);
  15748. this._depthStencilBufferAlreadyCleaned = true;
  15749. };
  15750. RenderingManager.prototype._renderSpritesAndParticles = function () {
  15751. if (this._currentRenderSprites) {
  15752. this._renderSprites(this._currentIndex);
  15753. }
  15754. if (this._currentRenderParticles) {
  15755. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  15756. }
  15757. };
  15758. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15759. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15760. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15761. var info = null;
  15762. if (observable) {
  15763. if (!this._renderinGroupInfo) {
  15764. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15765. }
  15766. info = this._renderinGroupInfo;
  15767. info.scene = this._scene;
  15768. info.camera = this._scene.activeCamera;
  15769. }
  15770. this._currentActiveMeshes = activeMeshes;
  15771. this._currentRenderParticles = renderParticles;
  15772. this._currentRenderSprites = renderSprites;
  15773. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15774. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15775. var renderingGroup = this._renderingGroups[index];
  15776. var needToStepBack = false;
  15777. this._currentIndex = index;
  15778. if (renderingGroup) {
  15779. var renderingGroupMask = 0;
  15780. // Fire PRECLEAR stage
  15781. if (observable) {
  15782. renderingGroupMask = Math.pow(2, index);
  15783. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15784. info.renderingGroupId = index;
  15785. observable.notifyObservers(info, renderingGroupMask);
  15786. }
  15787. // Clear depth/stencil if needed
  15788. if (this._autoClearDepthStencil[index]) {
  15789. this._clearDepthStencilBuffer();
  15790. }
  15791. // Fire PREOPAQUE stage
  15792. if (observable) {
  15793. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15794. observable.notifyObservers(info, renderingGroupMask);
  15795. }
  15796. if (!renderingGroup.onBeforeTransparentRendering) {
  15797. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  15798. }
  15799. // Fire PRETRANSPARENT stage
  15800. if (observable) {
  15801. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15802. observable.notifyObservers(info, renderingGroupMask);
  15803. }
  15804. if (!renderingGroup.render(customRenderFunction)) {
  15805. this._renderingGroups.splice(index, 1);
  15806. needToStepBack = true;
  15807. this._renderSpritesAndParticles();
  15808. }
  15809. // Fire POSTTRANSPARENT stage
  15810. if (observable) {
  15811. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15812. observable.notifyObservers(info, renderingGroupMask);
  15813. }
  15814. }
  15815. else {
  15816. this._renderSpritesAndParticles();
  15817. if (observable) {
  15818. var renderingGroupMask = Math.pow(2, index);
  15819. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15820. info.renderingGroupId = index;
  15821. observable.notifyObservers(info, renderingGroupMask);
  15822. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15823. observable.notifyObservers(info, renderingGroupMask);
  15824. }
  15825. }
  15826. if (needToStepBack) {
  15827. index--;
  15828. }
  15829. }
  15830. };
  15831. RenderingManager.prototype.reset = function () {
  15832. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15833. var renderingGroup = this._renderingGroups[index];
  15834. if (renderingGroup) {
  15835. renderingGroup.prepare();
  15836. }
  15837. }
  15838. };
  15839. RenderingManager.prototype.dispatch = function (subMesh) {
  15840. var mesh = subMesh.getMesh();
  15841. var renderingGroupId = mesh.renderingGroupId || 0;
  15842. if (!this._renderingGroups[renderingGroupId]) {
  15843. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15844. }
  15845. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15846. };
  15847. /**
  15848. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15849. * This allowed control for front to back rendering or reversly depending of the special needs.
  15850. *
  15851. * @param renderingGroupId The rendering group id corresponding to its index
  15852. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15853. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15854. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15855. */
  15856. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15857. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15858. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15859. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15860. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15861. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15862. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15863. if (this._renderingGroups[renderingGroupId]) {
  15864. var group = this._renderingGroups[renderingGroupId];
  15865. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15866. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15867. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15868. }
  15869. };
  15870. /**
  15871. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15872. *
  15873. * @param renderingGroupId The rendering group id corresponding to its index
  15874. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15875. */
  15876. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  15877. this._autoClearDepthStencil[renderingGroupId] = autoClearDepthStencil;
  15878. };
  15879. /**
  15880. * The max id used for rendering groups (not included)
  15881. */
  15882. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15883. /**
  15884. * The min id used for rendering groups (included)
  15885. */
  15886. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15887. return RenderingManager;
  15888. }());
  15889. BABYLON.RenderingManager = RenderingManager;
  15890. })(BABYLON || (BABYLON = {}));
  15891. var BABYLON;
  15892. (function (BABYLON) {
  15893. var RenderingGroup = (function () {
  15894. /**
  15895. * Creates a new rendering group.
  15896. * @param index The rendering group index
  15897. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15898. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15899. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15900. */
  15901. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15902. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15903. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15904. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15905. this.index = index;
  15906. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15907. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15908. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15909. this._scene = scene;
  15910. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15911. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15912. this.transparentSortCompareFn = transparentSortCompareFn;
  15913. }
  15914. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15915. /**
  15916. * Set the opaque sort comparison function.
  15917. * If null the sub meshes will be render in the order they were created
  15918. */
  15919. set: function (value) {
  15920. this._opaqueSortCompareFn = value;
  15921. if (value) {
  15922. this._renderOpaque = this.renderOpaqueSorted;
  15923. }
  15924. else {
  15925. this._renderOpaque = RenderingGroup.renderUnsorted;
  15926. }
  15927. },
  15928. enumerable: true,
  15929. configurable: true
  15930. });
  15931. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15932. /**
  15933. * Set the alpha test sort comparison function.
  15934. * If null the sub meshes will be render in the order they were created
  15935. */
  15936. set: function (value) {
  15937. this._alphaTestSortCompareFn = value;
  15938. if (value) {
  15939. this._renderAlphaTest = this.renderAlphaTestSorted;
  15940. }
  15941. else {
  15942. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15943. }
  15944. },
  15945. enumerable: true,
  15946. configurable: true
  15947. });
  15948. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15949. /**
  15950. * Set the transparent sort comparison function.
  15951. * If null the sub meshes will be render in the order they were created
  15952. */
  15953. set: function (value) {
  15954. if (value) {
  15955. this._transparentSortCompareFn = value;
  15956. }
  15957. else {
  15958. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15959. }
  15960. this._renderTransparent = this.renderTransparentSorted;
  15961. },
  15962. enumerable: true,
  15963. configurable: true
  15964. });
  15965. /**
  15966. * Render all the sub meshes contained in the group.
  15967. * @param customRenderFunction Used to override the default render behaviour of the group.
  15968. * @returns true if rendered some submeshes.
  15969. */
  15970. RenderingGroup.prototype.render = function (customRenderFunction) {
  15971. if (customRenderFunction) {
  15972. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15973. return true;
  15974. }
  15975. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  15976. if (this.onBeforeTransparentRendering) {
  15977. this.onBeforeTransparentRendering();
  15978. }
  15979. return false;
  15980. }
  15981. var engine = this._scene.getEngine();
  15982. // Opaque
  15983. this._renderOpaque(this._opaqueSubMeshes);
  15984. // Alpha test
  15985. engine.setAlphaTesting(true);
  15986. this._renderAlphaTest(this._alphaTestSubMeshes);
  15987. engine.setAlphaTesting(false);
  15988. if (this.onBeforeTransparentRendering) {
  15989. this.onBeforeTransparentRendering();
  15990. }
  15991. // Transparent
  15992. this._renderTransparent(this._transparentSubMeshes);
  15993. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15994. return true;
  15995. };
  15996. /**
  15997. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15998. * @param subMeshes The submeshes to render
  15999. */
  16000. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16001. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16002. };
  16003. /**
  16004. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16005. * @param subMeshes The submeshes to render
  16006. */
  16007. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16008. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16009. };
  16010. /**
  16011. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16012. * @param subMeshes The submeshes to render
  16013. */
  16014. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16015. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16016. };
  16017. /**
  16018. * Renders the submeshes in a specified order.
  16019. * @param subMeshes The submeshes to sort before render
  16020. * @param sortCompareFn The comparison function use to sort
  16021. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16022. * @param transparent Specifies to activate blending if true
  16023. */
  16024. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16025. var subIndex = 0;
  16026. var subMesh;
  16027. for (; subIndex < subMeshes.length; subIndex++) {
  16028. subMesh = subMeshes.data[subIndex];
  16029. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16030. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16031. }
  16032. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16033. sortedArray.sort(sortCompareFn);
  16034. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16035. subMesh = sortedArray[subIndex];
  16036. subMesh.render(transparent);
  16037. }
  16038. };
  16039. /**
  16040. * Renders the submeshes in the order they were dispatched (no sort applied).
  16041. * @param subMeshes The submeshes to render
  16042. */
  16043. RenderingGroup.renderUnsorted = function (subMeshes) {
  16044. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16045. var submesh = subMeshes.data[subIndex];
  16046. submesh.render(false);
  16047. }
  16048. };
  16049. /**
  16050. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16051. * are rendered back to front if in the same alpha index.
  16052. *
  16053. * @param a The first submesh
  16054. * @param b The second submesh
  16055. * @returns The result of the comparison
  16056. */
  16057. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16058. // Alpha index first
  16059. if (a._alphaIndex > b._alphaIndex) {
  16060. return 1;
  16061. }
  16062. if (a._alphaIndex < b._alphaIndex) {
  16063. return -1;
  16064. }
  16065. // Then distance to camera
  16066. return RenderingGroup.backToFrontSortCompare(a, b);
  16067. };
  16068. /**
  16069. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16070. * are rendered back to front.
  16071. *
  16072. * @param a The first submesh
  16073. * @param b The second submesh
  16074. * @returns The result of the comparison
  16075. */
  16076. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16077. // Then distance to camera
  16078. if (a._distanceToCamera < b._distanceToCamera) {
  16079. return 1;
  16080. }
  16081. if (a._distanceToCamera > b._distanceToCamera) {
  16082. return -1;
  16083. }
  16084. return 0;
  16085. };
  16086. /**
  16087. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16088. * are rendered front to back (prevent overdraw).
  16089. *
  16090. * @param a The first submesh
  16091. * @param b The second submesh
  16092. * @returns The result of the comparison
  16093. */
  16094. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16095. // Then distance to camera
  16096. if (a._distanceToCamera < b._distanceToCamera) {
  16097. return -1;
  16098. }
  16099. if (a._distanceToCamera > b._distanceToCamera) {
  16100. return 1;
  16101. }
  16102. return 0;
  16103. };
  16104. /**
  16105. * Resets the different lists of submeshes to prepare a new frame.
  16106. */
  16107. RenderingGroup.prototype.prepare = function () {
  16108. this._opaqueSubMeshes.reset();
  16109. this._transparentSubMeshes.reset();
  16110. this._alphaTestSubMeshes.reset();
  16111. };
  16112. /**
  16113. * Inserts the submesh in its correct queue depending on its material.
  16114. * @param subMesh The submesh to dispatch
  16115. */
  16116. RenderingGroup.prototype.dispatch = function (subMesh) {
  16117. var material = subMesh.getMaterial();
  16118. var mesh = subMesh.getMesh();
  16119. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16120. this._transparentSubMeshes.push(subMesh);
  16121. }
  16122. else if (material.needAlphaTesting()) {
  16123. this._alphaTestSubMeshes.push(subMesh);
  16124. }
  16125. else {
  16126. this._opaqueSubMeshes.push(subMesh); // Opaque
  16127. }
  16128. };
  16129. return RenderingGroup;
  16130. }());
  16131. BABYLON.RenderingGroup = RenderingGroup;
  16132. })(BABYLON || (BABYLON = {}));
  16133. var BABYLON;
  16134. (function (BABYLON) {
  16135. var PointerEventTypes = (function () {
  16136. function PointerEventTypes() {
  16137. }
  16138. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  16139. get: function () {
  16140. return PointerEventTypes._POINTERDOWN;
  16141. },
  16142. enumerable: true,
  16143. configurable: true
  16144. });
  16145. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  16146. get: function () {
  16147. return PointerEventTypes._POINTERUP;
  16148. },
  16149. enumerable: true,
  16150. configurable: true
  16151. });
  16152. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  16153. get: function () {
  16154. return PointerEventTypes._POINTERMOVE;
  16155. },
  16156. enumerable: true,
  16157. configurable: true
  16158. });
  16159. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  16160. get: function () {
  16161. return PointerEventTypes._POINTERWHEEL;
  16162. },
  16163. enumerable: true,
  16164. configurable: true
  16165. });
  16166. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  16167. get: function () {
  16168. return PointerEventTypes._POINTERPICK;
  16169. },
  16170. enumerable: true,
  16171. configurable: true
  16172. });
  16173. PointerEventTypes._POINTERDOWN = 0x01;
  16174. PointerEventTypes._POINTERUP = 0x02;
  16175. PointerEventTypes._POINTERMOVE = 0x04;
  16176. PointerEventTypes._POINTERWHEEL = 0x08;
  16177. PointerEventTypes._POINTERPICK = 0x10;
  16178. return PointerEventTypes;
  16179. }());
  16180. BABYLON.PointerEventTypes = PointerEventTypes;
  16181. var PointerInfoBase = (function () {
  16182. function PointerInfoBase(type, event) {
  16183. this.type = type;
  16184. this.event = event;
  16185. }
  16186. return PointerInfoBase;
  16187. }());
  16188. BABYLON.PointerInfoBase = PointerInfoBase;
  16189. /**
  16190. * This class is used to store pointer related info for the onPrePointerObservable event.
  16191. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  16192. */
  16193. var PointerInfoPre = (function (_super) {
  16194. __extends(PointerInfoPre, _super);
  16195. function PointerInfoPre(type, event, localX, localY) {
  16196. _super.call(this, type, event);
  16197. this.skipOnPointerObservable = false;
  16198. this.localPosition = new BABYLON.Vector2(localX, localY);
  16199. }
  16200. return PointerInfoPre;
  16201. }(PointerInfoBase));
  16202. BABYLON.PointerInfoPre = PointerInfoPre;
  16203. /**
  16204. * This type contains all the data related to a pointer event in Babylon.js.
  16205. * 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.
  16206. */
  16207. var PointerInfo = (function (_super) {
  16208. __extends(PointerInfo, _super);
  16209. function PointerInfo(type, event, pickInfo) {
  16210. _super.call(this, type, event);
  16211. this.pickInfo = pickInfo;
  16212. }
  16213. return PointerInfo;
  16214. }(PointerInfoBase));
  16215. BABYLON.PointerInfo = PointerInfo;
  16216. /**
  16217. * This class is used by the onRenderingGroupObservable
  16218. */
  16219. var RenderingGroupInfo = (function () {
  16220. function RenderingGroupInfo() {
  16221. }
  16222. /**
  16223. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16224. * This stage will be fired no matter what
  16225. */
  16226. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16227. /**
  16228. * Called before opaque object are rendered.
  16229. * This stage will be fired only if there's 3D Opaque content to render
  16230. */
  16231. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16232. /**
  16233. * Called after the opaque objects are rendered and before the transparent ones
  16234. * This stage will be fired only if there's 3D transparent content to render
  16235. */
  16236. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16237. /**
  16238. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16239. * This stage will be fired no matter what
  16240. */
  16241. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16242. return RenderingGroupInfo;
  16243. }());
  16244. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16245. /**
  16246. * Represents a scene to be rendered by the engine.
  16247. * @see http://doc.babylonjs.com/page.php?p=21911
  16248. */
  16249. var Scene = (function () {
  16250. /**
  16251. * @constructor
  16252. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16253. */
  16254. function Scene(engine) {
  16255. // Members
  16256. this.autoClear = true;
  16257. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16258. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16259. this.forceWireframe = false;
  16260. this.forcePointsCloud = false;
  16261. this.forceShowBoundingBoxes = false;
  16262. this.animationsEnabled = true;
  16263. this.constantlyUpdateMeshUnderPointer = false;
  16264. this.useRightHandedSystem = false;
  16265. this.hoverCursor = "pointer";
  16266. // Metadata
  16267. this.metadata = null;
  16268. // Events
  16269. /**
  16270. * An event triggered when the scene is disposed.
  16271. * @type {BABYLON.Observable}
  16272. */
  16273. this.onDisposeObservable = new BABYLON.Observable();
  16274. /**
  16275. * An event triggered before rendering the scene
  16276. * @type {BABYLON.Observable}
  16277. */
  16278. this.onBeforeRenderObservable = new BABYLON.Observable();
  16279. /**
  16280. * An event triggered after rendering the scene
  16281. * @type {BABYLON.Observable}
  16282. */
  16283. this.onAfterRenderObservable = new BABYLON.Observable();
  16284. /**
  16285. * An event triggered when the scene is ready
  16286. * @type {BABYLON.Observable}
  16287. */
  16288. this.onReadyObservable = new BABYLON.Observable();
  16289. /**
  16290. * An event triggered before rendering a camera
  16291. * @type {BABYLON.Observable}
  16292. */
  16293. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16294. /**
  16295. * An event triggered after rendering a camera
  16296. * @type {BABYLON.Observable}
  16297. */
  16298. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16299. /**
  16300. * An event triggered when a camera is created
  16301. * @type {BABYLON.Observable}
  16302. */
  16303. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16304. /**
  16305. * An event triggered when a camera is removed
  16306. * @type {BABYLON.Observable}
  16307. */
  16308. this.onCameraRemovedObservable = new BABYLON.Observable();
  16309. /**
  16310. * An event triggered when a light is created
  16311. * @type {BABYLON.Observable}
  16312. */
  16313. this.onNewLightAddedObservable = new BABYLON.Observable();
  16314. /**
  16315. * An event triggered when a light is removed
  16316. * @type {BABYLON.Observable}
  16317. */
  16318. this.onLightRemovedObservable = new BABYLON.Observable();
  16319. /**
  16320. * An event triggered when a geometry is created
  16321. * @type {BABYLON.Observable}
  16322. */
  16323. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16324. /**
  16325. * An event triggered when a geometry is removed
  16326. * @type {BABYLON.Observable}
  16327. */
  16328. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16329. /**
  16330. * An event triggered when a mesh is created
  16331. * @type {BABYLON.Observable}
  16332. */
  16333. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16334. /**
  16335. * An event triggered when a mesh is removed
  16336. * @type {BABYLON.Observable}
  16337. */
  16338. this.onMeshRemovedObservable = new BABYLON.Observable();
  16339. /**
  16340. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16341. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16342. * 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)
  16343. */
  16344. this.onRenderingGroupObservable = new BABYLON.Observable();
  16345. // Animations
  16346. this.animations = [];
  16347. /**
  16348. * 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).
  16349. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16350. */
  16351. this.onPrePointerObservable = new BABYLON.Observable();
  16352. /**
  16353. * Observable event triggered each time an input event is received from the rendering canvas
  16354. */
  16355. this.onPointerObservable = new BABYLON.Observable();
  16356. 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
  16357. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16358. this._startingPointerTime = 0;
  16359. // Fog
  16360. /**
  16361. * is fog enabled on this scene.
  16362. * @type {boolean}
  16363. */
  16364. this.fogEnabled = true;
  16365. this.fogMode = Scene.FOGMODE_NONE;
  16366. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16367. this.fogDensity = 0.1;
  16368. this.fogStart = 0;
  16369. this.fogEnd = 1000.0;
  16370. // Lights
  16371. /**
  16372. * is shadow enabled on this scene.
  16373. * @type {boolean}
  16374. */
  16375. this.shadowsEnabled = true;
  16376. /**
  16377. * is light enabled on this scene.
  16378. * @type {boolean}
  16379. */
  16380. this.lightsEnabled = true;
  16381. /**
  16382. * All of the lights added to this scene.
  16383. * @see BABYLON.Light
  16384. * @type {BABYLON.Light[]}
  16385. */
  16386. this.lights = new Array();
  16387. // Cameras
  16388. /**
  16389. * All of the cameras added to this scene.
  16390. * @see BABYLON.Camera
  16391. * @type {BABYLON.Camera[]}
  16392. */
  16393. this.cameras = new Array();
  16394. this.activeCameras = new Array();
  16395. // Meshes
  16396. /**
  16397. * All of the (abstract) meshes added to this scene.
  16398. * @see BABYLON.AbstractMesh
  16399. * @type {BABYLON.AbstractMesh[]}
  16400. */
  16401. this.meshes = new Array();
  16402. // Geometries
  16403. this._geometries = new Array();
  16404. this.materials = new Array();
  16405. this.multiMaterials = new Array();
  16406. // Textures
  16407. this.texturesEnabled = true;
  16408. this.textures = new Array();
  16409. // Particles
  16410. this.particlesEnabled = true;
  16411. this.particleSystems = new Array();
  16412. // Sprites
  16413. this.spritesEnabled = true;
  16414. this.spriteManagers = new Array();
  16415. // Layers
  16416. this.layers = new Array();
  16417. this.highlightLayers = new Array();
  16418. // Skeletons
  16419. this.skeletonsEnabled = true;
  16420. this.skeletons = new Array();
  16421. // Lens flares
  16422. this.lensFlaresEnabled = true;
  16423. this.lensFlareSystems = new Array();
  16424. // Collisions
  16425. this.collisionsEnabled = true;
  16426. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16427. // Postprocesses
  16428. this.postProcessesEnabled = true;
  16429. // Customs render targets
  16430. this.renderTargetsEnabled = true;
  16431. this.dumpNextRenderTargets = false;
  16432. this.customRenderTargets = new Array();
  16433. // Imported meshes
  16434. this.importedMeshesFiles = new Array();
  16435. // Probes
  16436. this.probesEnabled = true;
  16437. this.reflectionProbes = new Array();
  16438. this._actionManagers = new Array();
  16439. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16440. // Procedural textures
  16441. this.proceduralTexturesEnabled = true;
  16442. this._proceduralTextures = new Array();
  16443. this.soundTracks = new Array();
  16444. this._audioEnabled = true;
  16445. this._headphone = false;
  16446. // Performance counters
  16447. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16448. this._totalLightsCounter = new BABYLON.PerfCounter();
  16449. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16450. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16451. this._totalVertices = new BABYLON.PerfCounter();
  16452. this._activeIndices = new BABYLON.PerfCounter();
  16453. this._activeParticles = new BABYLON.PerfCounter();
  16454. this._lastFrameDuration = new BABYLON.PerfCounter();
  16455. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16456. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16457. this._particlesDuration = new BABYLON.PerfCounter();
  16458. this._renderDuration = new BABYLON.PerfCounter();
  16459. this._spritesDuration = new BABYLON.PerfCounter();
  16460. this._activeBones = new BABYLON.PerfCounter();
  16461. this._renderId = 0;
  16462. this._executeWhenReadyTimeoutId = -1;
  16463. this._intermediateRendering = false;
  16464. this._toBeDisposed = new BABYLON.SmartArray(256);
  16465. this._pendingData = []; //ANY
  16466. this._activeMeshes = new BABYLON.SmartArray(256);
  16467. this._processedMaterials = new BABYLON.SmartArray(256);
  16468. this._renderTargets = new BABYLON.SmartArray(256);
  16469. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16470. this._activeSkeletons = new BABYLON.SmartArray(32);
  16471. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16472. this._activeAnimatables = new Array();
  16473. this._transformMatrix = BABYLON.Matrix.Zero();
  16474. this._edgesRenderers = new BABYLON.SmartArray(16);
  16475. this._uniqueIdCounter = 0;
  16476. this._engine = engine;
  16477. engine.scenes.push(this);
  16478. this._externalData = new BABYLON.StringDictionary();
  16479. this._uid = null;
  16480. this._renderingManager = new BABYLON.RenderingManager(this);
  16481. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16482. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16483. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16484. if (BABYLON.OutlineRenderer) {
  16485. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16486. }
  16487. this.attachControl();
  16488. if (BABYLON.SoundTrack) {
  16489. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16490. }
  16491. //simplification queue
  16492. if (BABYLON.SimplificationQueue) {
  16493. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16494. }
  16495. //collision coordinator initialization. For now legacy per default.
  16496. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16497. }
  16498. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16499. get: function () {
  16500. return Scene._FOGMODE_NONE;
  16501. },
  16502. enumerable: true,
  16503. configurable: true
  16504. });
  16505. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16506. get: function () {
  16507. return Scene._FOGMODE_EXP;
  16508. },
  16509. enumerable: true,
  16510. configurable: true
  16511. });
  16512. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16513. get: function () {
  16514. return Scene._FOGMODE_EXP2;
  16515. },
  16516. enumerable: true,
  16517. configurable: true
  16518. });
  16519. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16520. get: function () {
  16521. return Scene._FOGMODE_LINEAR;
  16522. },
  16523. enumerable: true,
  16524. configurable: true
  16525. });
  16526. Object.defineProperty(Scene.prototype, "onDispose", {
  16527. set: function (callback) {
  16528. if (this._onDisposeObserver) {
  16529. this.onDisposeObservable.remove(this._onDisposeObserver);
  16530. }
  16531. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16532. },
  16533. enumerable: true,
  16534. configurable: true
  16535. });
  16536. Object.defineProperty(Scene.prototype, "beforeRender", {
  16537. set: function (callback) {
  16538. if (this._onBeforeRenderObserver) {
  16539. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16540. }
  16541. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16542. },
  16543. enumerable: true,
  16544. configurable: true
  16545. });
  16546. Object.defineProperty(Scene.prototype, "afterRender", {
  16547. set: function (callback) {
  16548. if (this._onAfterRenderObserver) {
  16549. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16550. }
  16551. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16552. },
  16553. enumerable: true,
  16554. configurable: true
  16555. });
  16556. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16557. set: function (callback) {
  16558. if (this._onBeforeCameraRenderObserver) {
  16559. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16560. }
  16561. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16562. },
  16563. enumerable: true,
  16564. configurable: true
  16565. });
  16566. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16567. set: function (callback) {
  16568. if (this._onAfterCameraRenderObserver) {
  16569. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16570. }
  16571. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16572. },
  16573. enumerable: true,
  16574. configurable: true
  16575. });
  16576. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16577. get: function () {
  16578. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16579. },
  16580. enumerable: true,
  16581. configurable: true
  16582. });
  16583. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16584. get: function () {
  16585. if (!this._defaultMaterial) {
  16586. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16587. }
  16588. return this._defaultMaterial;
  16589. },
  16590. enumerable: true,
  16591. configurable: true
  16592. });
  16593. Object.defineProperty(Scene.prototype, "debugLayer", {
  16594. // Properties
  16595. get: function () {
  16596. if (!this._debugLayer) {
  16597. this._debugLayer = new BABYLON.DebugLayer(this);
  16598. }
  16599. return this._debugLayer;
  16600. },
  16601. enumerable: true,
  16602. configurable: true
  16603. });
  16604. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16605. get: function () {
  16606. return this._workerCollisions;
  16607. },
  16608. set: function (enabled) {
  16609. enabled = (enabled && !!Worker);
  16610. this._workerCollisions = enabled;
  16611. if (this.collisionCoordinator) {
  16612. this.collisionCoordinator.destroy();
  16613. }
  16614. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16615. this.collisionCoordinator.init(this);
  16616. },
  16617. enumerable: true,
  16618. configurable: true
  16619. });
  16620. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  16621. get: function () {
  16622. return this._selectionOctree;
  16623. },
  16624. enumerable: true,
  16625. configurable: true
  16626. });
  16627. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16628. /**
  16629. * The mesh that is currently under the pointer.
  16630. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16631. */
  16632. get: function () {
  16633. return this._pointerOverMesh;
  16634. },
  16635. enumerable: true,
  16636. configurable: true
  16637. });
  16638. Object.defineProperty(Scene.prototype, "pointerX", {
  16639. /**
  16640. * Current on-screen X position of the pointer
  16641. * @return {number} X position of the pointer
  16642. */
  16643. get: function () {
  16644. return this._pointerX;
  16645. },
  16646. enumerable: true,
  16647. configurable: true
  16648. });
  16649. Object.defineProperty(Scene.prototype, "pointerY", {
  16650. /**
  16651. * Current on-screen Y position of the pointer
  16652. * @return {number} Y position of the pointer
  16653. */
  16654. get: function () {
  16655. return this._pointerY;
  16656. },
  16657. enumerable: true,
  16658. configurable: true
  16659. });
  16660. Scene.prototype.getCachedMaterial = function () {
  16661. return this._cachedMaterial;
  16662. };
  16663. Scene.prototype.getBoundingBoxRenderer = function () {
  16664. return this._boundingBoxRenderer;
  16665. };
  16666. Scene.prototype.getOutlineRenderer = function () {
  16667. return this._outlineRenderer;
  16668. };
  16669. Scene.prototype.getEngine = function () {
  16670. return this._engine;
  16671. };
  16672. Scene.prototype.getTotalVertices = function () {
  16673. return this._totalVertices.current;
  16674. };
  16675. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16676. get: function () {
  16677. return this._totalVertices;
  16678. },
  16679. enumerable: true,
  16680. configurable: true
  16681. });
  16682. Scene.prototype.getActiveIndices = function () {
  16683. return this._activeIndices.current;
  16684. };
  16685. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16686. get: function () {
  16687. return this._activeIndices;
  16688. },
  16689. enumerable: true,
  16690. configurable: true
  16691. });
  16692. Scene.prototype.getActiveParticles = function () {
  16693. return this._activeParticles.current;
  16694. };
  16695. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16696. get: function () {
  16697. return this._activeParticles;
  16698. },
  16699. enumerable: true,
  16700. configurable: true
  16701. });
  16702. Scene.prototype.getActiveBones = function () {
  16703. return this._activeBones.current;
  16704. };
  16705. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16706. get: function () {
  16707. return this._activeBones;
  16708. },
  16709. enumerable: true,
  16710. configurable: true
  16711. });
  16712. // Stats
  16713. Scene.prototype.getLastFrameDuration = function () {
  16714. return this._lastFrameDuration.current;
  16715. };
  16716. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16717. get: function () {
  16718. return this._lastFrameDuration;
  16719. },
  16720. enumerable: true,
  16721. configurable: true
  16722. });
  16723. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16724. return this._evaluateActiveMeshesDuration.current;
  16725. };
  16726. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16727. get: function () {
  16728. return this._evaluateActiveMeshesDuration;
  16729. },
  16730. enumerable: true,
  16731. configurable: true
  16732. });
  16733. Scene.prototype.getActiveMeshes = function () {
  16734. return this._activeMeshes;
  16735. };
  16736. Scene.prototype.getRenderTargetsDuration = function () {
  16737. return this._renderTargetsDuration.current;
  16738. };
  16739. Scene.prototype.getRenderDuration = function () {
  16740. return this._renderDuration.current;
  16741. };
  16742. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16743. get: function () {
  16744. return this._renderDuration;
  16745. },
  16746. enumerable: true,
  16747. configurable: true
  16748. });
  16749. Scene.prototype.getParticlesDuration = function () {
  16750. return this._particlesDuration.current;
  16751. };
  16752. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16753. get: function () {
  16754. return this._particlesDuration;
  16755. },
  16756. enumerable: true,
  16757. configurable: true
  16758. });
  16759. Scene.prototype.getSpritesDuration = function () {
  16760. return this._spritesDuration.current;
  16761. };
  16762. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16763. get: function () {
  16764. return this._spritesDuration;
  16765. },
  16766. enumerable: true,
  16767. configurable: true
  16768. });
  16769. Scene.prototype.getAnimationRatio = function () {
  16770. return this._animationRatio;
  16771. };
  16772. Scene.prototype.getRenderId = function () {
  16773. return this._renderId;
  16774. };
  16775. Scene.prototype.incrementRenderId = function () {
  16776. this._renderId++;
  16777. };
  16778. Scene.prototype._updatePointerPosition = function (evt) {
  16779. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16780. this._pointerX = evt.clientX - canvasRect.left;
  16781. this._pointerY = evt.clientY - canvasRect.top;
  16782. this._unTranslatedPointerX = this._pointerX;
  16783. this._unTranslatedPointerY = this._pointerY;
  16784. if (this.cameraToUseForPointers) {
  16785. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16786. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16787. }
  16788. };
  16789. // Pointers handling
  16790. /**
  16791. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16792. * @param attachUp defines if you want to attach events to pointerup
  16793. * @param attachDown defines if you want to attach events to pointerdown
  16794. * @param attachMove defines if you want to attach events to pointermove
  16795. */
  16796. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16797. var _this = this;
  16798. if (attachUp === void 0) { attachUp = true; }
  16799. if (attachDown === void 0) { attachDown = true; }
  16800. if (attachMove === void 0) { attachMove = true; }
  16801. var spritePredicate = function (sprite) {
  16802. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16803. };
  16804. this._onPointerMove = function (evt) {
  16805. _this._updatePointerPosition(evt);
  16806. // PreObservable support
  16807. if (_this.onPrePointerObservable.hasObservers()) {
  16808. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16809. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16810. _this.onPrePointerObservable.notifyObservers(pi, type);
  16811. if (pi.skipOnPointerObservable) {
  16812. return;
  16813. }
  16814. }
  16815. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16816. return;
  16817. }
  16818. var canvas = _this._engine.getRenderingCanvas();
  16819. if (!_this.pointerMovePredicate) {
  16820. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  16821. }
  16822. // Meshes
  16823. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16824. if (pickResult.hit && pickResult.pickedMesh) {
  16825. _this.setPointerOverSprite(null);
  16826. _this.setPointerOverMesh(pickResult.pickedMesh);
  16827. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16828. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  16829. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  16830. }
  16831. else {
  16832. canvas.style.cursor = _this.hoverCursor;
  16833. }
  16834. }
  16835. else {
  16836. canvas.style.cursor = "";
  16837. }
  16838. }
  16839. else {
  16840. _this.setPointerOverMesh(null);
  16841. // Sprites
  16842. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16843. if (pickResult.hit && pickResult.pickedSprite) {
  16844. _this.setPointerOverSprite(pickResult.pickedSprite);
  16845. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  16846. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  16847. }
  16848. else {
  16849. canvas.style.cursor = _this.hoverCursor;
  16850. }
  16851. }
  16852. else {
  16853. _this.setPointerOverSprite(null);
  16854. // Restore pointer
  16855. canvas.style.cursor = "";
  16856. }
  16857. }
  16858. if (_this.onPointerMove) {
  16859. _this.onPointerMove(evt, pickResult);
  16860. }
  16861. if (_this.onPointerObservable.hasObservers()) {
  16862. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16863. var pi = new PointerInfo(type, evt, pickResult);
  16864. _this.onPointerObservable.notifyObservers(pi, type);
  16865. }
  16866. };
  16867. this._onPointerDown = function (evt) {
  16868. _this._updatePointerPosition(evt);
  16869. // PreObservable support
  16870. if (_this.onPrePointerObservable.hasObservers()) {
  16871. var type = PointerEventTypes.POINTERDOWN;
  16872. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16873. _this.onPrePointerObservable.notifyObservers(pi, type);
  16874. if (pi.skipOnPointerObservable) {
  16875. return;
  16876. }
  16877. }
  16878. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16879. return;
  16880. }
  16881. _this._startingPointerPosition.x = _this._pointerX;
  16882. _this._startingPointerPosition.y = _this._pointerY;
  16883. _this._startingPointerTime = new Date().getTime();
  16884. if (!_this.pointerDownPredicate) {
  16885. _this.pointerDownPredicate = function (mesh) {
  16886. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  16887. };
  16888. }
  16889. // Meshes
  16890. _this._pickedDownMesh = null;
  16891. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16892. if (pickResult.hit && pickResult.pickedMesh) {
  16893. if (pickResult.pickedMesh.actionManager) {
  16894. _this._pickedDownMesh = pickResult.pickedMesh;
  16895. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  16896. switch (evt.button) {
  16897. case 0:
  16898. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16899. break;
  16900. case 1:
  16901. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16902. break;
  16903. case 2:
  16904. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16905. break;
  16906. }
  16907. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16908. }
  16909. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16910. var that = _this;
  16911. window.setTimeout(function () {
  16912. 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);
  16913. if (pickResult.hit && pickResult.pickedMesh) {
  16914. if (pickResult.pickedMesh.actionManager) {
  16915. 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)) {
  16916. that._startingPointerTime = 0;
  16917. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16918. }
  16919. }
  16920. }
  16921. }, BABYLON.ActionManager.LongPressDelay);
  16922. }
  16923. }
  16924. }
  16925. if (_this.onPointerDown) {
  16926. _this.onPointerDown(evt, pickResult);
  16927. }
  16928. if (_this.onPointerObservable.hasObservers()) {
  16929. var type = PointerEventTypes.POINTERDOWN;
  16930. var pi = new PointerInfo(type, evt, pickResult);
  16931. _this.onPointerObservable.notifyObservers(pi, type);
  16932. }
  16933. // Sprites
  16934. _this._pickedDownSprite = null;
  16935. if (_this.spriteManagers.length > 0) {
  16936. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16937. if (pickResult.hit && pickResult.pickedSprite) {
  16938. if (pickResult.pickedSprite.actionManager) {
  16939. _this._pickedDownSprite = pickResult.pickedSprite;
  16940. switch (evt.button) {
  16941. case 0:
  16942. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16943. break;
  16944. case 1:
  16945. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16946. break;
  16947. case 2:
  16948. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16949. break;
  16950. }
  16951. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16952. }
  16953. }
  16954. }
  16955. };
  16956. this._onPointerUp = function (evt) {
  16957. _this._updatePointerPosition(evt);
  16958. // PreObservable support
  16959. if (_this.onPrePointerObservable.hasObservers()) {
  16960. var type = PointerEventTypes.POINTERUP;
  16961. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16962. _this.onPrePointerObservable.notifyObservers(pi, type);
  16963. if (pi.skipOnPointerObservable) {
  16964. return;
  16965. }
  16966. }
  16967. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16968. return;
  16969. }
  16970. if (!_this.pointerUpPredicate) {
  16971. _this.pointerUpPredicate = function (mesh) {
  16972. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  16973. };
  16974. }
  16975. // Meshes
  16976. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  16977. if (pickResult.hit && pickResult.pickedMesh) {
  16978. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  16979. if (_this.onPointerPick) {
  16980. _this.onPointerPick(evt, pickResult);
  16981. }
  16982. if (_this.onPointerObservable.hasObservers()) {
  16983. var type = PointerEventTypes.POINTERPICK;
  16984. var pi = new PointerInfo(type, evt, pickResult);
  16985. _this.onPointerObservable.notifyObservers(pi, type);
  16986. }
  16987. }
  16988. if (pickResult.pickedMesh.actionManager) {
  16989. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16990. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16991. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16992. }
  16993. }
  16994. }
  16995. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  16996. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  16997. }
  16998. if (_this.onPointerUp) {
  16999. _this.onPointerUp(evt, pickResult);
  17000. }
  17001. if (_this.onPointerObservable.hasObservers()) {
  17002. var type = PointerEventTypes.POINTERUP;
  17003. var pi = new PointerInfo(type, evt, pickResult);
  17004. _this.onPointerObservable.notifyObservers(pi, type);
  17005. }
  17006. _this._startingPointerTime = 0;
  17007. // Sprites
  17008. if (_this.spriteManagers.length > 0) {
  17009. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17010. if (pickResult.hit && pickResult.pickedSprite) {
  17011. if (pickResult.pickedSprite.actionManager) {
  17012. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17013. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  17014. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17015. }
  17016. }
  17017. }
  17018. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  17019. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  17020. }
  17021. }
  17022. };
  17023. this._onKeyDown = function (evt) {
  17024. if (_this.actionManager) {
  17025. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17026. }
  17027. };
  17028. this._onKeyUp = function (evt) {
  17029. if (_this.actionManager) {
  17030. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17031. }
  17032. };
  17033. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17034. var canvas = this._engine.getRenderingCanvas();
  17035. if (attachMove) {
  17036. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17037. // Wheel
  17038. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17039. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17040. }
  17041. if (attachDown) {
  17042. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17043. }
  17044. if (attachUp) {
  17045. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17046. }
  17047. canvas.tabIndex = 1;
  17048. canvas.addEventListener("keydown", this._onKeyDown, false);
  17049. canvas.addEventListener("keyup", this._onKeyUp, false);
  17050. };
  17051. Scene.prototype.detachControl = function () {
  17052. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17053. var canvas = this._engine.getRenderingCanvas();
  17054. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17055. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17056. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17057. // Wheel
  17058. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17059. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17060. canvas.removeEventListener("keydown", this._onKeyDown);
  17061. canvas.removeEventListener("keyup", this._onKeyUp);
  17062. };
  17063. // Ready
  17064. Scene.prototype.isReady = function () {
  17065. if (this._pendingData.length > 0) {
  17066. return false;
  17067. }
  17068. var index;
  17069. for (index = 0; index < this._geometries.length; index++) {
  17070. var geometry = this._geometries[index];
  17071. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17072. return false;
  17073. }
  17074. }
  17075. for (index = 0; index < this.meshes.length; index++) {
  17076. var mesh = this.meshes[index];
  17077. if (!mesh.isReady()) {
  17078. return false;
  17079. }
  17080. var mat = mesh.material;
  17081. if (mat) {
  17082. if (!mat.isReady(mesh)) {
  17083. return false;
  17084. }
  17085. }
  17086. }
  17087. return true;
  17088. };
  17089. Scene.prototype.resetCachedMaterial = function () {
  17090. this._cachedMaterial = null;
  17091. };
  17092. Scene.prototype.registerBeforeRender = function (func) {
  17093. this.onBeforeRenderObservable.add(func);
  17094. };
  17095. Scene.prototype.unregisterBeforeRender = function (func) {
  17096. this.onBeforeRenderObservable.removeCallback(func);
  17097. };
  17098. Scene.prototype.registerAfterRender = function (func) {
  17099. this.onAfterRenderObservable.add(func);
  17100. };
  17101. Scene.prototype.unregisterAfterRender = function (func) {
  17102. this.onAfterRenderObservable.removeCallback(func);
  17103. };
  17104. Scene.prototype._addPendingData = function (data) {
  17105. this._pendingData.push(data);
  17106. };
  17107. Scene.prototype._removePendingData = function (data) {
  17108. var index = this._pendingData.indexOf(data);
  17109. if (index !== -1) {
  17110. this._pendingData.splice(index, 1);
  17111. }
  17112. };
  17113. Scene.prototype.getWaitingItemsCount = function () {
  17114. return this._pendingData.length;
  17115. };
  17116. /**
  17117. * Registers a function to be executed when the scene is ready.
  17118. * @param {Function} func - the function to be executed.
  17119. */
  17120. Scene.prototype.executeWhenReady = function (func) {
  17121. var _this = this;
  17122. this.onReadyObservable.add(func);
  17123. if (this._executeWhenReadyTimeoutId !== -1) {
  17124. return;
  17125. }
  17126. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17127. _this._checkIsReady();
  17128. }, 150);
  17129. };
  17130. Scene.prototype._checkIsReady = function () {
  17131. var _this = this;
  17132. if (this.isReady()) {
  17133. this.onReadyObservable.notifyObservers(this);
  17134. this.onReadyObservable.clear();
  17135. this._executeWhenReadyTimeoutId = -1;
  17136. return;
  17137. }
  17138. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17139. _this._checkIsReady();
  17140. }, 150);
  17141. };
  17142. // Animations
  17143. /**
  17144. * Will start the animation sequence of a given target
  17145. * @param target - the target
  17146. * @param {number} from - from which frame should animation start
  17147. * @param {number} to - till which frame should animation run.
  17148. * @param {boolean} [loop] - should the animation loop
  17149. * @param {number} [speedRatio] - the speed in which to run the animation
  17150. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17151. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17152. * @return {BABYLON.Animatable} the animatable object created for this animation
  17153. * @see BABYLON.Animatable
  17154. * @see http://doc.babylonjs.com/page.php?p=22081
  17155. */
  17156. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17157. if (speedRatio === void 0) { speedRatio = 1.0; }
  17158. this.stopAnimation(target);
  17159. if (!animatable) {
  17160. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17161. }
  17162. // Local animations
  17163. if (target.animations) {
  17164. animatable.appendAnimations(target, target.animations);
  17165. }
  17166. // Children animations
  17167. if (target.getAnimatables) {
  17168. var animatables = target.getAnimatables();
  17169. for (var index = 0; index < animatables.length; index++) {
  17170. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17171. }
  17172. }
  17173. animatable.reset();
  17174. return animatable;
  17175. };
  17176. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17177. if (speedRatio === undefined) {
  17178. speedRatio = 1.0;
  17179. }
  17180. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17181. return animatable;
  17182. };
  17183. Scene.prototype.getAnimatableByTarget = function (target) {
  17184. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17185. if (this._activeAnimatables[index].target === target) {
  17186. return this._activeAnimatables[index];
  17187. }
  17188. }
  17189. return null;
  17190. };
  17191. Object.defineProperty(Scene.prototype, "Animatables", {
  17192. get: function () {
  17193. return this._activeAnimatables;
  17194. },
  17195. enumerable: true,
  17196. configurable: true
  17197. });
  17198. /**
  17199. * Will stop the animation of the given target
  17200. * @param target - the target
  17201. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17202. * @see beginAnimation
  17203. */
  17204. Scene.prototype.stopAnimation = function (target, animationName) {
  17205. var animatable = this.getAnimatableByTarget(target);
  17206. if (animatable) {
  17207. animatable.stop(animationName);
  17208. }
  17209. };
  17210. Scene.prototype._animate = function () {
  17211. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17212. return;
  17213. }
  17214. if (!this._animationStartDate) {
  17215. if (this._pendingData.length > 0) {
  17216. return;
  17217. }
  17218. this._animationStartDate = BABYLON.Tools.Now;
  17219. }
  17220. // Getting time
  17221. var now = BABYLON.Tools.Now;
  17222. var delay = now - this._animationStartDate;
  17223. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17224. this._activeAnimatables[index]._animate(delay);
  17225. }
  17226. };
  17227. // Matrix
  17228. Scene.prototype.getViewMatrix = function () {
  17229. return this._viewMatrix;
  17230. };
  17231. Scene.prototype.getProjectionMatrix = function () {
  17232. return this._projectionMatrix;
  17233. };
  17234. Scene.prototype.getTransformMatrix = function () {
  17235. return this._transformMatrix;
  17236. };
  17237. Scene.prototype.setTransformMatrix = function (view, projection) {
  17238. this._viewMatrix = view;
  17239. this._projectionMatrix = projection;
  17240. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17241. // Update frustum
  17242. if (!this._frustumPlanes) {
  17243. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17244. }
  17245. else {
  17246. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17247. }
  17248. };
  17249. // Methods
  17250. Scene.prototype.addMesh = function (newMesh) {
  17251. newMesh.uniqueId = this._uniqueIdCounter++;
  17252. var position = this.meshes.push(newMesh);
  17253. //notify the collision coordinator
  17254. this.collisionCoordinator.onMeshAdded(newMesh);
  17255. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17256. };
  17257. Scene.prototype.removeMesh = function (toRemove) {
  17258. var index = this.meshes.indexOf(toRemove);
  17259. if (index !== -1) {
  17260. // Remove from the scene if mesh found
  17261. this.meshes.splice(index, 1);
  17262. }
  17263. //notify the collision coordinator
  17264. this.collisionCoordinator.onMeshRemoved(toRemove);
  17265. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17266. return index;
  17267. };
  17268. Scene.prototype.removeSkeleton = function (toRemove) {
  17269. var index = this.skeletons.indexOf(toRemove);
  17270. if (index !== -1) {
  17271. // Remove from the scene if mesh found
  17272. this.skeletons.splice(index, 1);
  17273. }
  17274. return index;
  17275. };
  17276. Scene.prototype.removeLight = function (toRemove) {
  17277. var index = this.lights.indexOf(toRemove);
  17278. if (index !== -1) {
  17279. // Remove from the scene if mesh found
  17280. this.lights.splice(index, 1);
  17281. }
  17282. this.onLightRemovedObservable.notifyObservers(toRemove);
  17283. return index;
  17284. };
  17285. Scene.prototype.removeCamera = function (toRemove) {
  17286. var index = this.cameras.indexOf(toRemove);
  17287. if (index !== -1) {
  17288. // Remove from the scene if mesh found
  17289. this.cameras.splice(index, 1);
  17290. }
  17291. // Remove from activeCameras
  17292. var index2 = this.activeCameras.indexOf(toRemove);
  17293. if (index2 !== -1) {
  17294. // Remove from the scene if mesh found
  17295. this.activeCameras.splice(index2, 1);
  17296. }
  17297. // Reset the activeCamera
  17298. if (this.activeCamera === toRemove) {
  17299. if (this.cameras.length > 0) {
  17300. this.activeCamera = this.cameras[0];
  17301. }
  17302. else {
  17303. this.activeCamera = null;
  17304. }
  17305. }
  17306. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17307. return index;
  17308. };
  17309. Scene.prototype.addLight = function (newLight) {
  17310. newLight.uniqueId = this._uniqueIdCounter++;
  17311. var position = this.lights.push(newLight);
  17312. this.onNewLightAddedObservable.notifyObservers(newLight);
  17313. };
  17314. Scene.prototype.addCamera = function (newCamera) {
  17315. newCamera.uniqueId = this._uniqueIdCounter++;
  17316. var position = this.cameras.push(newCamera);
  17317. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17318. };
  17319. /**
  17320. * Switch active camera
  17321. * @param {Camera} newCamera - new active camera
  17322. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17323. */
  17324. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17325. if (attachControl === void 0) { attachControl = true; }
  17326. var canvas = this._engine.getRenderingCanvas();
  17327. this.activeCamera.detachControl(canvas);
  17328. this.activeCamera = newCamera;
  17329. if (attachControl) {
  17330. newCamera.attachControl(canvas);
  17331. }
  17332. };
  17333. /**
  17334. * sets the active camera of the scene using its ID
  17335. * @param {string} id - the camera's ID
  17336. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17337. * @see activeCamera
  17338. */
  17339. Scene.prototype.setActiveCameraByID = function (id) {
  17340. var camera = this.getCameraByID(id);
  17341. if (camera) {
  17342. this.activeCamera = camera;
  17343. return camera;
  17344. }
  17345. return null;
  17346. };
  17347. /**
  17348. * sets the active camera of the scene using its name
  17349. * @param {string} name - the camera's name
  17350. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17351. * @see activeCamera
  17352. */
  17353. Scene.prototype.setActiveCameraByName = function (name) {
  17354. var camera = this.getCameraByName(name);
  17355. if (camera) {
  17356. this.activeCamera = camera;
  17357. return camera;
  17358. }
  17359. return null;
  17360. };
  17361. /**
  17362. * get a material using its id
  17363. * @param {string} the material's ID
  17364. * @return {BABYLON.Material|null} the material or null if none found.
  17365. */
  17366. Scene.prototype.getMaterialByID = function (id) {
  17367. for (var index = 0; index < this.materials.length; index++) {
  17368. if (this.materials[index].id === id) {
  17369. return this.materials[index];
  17370. }
  17371. }
  17372. return null;
  17373. };
  17374. /**
  17375. * get a material using its name
  17376. * @param {string} the material's name
  17377. * @return {BABYLON.Material|null} the material or null if none found.
  17378. */
  17379. Scene.prototype.getMaterialByName = function (name) {
  17380. for (var index = 0; index < this.materials.length; index++) {
  17381. if (this.materials[index].name === name) {
  17382. return this.materials[index];
  17383. }
  17384. }
  17385. return null;
  17386. };
  17387. Scene.prototype.getLensFlareSystemByName = function (name) {
  17388. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17389. if (this.lensFlareSystems[index].name === name) {
  17390. return this.lensFlareSystems[index];
  17391. }
  17392. }
  17393. return null;
  17394. };
  17395. Scene.prototype.getLensFlareSystemByID = function (id) {
  17396. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17397. if (this.lensFlareSystems[index].id === id) {
  17398. return this.lensFlareSystems[index];
  17399. }
  17400. }
  17401. return null;
  17402. };
  17403. Scene.prototype.getCameraByID = function (id) {
  17404. for (var index = 0; index < this.cameras.length; index++) {
  17405. if (this.cameras[index].id === id) {
  17406. return this.cameras[index];
  17407. }
  17408. }
  17409. return null;
  17410. };
  17411. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17412. for (var index = 0; index < this.cameras.length; index++) {
  17413. if (this.cameras[index].uniqueId === uniqueId) {
  17414. return this.cameras[index];
  17415. }
  17416. }
  17417. return null;
  17418. };
  17419. /**
  17420. * get a camera using its name
  17421. * @param {string} the camera's name
  17422. * @return {BABYLON.Camera|null} the camera or null if none found.
  17423. */
  17424. Scene.prototype.getCameraByName = function (name) {
  17425. for (var index = 0; index < this.cameras.length; index++) {
  17426. if (this.cameras[index].name === name) {
  17427. return this.cameras[index];
  17428. }
  17429. }
  17430. return null;
  17431. };
  17432. /**
  17433. * get a bone using its id
  17434. * @param {string} the bone's id
  17435. * @return {BABYLON.Bone|null} the bone or null if not found
  17436. */
  17437. Scene.prototype.getBoneByID = function (id) {
  17438. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17439. var skeleton = this.skeletons[skeletonIndex];
  17440. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17441. if (skeleton.bones[boneIndex].id === id) {
  17442. return skeleton.bones[boneIndex];
  17443. }
  17444. }
  17445. }
  17446. return null;
  17447. };
  17448. /**
  17449. * get a bone using its id
  17450. * @param {string} the bone's name
  17451. * @return {BABYLON.Bone|null} the bone or null if not found
  17452. */
  17453. Scene.prototype.getBoneByName = function (name) {
  17454. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17455. var skeleton = this.skeletons[skeletonIndex];
  17456. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17457. if (skeleton.bones[boneIndex].name === name) {
  17458. return skeleton.bones[boneIndex];
  17459. }
  17460. }
  17461. }
  17462. return null;
  17463. };
  17464. /**
  17465. * get a light node using its name
  17466. * @param {string} the light's name
  17467. * @return {BABYLON.Light|null} the light or null if none found.
  17468. */
  17469. Scene.prototype.getLightByName = function (name) {
  17470. for (var index = 0; index < this.lights.length; index++) {
  17471. if (this.lights[index].name === name) {
  17472. return this.lights[index];
  17473. }
  17474. }
  17475. return null;
  17476. };
  17477. /**
  17478. * get a light node using its ID
  17479. * @param {string} the light's id
  17480. * @return {BABYLON.Light|null} the light or null if none found.
  17481. */
  17482. Scene.prototype.getLightByID = function (id) {
  17483. for (var index = 0; index < this.lights.length; index++) {
  17484. if (this.lights[index].id === id) {
  17485. return this.lights[index];
  17486. }
  17487. }
  17488. return null;
  17489. };
  17490. /**
  17491. * get a light node using its scene-generated unique ID
  17492. * @param {number} the light's unique id
  17493. * @return {BABYLON.Light|null} the light or null if none found.
  17494. */
  17495. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17496. for (var index = 0; index < this.lights.length; index++) {
  17497. if (this.lights[index].uniqueId === uniqueId) {
  17498. return this.lights[index];
  17499. }
  17500. }
  17501. return null;
  17502. };
  17503. /**
  17504. * get a particle system by id
  17505. * @param id {number} the particle system id
  17506. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17507. */
  17508. Scene.prototype.getParticleSystemByID = function (id) {
  17509. for (var index = 0; index < this.particleSystems.length; index++) {
  17510. if (this.particleSystems[index].id === id) {
  17511. return this.particleSystems[index];
  17512. }
  17513. }
  17514. return null;
  17515. };
  17516. /**
  17517. * get a geometry using its ID
  17518. * @param {string} the geometry's id
  17519. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17520. */
  17521. Scene.prototype.getGeometryByID = function (id) {
  17522. for (var index = 0; index < this._geometries.length; index++) {
  17523. if (this._geometries[index].id === id) {
  17524. return this._geometries[index];
  17525. }
  17526. }
  17527. return null;
  17528. };
  17529. /**
  17530. * add a new geometry to this scene.
  17531. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17532. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17533. * @return {boolean} was the geometry added or not
  17534. */
  17535. Scene.prototype.pushGeometry = function (geometry, force) {
  17536. if (!force && this.getGeometryByID(geometry.id)) {
  17537. return false;
  17538. }
  17539. this._geometries.push(geometry);
  17540. //notify the collision coordinator
  17541. this.collisionCoordinator.onGeometryAdded(geometry);
  17542. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17543. return true;
  17544. };
  17545. /**
  17546. * Removes an existing geometry
  17547. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17548. * @return {boolean} was the geometry removed or not
  17549. */
  17550. Scene.prototype.removeGeometry = function (geometry) {
  17551. var index = this._geometries.indexOf(geometry);
  17552. if (index > -1) {
  17553. this._geometries.splice(index, 1);
  17554. //notify the collision coordinator
  17555. this.collisionCoordinator.onGeometryDeleted(geometry);
  17556. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17557. return true;
  17558. }
  17559. return false;
  17560. };
  17561. Scene.prototype.getGeometries = function () {
  17562. return this._geometries;
  17563. };
  17564. /**
  17565. * Get the first added mesh found of a given ID
  17566. * @param {string} id - the id to search for
  17567. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17568. */
  17569. Scene.prototype.getMeshByID = function (id) {
  17570. for (var index = 0; index < this.meshes.length; index++) {
  17571. if (this.meshes[index].id === id) {
  17572. return this.meshes[index];
  17573. }
  17574. }
  17575. return null;
  17576. };
  17577. Scene.prototype.getMeshesByID = function (id) {
  17578. return this.meshes.filter(function (m) {
  17579. return m.id === id;
  17580. });
  17581. };
  17582. /**
  17583. * Get a mesh with its auto-generated unique id
  17584. * @param {number} uniqueId - the unique id to search for
  17585. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17586. */
  17587. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17588. for (var index = 0; index < this.meshes.length; index++) {
  17589. if (this.meshes[index].uniqueId === uniqueId) {
  17590. return this.meshes[index];
  17591. }
  17592. }
  17593. return null;
  17594. };
  17595. /**
  17596. * Get a the last added mesh found of a given ID
  17597. * @param {string} id - the id to search for
  17598. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17599. */
  17600. Scene.prototype.getLastMeshByID = function (id) {
  17601. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17602. if (this.meshes[index].id === id) {
  17603. return this.meshes[index];
  17604. }
  17605. }
  17606. return null;
  17607. };
  17608. /**
  17609. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17610. * @param {string} id - the id to search for
  17611. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17612. */
  17613. Scene.prototype.getLastEntryByID = function (id) {
  17614. var index;
  17615. for (index = this.meshes.length - 1; index >= 0; index--) {
  17616. if (this.meshes[index].id === id) {
  17617. return this.meshes[index];
  17618. }
  17619. }
  17620. for (index = this.cameras.length - 1; index >= 0; index--) {
  17621. if (this.cameras[index].id === id) {
  17622. return this.cameras[index];
  17623. }
  17624. }
  17625. for (index = this.lights.length - 1; index >= 0; index--) {
  17626. if (this.lights[index].id === id) {
  17627. return this.lights[index];
  17628. }
  17629. }
  17630. return null;
  17631. };
  17632. Scene.prototype.getNodeByID = function (id) {
  17633. var mesh = this.getMeshByID(id);
  17634. if (mesh) {
  17635. return mesh;
  17636. }
  17637. var light = this.getLightByID(id);
  17638. if (light) {
  17639. return light;
  17640. }
  17641. var camera = this.getCameraByID(id);
  17642. if (camera) {
  17643. return camera;
  17644. }
  17645. var bone = this.getBoneByID(id);
  17646. return bone;
  17647. };
  17648. Scene.prototype.getNodeByName = function (name) {
  17649. var mesh = this.getMeshByName(name);
  17650. if (mesh) {
  17651. return mesh;
  17652. }
  17653. var light = this.getLightByName(name);
  17654. if (light) {
  17655. return light;
  17656. }
  17657. var camera = this.getCameraByName(name);
  17658. if (camera) {
  17659. return camera;
  17660. }
  17661. var bone = this.getBoneByName(name);
  17662. return bone;
  17663. };
  17664. Scene.prototype.getMeshByName = function (name) {
  17665. for (var index = 0; index < this.meshes.length; index++) {
  17666. if (this.meshes[index].name === name) {
  17667. return this.meshes[index];
  17668. }
  17669. }
  17670. return null;
  17671. };
  17672. Scene.prototype.getSoundByName = function (name) {
  17673. var index;
  17674. if (BABYLON.AudioEngine) {
  17675. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17676. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17677. return this.mainSoundTrack.soundCollection[index];
  17678. }
  17679. }
  17680. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17681. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17682. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17683. return this.soundTracks[sdIndex].soundCollection[index];
  17684. }
  17685. }
  17686. }
  17687. }
  17688. return null;
  17689. };
  17690. Scene.prototype.getLastSkeletonByID = function (id) {
  17691. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17692. if (this.skeletons[index].id === id) {
  17693. return this.skeletons[index];
  17694. }
  17695. }
  17696. return null;
  17697. };
  17698. Scene.prototype.getSkeletonById = function (id) {
  17699. for (var index = 0; index < this.skeletons.length; index++) {
  17700. if (this.skeletons[index].id === id) {
  17701. return this.skeletons[index];
  17702. }
  17703. }
  17704. return null;
  17705. };
  17706. Scene.prototype.getSkeletonByName = function (name) {
  17707. for (var index = 0; index < this.skeletons.length; index++) {
  17708. if (this.skeletons[index].name === name) {
  17709. return this.skeletons[index];
  17710. }
  17711. }
  17712. return null;
  17713. };
  17714. Scene.prototype.isActiveMesh = function (mesh) {
  17715. return (this._activeMeshes.indexOf(mesh) !== -1);
  17716. };
  17717. Object.defineProperty(Scene.prototype, "uid", {
  17718. /**
  17719. * Return a unique id as a string which can serve as an identifier for the scene
  17720. */
  17721. get: function () {
  17722. if (!this._uid) {
  17723. this._uid = BABYLON.Tools.RandomId();
  17724. }
  17725. return this._uid;
  17726. },
  17727. enumerable: true,
  17728. configurable: true
  17729. });
  17730. /**
  17731. * Add an externaly attached data from its key.
  17732. * This method call will fail and return false, if such key already exists.
  17733. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17734. * @param key the unique key that identifies the data
  17735. * @param data the data object to associate to the key for this Engine instance
  17736. * @return true if no such key were already present and the data was added successfully, false otherwise
  17737. */
  17738. Scene.prototype.addExternalData = function (key, data) {
  17739. return this._externalData.add(key, data);
  17740. };
  17741. /**
  17742. * Get an externaly attached data from its key
  17743. * @param key the unique key that identifies the data
  17744. * @return the associated data, if present (can be null), or undefined if not present
  17745. */
  17746. Scene.prototype.getExternalData = function (key) {
  17747. return this._externalData.get(key);
  17748. };
  17749. /**
  17750. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17751. * @param key the unique key that identifies the data
  17752. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17753. * @return the associated data, can be null if the factory returned null.
  17754. */
  17755. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17756. return this._externalData.getOrAddWithFactory(key, factory);
  17757. };
  17758. /**
  17759. * Remove an externaly attached data from the Engine instance
  17760. * @param key the unique key that identifies the data
  17761. * @return true if the data was successfully removed, false if it doesn't exist
  17762. */
  17763. Scene.prototype.removeExternalData = function (key) {
  17764. return this._externalData.remove(key);
  17765. };
  17766. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17767. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17768. var material = subMesh.getMaterial();
  17769. if (mesh.showSubMeshesBoundingBox) {
  17770. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  17771. }
  17772. if (material) {
  17773. // Render targets
  17774. if (material.getRenderTargetTextures) {
  17775. if (this._processedMaterials.indexOf(material) === -1) {
  17776. this._processedMaterials.push(material);
  17777. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17778. }
  17779. }
  17780. // Dispatch
  17781. this._activeIndices.addCount(subMesh.indexCount, false);
  17782. this._renderingManager.dispatch(subMesh);
  17783. }
  17784. }
  17785. };
  17786. Scene.prototype._isInIntermediateRendering = function () {
  17787. return this._intermediateRendering;
  17788. };
  17789. Scene.prototype._evaluateActiveMeshes = function () {
  17790. this.activeCamera._activeMeshes.reset();
  17791. this._activeMeshes.reset();
  17792. this._renderingManager.reset();
  17793. this._processedMaterials.reset();
  17794. this._activeParticleSystems.reset();
  17795. this._activeSkeletons.reset();
  17796. this._softwareSkinnedMeshes.reset();
  17797. this._boundingBoxRenderer.reset();
  17798. this._edgesRenderers.reset();
  17799. // Meshes
  17800. var meshes;
  17801. var len;
  17802. if (this._selectionOctree) {
  17803. var selection = this._selectionOctree.select(this._frustumPlanes);
  17804. meshes = selection.data;
  17805. len = selection.length;
  17806. }
  17807. else {
  17808. len = this.meshes.length;
  17809. meshes = this.meshes;
  17810. }
  17811. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17812. var mesh = meshes[meshIndex];
  17813. if (mesh.isBlocked) {
  17814. continue;
  17815. }
  17816. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17817. if (!mesh.isReady() || !mesh.isEnabled()) {
  17818. continue;
  17819. }
  17820. mesh.computeWorldMatrix();
  17821. // Intersections
  17822. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17823. this._meshesForIntersections.pushNoDuplicate(mesh);
  17824. }
  17825. // Switch to current LOD
  17826. var meshLOD = mesh.getLOD(this.activeCamera);
  17827. if (!meshLOD) {
  17828. continue;
  17829. }
  17830. mesh._preActivate();
  17831. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17832. this._activeMeshes.push(mesh);
  17833. this.activeCamera._activeMeshes.push(mesh);
  17834. mesh._activate(this._renderId);
  17835. this._activeMesh(mesh, meshLOD);
  17836. }
  17837. }
  17838. // Particle systems
  17839. this._particlesDuration.beginMonitoring();
  17840. var beforeParticlesDate = BABYLON.Tools.Now;
  17841. if (this.particlesEnabled) {
  17842. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17843. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17844. var particleSystem = this.particleSystems[particleIndex];
  17845. if (!particleSystem.isStarted()) {
  17846. continue;
  17847. }
  17848. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17849. this._activeParticleSystems.push(particleSystem);
  17850. particleSystem.animate();
  17851. }
  17852. }
  17853. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17854. }
  17855. this._particlesDuration.endMonitoring(false);
  17856. };
  17857. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17858. if (mesh.skeleton && this.skeletonsEnabled) {
  17859. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17860. mesh.skeleton.prepare();
  17861. }
  17862. if (!mesh.computeBonesUsingShaders) {
  17863. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17864. }
  17865. }
  17866. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17867. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17868. }
  17869. if (sourceMesh._edgesRenderer) {
  17870. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  17871. }
  17872. if (mesh && mesh.subMeshes) {
  17873. // Submeshes Octrees
  17874. var len;
  17875. var subMeshes;
  17876. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17877. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17878. len = intersections.length;
  17879. subMeshes = intersections.data;
  17880. }
  17881. else {
  17882. subMeshes = mesh.subMeshes;
  17883. len = subMeshes.length;
  17884. }
  17885. for (var subIndex = 0; subIndex < len; subIndex++) {
  17886. var subMesh = subMeshes[subIndex];
  17887. this._evaluateSubMesh(subMesh, mesh);
  17888. }
  17889. }
  17890. };
  17891. Scene.prototype.updateTransformMatrix = function (force) {
  17892. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17893. };
  17894. Scene.prototype._renderForCamera = function (camera) {
  17895. var engine = this._engine;
  17896. var startTime = BABYLON.Tools.Now;
  17897. this.activeCamera = camera;
  17898. if (!this.activeCamera)
  17899. throw new Error("Active camera not set");
  17900. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17901. // Viewport
  17902. engine.setViewport(this.activeCamera.viewport);
  17903. // Camera
  17904. this.resetCachedMaterial();
  17905. this._renderId++;
  17906. this.updateTransformMatrix();
  17907. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17908. // Meshes
  17909. this._evaluateActiveMeshesDuration.beginMonitoring();
  17910. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17911. this._evaluateActiveMeshes();
  17912. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17913. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17914. // Software skinning
  17915. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17916. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17917. mesh.applySkeleton(mesh.skeleton);
  17918. }
  17919. // Render targets
  17920. this._renderTargetsDuration.beginMonitoring();
  17921. var needsRestoreFrameBuffer = false;
  17922. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17923. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17924. this._intermediateRendering = true;
  17925. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17926. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17927. var renderTarget = this._renderTargets.data[renderIndex];
  17928. if (renderTarget._shouldRender()) {
  17929. this._renderId++;
  17930. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17931. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17932. }
  17933. }
  17934. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17935. this._intermediateRendering = false;
  17936. this._renderId++;
  17937. needsRestoreFrameBuffer = true; // Restore back buffer
  17938. }
  17939. // Render HighlightLayer Texture
  17940. var stencilState = this._engine.getStencilBuffer();
  17941. var renderhighlights = false;
  17942. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  17943. this._intermediateRendering = true;
  17944. for (var i = 0; i < this.highlightLayers.length; i++) {
  17945. var highlightLayer = this.highlightLayers[i];
  17946. if (highlightLayer.shouldRender() &&
  17947. (!highlightLayer.camera ||
  17948. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  17949. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  17950. renderhighlights = true;
  17951. var renderTarget = highlightLayer._mainTexture;
  17952. if (renderTarget._shouldRender()) {
  17953. this._renderId++;
  17954. renderTarget.render(false, false);
  17955. needsRestoreFrameBuffer = true;
  17956. }
  17957. }
  17958. }
  17959. this._intermediateRendering = false;
  17960. this._renderId++;
  17961. }
  17962. if (needsRestoreFrameBuffer) {
  17963. engine.restoreDefaultFramebuffer();
  17964. }
  17965. this._renderTargetsDuration.endMonitoring(false);
  17966. // Prepare Frame
  17967. this.postProcessManager._prepareFrame();
  17968. this._renderDuration.beginMonitoring();
  17969. // Backgrounds
  17970. var layerIndex;
  17971. var layer;
  17972. if (this.layers.length) {
  17973. engine.setDepthBuffer(false);
  17974. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17975. layer = this.layers[layerIndex];
  17976. if (layer.isBackground) {
  17977. layer.render();
  17978. }
  17979. }
  17980. engine.setDepthBuffer(true);
  17981. }
  17982. // Render
  17983. BABYLON.Tools.StartPerformanceCounter("Main render");
  17984. // Activate HighlightLayer stencil
  17985. if (renderhighlights) {
  17986. this._engine.setStencilBuffer(true);
  17987. }
  17988. this._renderingManager.render(null, null, true, true);
  17989. // Restore HighlightLayer stencil
  17990. if (renderhighlights) {
  17991. this._engine.setStencilBuffer(stencilState);
  17992. }
  17993. BABYLON.Tools.EndPerformanceCounter("Main render");
  17994. // Bounding boxes
  17995. this._boundingBoxRenderer.render();
  17996. // Edges
  17997. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17998. this._edgesRenderers.data[edgesRendererIndex].render();
  17999. }
  18000. // Lens flares
  18001. if (this.lensFlaresEnabled) {
  18002. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18003. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18004. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18005. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18006. lensFlareSystem.render();
  18007. }
  18008. }
  18009. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18010. }
  18011. // Foregrounds
  18012. if (this.layers.length) {
  18013. engine.setDepthBuffer(false);
  18014. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18015. layer = this.layers[layerIndex];
  18016. if (!layer.isBackground) {
  18017. layer.render();
  18018. }
  18019. }
  18020. engine.setDepthBuffer(true);
  18021. }
  18022. // Highlight Layer
  18023. if (renderhighlights) {
  18024. engine.setDepthBuffer(false);
  18025. for (var i = 0; i < this.highlightLayers.length; i++) {
  18026. if (this.highlightLayers[i].shouldRender()) {
  18027. this.highlightLayers[i].render();
  18028. }
  18029. }
  18030. engine.setDepthBuffer(true);
  18031. }
  18032. this._renderDuration.endMonitoring(false);
  18033. // Finalize frame
  18034. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18035. // Update camera
  18036. this.activeCamera._updateFromScene();
  18037. // Reset some special arrays
  18038. this._renderTargets.reset();
  18039. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18040. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18041. };
  18042. Scene.prototype._processSubCameras = function (camera) {
  18043. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18044. this._renderForCamera(camera);
  18045. return;
  18046. }
  18047. // rig cameras
  18048. for (var index = 0; index < camera._rigCameras.length; index++) {
  18049. this._renderForCamera(camera._rigCameras[index]);
  18050. }
  18051. this.activeCamera = camera;
  18052. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18053. // Update camera
  18054. this.activeCamera._updateFromScene();
  18055. };
  18056. Scene.prototype._checkIntersections = function () {
  18057. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18058. var sourceMesh = this._meshesForIntersections.data[index];
  18059. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18060. var action = sourceMesh.actionManager.actions[actionIndex];
  18061. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18062. var parameters = action.getTriggerParameter();
  18063. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18064. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18065. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18066. if (areIntersecting && currentIntersectionInProgress === -1) {
  18067. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18068. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18069. sourceMesh._intersectionsInProgress.push(otherMesh);
  18070. }
  18071. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18072. sourceMesh._intersectionsInProgress.push(otherMesh);
  18073. }
  18074. }
  18075. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18076. //They intersected, and now they don't.
  18077. //is this trigger an exit trigger? execute an event.
  18078. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18079. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18080. }
  18081. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18082. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18083. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18084. }
  18085. }
  18086. }
  18087. }
  18088. }
  18089. };
  18090. Scene.prototype.render = function () {
  18091. this._lastFrameDuration.beginMonitoring();
  18092. this._particlesDuration.fetchNewFrame();
  18093. this._spritesDuration.fetchNewFrame();
  18094. this._activeParticles.fetchNewFrame();
  18095. this._renderDuration.fetchNewFrame();
  18096. this._renderTargetsDuration.fetchNewFrame();
  18097. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18098. this._totalVertices.fetchNewFrame();
  18099. this._activeIndices.fetchNewFrame();
  18100. this._activeBones.fetchNewFrame();
  18101. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18102. this._meshesForIntersections.reset();
  18103. this.resetCachedMaterial();
  18104. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18105. // Actions
  18106. if (this.actionManager) {
  18107. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18108. }
  18109. //Simplification Queue
  18110. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18111. this.simplificationQueue.executeNext();
  18112. }
  18113. // Animations
  18114. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18115. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18116. this._animate();
  18117. // Physics
  18118. if (this._physicsEngine) {
  18119. BABYLON.Tools.StartPerformanceCounter("Physics");
  18120. this._physicsEngine._step(deltaTime / 1000.0);
  18121. BABYLON.Tools.EndPerformanceCounter("Physics");
  18122. }
  18123. // Before render
  18124. this.onBeforeRenderObservable.notifyObservers(this);
  18125. // Customs render targets
  18126. this._renderTargetsDuration.beginMonitoring();
  18127. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18128. var engine = this.getEngine();
  18129. var currentActiveCamera = this.activeCamera;
  18130. if (this.renderTargetsEnabled) {
  18131. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18132. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18133. var renderTarget = this.customRenderTargets[customIndex];
  18134. if (renderTarget._shouldRender()) {
  18135. this._renderId++;
  18136. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18137. if (!this.activeCamera)
  18138. throw new Error("Active camera not set");
  18139. // Viewport
  18140. engine.setViewport(this.activeCamera.viewport);
  18141. // Camera
  18142. this.updateTransformMatrix();
  18143. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18144. }
  18145. }
  18146. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18147. this._renderId++;
  18148. }
  18149. if (this.customRenderTargets.length > 0) {
  18150. engine.restoreDefaultFramebuffer();
  18151. }
  18152. this._renderTargetsDuration.endMonitoring();
  18153. this.activeCamera = currentActiveCamera;
  18154. // Procedural textures
  18155. if (this.proceduralTexturesEnabled) {
  18156. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18157. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18158. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18159. if (proceduralTexture._shouldRender()) {
  18160. proceduralTexture.render();
  18161. }
  18162. }
  18163. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18164. }
  18165. // Clear
  18166. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  18167. // Shadows
  18168. if (this.shadowsEnabled) {
  18169. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18170. var light = this.lights[lightIndex];
  18171. var shadowGenerator = light.getShadowGenerator();
  18172. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  18173. this._renderTargets.push(shadowGenerator.getShadowMap());
  18174. }
  18175. }
  18176. }
  18177. // Depth renderer
  18178. if (this._depthRenderer) {
  18179. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18180. }
  18181. // RenderPipeline
  18182. this.postProcessRenderPipelineManager.update();
  18183. // Multi-cameras?
  18184. if (this.activeCameras.length > 0) {
  18185. var currentRenderId = this._renderId;
  18186. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18187. this._renderId = currentRenderId;
  18188. if (cameraIndex > 0) {
  18189. this._engine.clear(0, false, true, true);
  18190. }
  18191. this._processSubCameras(this.activeCameras[cameraIndex]);
  18192. }
  18193. }
  18194. else {
  18195. if (!this.activeCamera) {
  18196. throw new Error("No camera defined");
  18197. }
  18198. this._processSubCameras(this.activeCamera);
  18199. }
  18200. // Intersection checks
  18201. this._checkIntersections();
  18202. // Update the audio listener attached to the camera
  18203. if (BABYLON.AudioEngine) {
  18204. this._updateAudioParameters();
  18205. }
  18206. // After render
  18207. if (this.afterRender) {
  18208. this.afterRender();
  18209. }
  18210. this.onAfterRenderObservable.notifyObservers(this);
  18211. // Cleaning
  18212. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18213. this._toBeDisposed.data[index].dispose();
  18214. this._toBeDisposed[index] = null;
  18215. }
  18216. this._toBeDisposed.reset();
  18217. if (this.dumpNextRenderTargets) {
  18218. this.dumpNextRenderTargets = false;
  18219. }
  18220. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18221. this._lastFrameDuration.endMonitoring();
  18222. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18223. this._totalLightsCounter.addCount(this.lights.length, true);
  18224. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18225. this._totalTexturesCounter.addCount(this.textures.length, true);
  18226. this._activeBones.addCount(0, true);
  18227. this._activeIndices.addCount(0, true);
  18228. this._activeParticles.addCount(0, true);
  18229. };
  18230. Scene.prototype._updateAudioParameters = function () {
  18231. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18232. return;
  18233. }
  18234. var listeningCamera;
  18235. var audioEngine = BABYLON.Engine.audioEngine;
  18236. if (this.activeCameras.length > 0) {
  18237. listeningCamera = this.activeCameras[0];
  18238. }
  18239. else {
  18240. listeningCamera = this.activeCamera;
  18241. }
  18242. if (listeningCamera && audioEngine.canUseWebAudio) {
  18243. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18244. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18245. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18246. cameraDirection.normalize();
  18247. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18248. var i;
  18249. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18250. var sound = this.mainSoundTrack.soundCollection[i];
  18251. if (sound.useCustomAttenuation) {
  18252. sound.updateDistanceFromListener();
  18253. }
  18254. }
  18255. for (i = 0; i < this.soundTracks.length; i++) {
  18256. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18257. sound = this.soundTracks[i].soundCollection[j];
  18258. if (sound.useCustomAttenuation) {
  18259. sound.updateDistanceFromListener();
  18260. }
  18261. }
  18262. }
  18263. }
  18264. };
  18265. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18266. // Audio
  18267. get: function () {
  18268. return this._audioEnabled;
  18269. },
  18270. set: function (value) {
  18271. this._audioEnabled = value;
  18272. if (BABYLON.AudioEngine) {
  18273. if (this._audioEnabled) {
  18274. this._enableAudio();
  18275. }
  18276. else {
  18277. this._disableAudio();
  18278. }
  18279. }
  18280. },
  18281. enumerable: true,
  18282. configurable: true
  18283. });
  18284. Scene.prototype._disableAudio = function () {
  18285. var i;
  18286. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18287. this.mainSoundTrack.soundCollection[i].pause();
  18288. }
  18289. for (i = 0; i < this.soundTracks.length; i++) {
  18290. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18291. this.soundTracks[i].soundCollection[j].pause();
  18292. }
  18293. }
  18294. };
  18295. Scene.prototype._enableAudio = function () {
  18296. var i;
  18297. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18298. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18299. this.mainSoundTrack.soundCollection[i].play();
  18300. }
  18301. }
  18302. for (i = 0; i < this.soundTracks.length; i++) {
  18303. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18304. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18305. this.soundTracks[i].soundCollection[j].play();
  18306. }
  18307. }
  18308. }
  18309. };
  18310. Object.defineProperty(Scene.prototype, "headphone", {
  18311. get: function () {
  18312. return this._headphone;
  18313. },
  18314. set: function (value) {
  18315. this._headphone = value;
  18316. if (BABYLON.AudioEngine) {
  18317. if (this._headphone) {
  18318. this._switchAudioModeForHeadphones();
  18319. }
  18320. else {
  18321. this._switchAudioModeForNormalSpeakers();
  18322. }
  18323. }
  18324. },
  18325. enumerable: true,
  18326. configurable: true
  18327. });
  18328. Scene.prototype._switchAudioModeForHeadphones = function () {
  18329. this.mainSoundTrack.switchPanningModelToHRTF();
  18330. for (var i = 0; i < this.soundTracks.length; i++) {
  18331. this.soundTracks[i].switchPanningModelToHRTF();
  18332. }
  18333. };
  18334. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18335. this.mainSoundTrack.switchPanningModelToEqualPower();
  18336. for (var i = 0; i < this.soundTracks.length; i++) {
  18337. this.soundTracks[i].switchPanningModelToEqualPower();
  18338. }
  18339. };
  18340. Scene.prototype.enableDepthRenderer = function () {
  18341. if (this._depthRenderer) {
  18342. return this._depthRenderer;
  18343. }
  18344. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18345. return this._depthRenderer;
  18346. };
  18347. Scene.prototype.disableDepthRenderer = function () {
  18348. if (!this._depthRenderer) {
  18349. return;
  18350. }
  18351. this._depthRenderer.dispose();
  18352. this._depthRenderer = null;
  18353. };
  18354. Scene.prototype.freezeMaterials = function () {
  18355. for (var i = 0; i < this.materials.length; i++) {
  18356. this.materials[i].freeze();
  18357. }
  18358. };
  18359. Scene.prototype.unfreezeMaterials = function () {
  18360. for (var i = 0; i < this.materials.length; i++) {
  18361. this.materials[i].unfreeze();
  18362. }
  18363. };
  18364. Scene.prototype.dispose = function () {
  18365. this.beforeRender = null;
  18366. this.afterRender = null;
  18367. this.skeletons = [];
  18368. this._boundingBoxRenderer.dispose();
  18369. if (this._depthRenderer) {
  18370. this._depthRenderer.dispose();
  18371. }
  18372. // Debug layer
  18373. if (this._debugLayer) {
  18374. this._debugLayer.hide();
  18375. }
  18376. // Events
  18377. this.onDisposeObservable.notifyObservers(this);
  18378. this.onDisposeObservable.clear();
  18379. this.onBeforeRenderObservable.clear();
  18380. this.onAfterRenderObservable.clear();
  18381. this.detachControl();
  18382. // Release sounds & sounds tracks
  18383. if (BABYLON.AudioEngine) {
  18384. this.disposeSounds();
  18385. }
  18386. // Detach cameras
  18387. var canvas = this._engine.getRenderingCanvas();
  18388. var index;
  18389. for (index = 0; index < this.cameras.length; index++) {
  18390. this.cameras[index].detachControl(canvas);
  18391. }
  18392. // Release lights
  18393. while (this.lights.length) {
  18394. this.lights[0].dispose();
  18395. }
  18396. // Release meshes
  18397. while (this.meshes.length) {
  18398. this.meshes[0].dispose(true);
  18399. }
  18400. // Release cameras
  18401. while (this.cameras.length) {
  18402. this.cameras[0].dispose();
  18403. }
  18404. // Release materials
  18405. while (this.materials.length) {
  18406. this.materials[0].dispose();
  18407. }
  18408. // Release particles
  18409. while (this.particleSystems.length) {
  18410. this.particleSystems[0].dispose();
  18411. }
  18412. // Release sprites
  18413. while (this.spriteManagers.length) {
  18414. this.spriteManagers[0].dispose();
  18415. }
  18416. // Release layers
  18417. while (this.layers.length) {
  18418. this.layers[0].dispose();
  18419. }
  18420. while (this.highlightLayers.length) {
  18421. this.highlightLayers[0].dispose();
  18422. }
  18423. // Release textures
  18424. while (this.textures.length) {
  18425. this.textures[0].dispose();
  18426. }
  18427. // Post-processes
  18428. this.postProcessManager.dispose();
  18429. // Physics
  18430. if (this._physicsEngine) {
  18431. this.disablePhysicsEngine();
  18432. }
  18433. // Remove from engine
  18434. index = this._engine.scenes.indexOf(this);
  18435. if (index > -1) {
  18436. this._engine.scenes.splice(index, 1);
  18437. }
  18438. this._engine.wipeCaches();
  18439. };
  18440. // Release sounds & sounds tracks
  18441. Scene.prototype.disposeSounds = function () {
  18442. this.mainSoundTrack.dispose();
  18443. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18444. this.soundTracks[scIndex].dispose();
  18445. }
  18446. };
  18447. // Octrees
  18448. Scene.prototype.getWorldExtends = function () {
  18449. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18450. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18451. for (var index = 0; index < this.meshes.length; index++) {
  18452. var mesh = this.meshes[index];
  18453. mesh.computeWorldMatrix(true);
  18454. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18455. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18456. BABYLON.Tools.CheckExtends(minBox, min, max);
  18457. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18458. }
  18459. return {
  18460. min: min,
  18461. max: max
  18462. };
  18463. };
  18464. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18465. if (maxCapacity === void 0) { maxCapacity = 64; }
  18466. if (maxDepth === void 0) { maxDepth = 2; }
  18467. if (!this._selectionOctree) {
  18468. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18469. }
  18470. var worldExtends = this.getWorldExtends();
  18471. // Update octree
  18472. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18473. return this._selectionOctree;
  18474. };
  18475. // Picking
  18476. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18477. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18478. var engine = this._engine;
  18479. if (!camera) {
  18480. if (!this.activeCamera)
  18481. throw new Error("Active camera not set");
  18482. camera = this.activeCamera;
  18483. }
  18484. var cameraViewport = camera.viewport;
  18485. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18486. // Moving coordinates to local viewport world
  18487. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18488. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18489. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18490. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18491. };
  18492. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18493. var engine = this._engine;
  18494. if (!camera) {
  18495. if (!this.activeCamera)
  18496. throw new Error("Active camera not set");
  18497. camera = this.activeCamera;
  18498. }
  18499. var cameraViewport = camera.viewport;
  18500. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18501. var identity = BABYLON.Matrix.Identity();
  18502. // Moving coordinates to local viewport world
  18503. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18504. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18505. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18506. };
  18507. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18508. var pickingInfo = null;
  18509. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18510. var mesh = this.meshes[meshIndex];
  18511. if (predicate) {
  18512. if (!predicate(mesh)) {
  18513. continue;
  18514. }
  18515. }
  18516. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18517. continue;
  18518. }
  18519. var world = mesh.getWorldMatrix();
  18520. var ray = rayFunction(world);
  18521. var result = mesh.intersects(ray, fastCheck);
  18522. if (!result || !result.hit)
  18523. continue;
  18524. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18525. continue;
  18526. pickingInfo = result;
  18527. if (fastCheck) {
  18528. break;
  18529. }
  18530. }
  18531. return pickingInfo || new BABYLON.PickingInfo();
  18532. };
  18533. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18534. var pickingInfo = null;
  18535. camera = camera || this.activeCamera;
  18536. if (this.spriteManagers.length > 0) {
  18537. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18538. var spriteManager = this.spriteManagers[spriteIndex];
  18539. if (!spriteManager.isPickable) {
  18540. continue;
  18541. }
  18542. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18543. if (!result || !result.hit)
  18544. continue;
  18545. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18546. continue;
  18547. pickingInfo = result;
  18548. if (fastCheck) {
  18549. break;
  18550. }
  18551. }
  18552. }
  18553. return pickingInfo || new BABYLON.PickingInfo();
  18554. };
  18555. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18556. var _this = this;
  18557. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18558. /// <param name="x">X position on screen</param>
  18559. /// <param name="y">Y position on screen</param>
  18560. /// <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>
  18561. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18562. /// <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>
  18563. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18564. };
  18565. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18566. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18567. /// <param name="x">X position on screen</param>
  18568. /// <param name="y">Y position on screen</param>
  18569. /// <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>
  18570. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18571. /// <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>
  18572. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18573. };
  18574. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18575. var _this = this;
  18576. return this._internalPick(function (world) {
  18577. if (!_this._pickWithRayInverseMatrix) {
  18578. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18579. }
  18580. world.invertToRef(_this._pickWithRayInverseMatrix);
  18581. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18582. }, predicate, fastCheck);
  18583. };
  18584. Scene.prototype.setPointerOverMesh = function (mesh) {
  18585. if (this._pointerOverMesh === mesh) {
  18586. return;
  18587. }
  18588. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18589. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18590. }
  18591. this._pointerOverMesh = mesh;
  18592. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18593. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18594. }
  18595. };
  18596. Scene.prototype.getPointerOverMesh = function () {
  18597. return this._pointerOverMesh;
  18598. };
  18599. Scene.prototype.setPointerOverSprite = function (sprite) {
  18600. if (this._pointerOverSprite === sprite) {
  18601. return;
  18602. }
  18603. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18604. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18605. }
  18606. this._pointerOverSprite = sprite;
  18607. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18608. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18609. }
  18610. };
  18611. Scene.prototype.getPointerOverSprite = function () {
  18612. return this._pointerOverSprite;
  18613. };
  18614. // Physics
  18615. Scene.prototype.getPhysicsEngine = function () {
  18616. return this._physicsEngine;
  18617. };
  18618. /**
  18619. * Enables physics to the current scene
  18620. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18621. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18622. * @return {boolean} was the physics engine initialized
  18623. */
  18624. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18625. if (this._physicsEngine) {
  18626. return true;
  18627. }
  18628. try {
  18629. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18630. return true;
  18631. }
  18632. catch (e) {
  18633. BABYLON.Tools.Error(e.message);
  18634. return false;
  18635. }
  18636. };
  18637. Scene.prototype.disablePhysicsEngine = function () {
  18638. if (!this._physicsEngine) {
  18639. return;
  18640. }
  18641. this._physicsEngine.dispose();
  18642. this._physicsEngine = undefined;
  18643. };
  18644. Scene.prototype.isPhysicsEnabled = function () {
  18645. return this._physicsEngine !== undefined;
  18646. };
  18647. /**
  18648. *
  18649. * Sets the gravity of the physics engine (and NOT of the scene)
  18650. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  18651. */
  18652. Scene.prototype.setGravity = function (gravity) {
  18653. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  18654. if (!this._physicsEngine) {
  18655. return;
  18656. }
  18657. this._physicsEngine.setGravity(gravity);
  18658. };
  18659. /**
  18660. * Legacy support, using the new API
  18661. * @Deprecated
  18662. */
  18663. Scene.prototype.createCompoundImpostor = function (parts, options) {
  18664. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  18665. if (parts.parts) {
  18666. options = parts;
  18667. parts = parts.parts;
  18668. }
  18669. var mainMesh = parts[0].mesh;
  18670. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  18671. for (var index = 1; index < parts.length; index++) {
  18672. var mesh = parts[index].mesh;
  18673. if (mesh.parent !== mainMesh) {
  18674. mesh.position = mesh.position.subtract(mainMesh.position);
  18675. mesh.parent = mainMesh;
  18676. }
  18677. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  18678. }
  18679. mainMesh.physicsImpostor.forceUpdate();
  18680. };
  18681. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18682. var mesh = compound.parts[0].mesh;
  18683. mesh.physicsImpostor.dispose();
  18684. mesh.physicsImpostor = null;
  18685. };
  18686. // Misc.
  18687. Scene.prototype.createDefaultCameraOrLight = function () {
  18688. // Light
  18689. if (this.lights.length === 0) {
  18690. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18691. }
  18692. // Camera
  18693. if (!this.activeCamera) {
  18694. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  18695. // Compute position
  18696. var worldExtends = this.getWorldExtends();
  18697. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  18698. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  18699. camera.setTarget(worldCenter);
  18700. this.activeCamera = camera;
  18701. }
  18702. };
  18703. // Tags
  18704. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18705. if (tagsQuery === undefined) {
  18706. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18707. return list;
  18708. }
  18709. var listByTags = [];
  18710. forEach = forEach || (function (item) { return; });
  18711. for (var i in list) {
  18712. var item = list[i];
  18713. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18714. listByTags.push(item);
  18715. forEach(item);
  18716. }
  18717. }
  18718. return listByTags;
  18719. };
  18720. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18721. return this._getByTags(this.meshes, tagsQuery, forEach);
  18722. };
  18723. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18724. return this._getByTags(this.cameras, tagsQuery, forEach);
  18725. };
  18726. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18727. return this._getByTags(this.lights, tagsQuery, forEach);
  18728. };
  18729. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18730. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18731. };
  18732. /**
  18733. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18734. * This allowed control for front to back rendering or reversly depending of the special needs.
  18735. *
  18736. * @param renderingGroupId The rendering group id corresponding to its index
  18737. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18738. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18739. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18740. */
  18741. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18742. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18743. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18744. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18745. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18746. };
  18747. /**
  18748. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18749. *
  18750. * @param renderingGroupId The rendering group id corresponding to its index
  18751. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18752. */
  18753. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  18754. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  18755. };
  18756. // Statics
  18757. Scene._FOGMODE_NONE = 0;
  18758. Scene._FOGMODE_EXP = 1;
  18759. Scene._FOGMODE_EXP2 = 2;
  18760. Scene._FOGMODE_LINEAR = 3;
  18761. Scene.MinDeltaTime = 1.0;
  18762. Scene.MaxDeltaTime = 1000.0;
  18763. return Scene;
  18764. }());
  18765. BABYLON.Scene = Scene;
  18766. })(BABYLON || (BABYLON = {}));
  18767. var BABYLON;
  18768. (function (BABYLON) {
  18769. var Buffer = (function () {
  18770. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18771. if (engine instanceof BABYLON.Mesh) {
  18772. this._engine = engine.getScene().getEngine();
  18773. }
  18774. else {
  18775. this._engine = engine;
  18776. }
  18777. this._updatable = updatable;
  18778. this._data = data;
  18779. this._strideSize = stride;
  18780. if (!postponeInternalCreation) {
  18781. this.create();
  18782. }
  18783. this._instanced = instanced;
  18784. }
  18785. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18786. // a lot of these parameters are ignored as they are overriden by the buffer
  18787. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18788. };
  18789. // Properties
  18790. Buffer.prototype.isUpdatable = function () {
  18791. return this._updatable;
  18792. };
  18793. Buffer.prototype.getData = function () {
  18794. return this._data;
  18795. };
  18796. Buffer.prototype.getBuffer = function () {
  18797. return this._buffer;
  18798. };
  18799. Buffer.prototype.getStrideSize = function () {
  18800. return this._strideSize;
  18801. };
  18802. Buffer.prototype.getIsInstanced = function () {
  18803. return this._instanced;
  18804. };
  18805. // Methods
  18806. Buffer.prototype.create = function (data) {
  18807. if (!data && this._buffer) {
  18808. return; // nothing to do
  18809. }
  18810. data = data || this._data;
  18811. if (!this._buffer) {
  18812. if (this._updatable) {
  18813. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18814. this._data = data;
  18815. }
  18816. else {
  18817. this._buffer = this._engine.createVertexBuffer(data);
  18818. }
  18819. }
  18820. else if (this._updatable) {
  18821. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18822. this._data = data;
  18823. }
  18824. };
  18825. Buffer.prototype.update = function (data) {
  18826. this.create(data);
  18827. };
  18828. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18829. if (!this._buffer) {
  18830. return;
  18831. }
  18832. if (this._updatable) {
  18833. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18834. this._data = null;
  18835. }
  18836. };
  18837. Buffer.prototype.dispose = function () {
  18838. if (!this._buffer) {
  18839. return;
  18840. }
  18841. if (this._engine._releaseBuffer(this._buffer)) {
  18842. this._buffer = null;
  18843. }
  18844. };
  18845. return Buffer;
  18846. }());
  18847. BABYLON.Buffer = Buffer;
  18848. })(BABYLON || (BABYLON = {}));
  18849. var BABYLON;
  18850. (function (BABYLON) {
  18851. var VertexBuffer = (function () {
  18852. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18853. if (!stride) {
  18854. // Deduce stride from kind
  18855. switch (kind) {
  18856. case VertexBuffer.PositionKind:
  18857. stride = 3;
  18858. break;
  18859. case VertexBuffer.NormalKind:
  18860. stride = 3;
  18861. break;
  18862. case VertexBuffer.UVKind:
  18863. case VertexBuffer.UV2Kind:
  18864. case VertexBuffer.UV3Kind:
  18865. case VertexBuffer.UV4Kind:
  18866. case VertexBuffer.UV5Kind:
  18867. case VertexBuffer.UV6Kind:
  18868. stride = 2;
  18869. break;
  18870. case VertexBuffer.ColorKind:
  18871. stride = 4;
  18872. break;
  18873. case VertexBuffer.MatricesIndicesKind:
  18874. case VertexBuffer.MatricesIndicesExtraKind:
  18875. stride = 4;
  18876. break;
  18877. case VertexBuffer.MatricesWeightsKind:
  18878. case VertexBuffer.MatricesWeightsExtraKind:
  18879. stride = 4;
  18880. break;
  18881. }
  18882. }
  18883. if (data instanceof BABYLON.Buffer) {
  18884. if (!stride) {
  18885. stride = data.getStrideSize();
  18886. }
  18887. this._buffer = data;
  18888. this._ownsBuffer = false;
  18889. }
  18890. else {
  18891. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18892. this._ownsBuffer = true;
  18893. }
  18894. this._stride = stride;
  18895. this._offset = offset ? offset : 0;
  18896. this._size = size ? size : stride;
  18897. this._kind = kind;
  18898. }
  18899. VertexBuffer.prototype.getKind = function () {
  18900. return this._kind;
  18901. };
  18902. // Properties
  18903. VertexBuffer.prototype.isUpdatable = function () {
  18904. return this._buffer.isUpdatable();
  18905. };
  18906. VertexBuffer.prototype.getData = function () {
  18907. return this._buffer.getData();
  18908. };
  18909. VertexBuffer.prototype.getBuffer = function () {
  18910. return this._buffer.getBuffer();
  18911. };
  18912. VertexBuffer.prototype.getStrideSize = function () {
  18913. return this._stride;
  18914. };
  18915. VertexBuffer.prototype.getOffset = function () {
  18916. return this._offset;
  18917. };
  18918. VertexBuffer.prototype.getSize = function () {
  18919. return this._size;
  18920. };
  18921. VertexBuffer.prototype.getIsInstanced = function () {
  18922. return this._buffer.getIsInstanced();
  18923. };
  18924. // Methods
  18925. VertexBuffer.prototype.create = function (data) {
  18926. return this._buffer.create(data);
  18927. };
  18928. VertexBuffer.prototype.update = function (data) {
  18929. return this._buffer.update(data);
  18930. };
  18931. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18932. return this._buffer.updateDirectly(data, offset);
  18933. };
  18934. VertexBuffer.prototype.dispose = function () {
  18935. if (this._ownsBuffer) {
  18936. this._buffer.dispose();
  18937. }
  18938. };
  18939. Object.defineProperty(VertexBuffer, "PositionKind", {
  18940. get: function () {
  18941. return VertexBuffer._PositionKind;
  18942. },
  18943. enumerable: true,
  18944. configurable: true
  18945. });
  18946. Object.defineProperty(VertexBuffer, "NormalKind", {
  18947. get: function () {
  18948. return VertexBuffer._NormalKind;
  18949. },
  18950. enumerable: true,
  18951. configurable: true
  18952. });
  18953. Object.defineProperty(VertexBuffer, "UVKind", {
  18954. get: function () {
  18955. return VertexBuffer._UVKind;
  18956. },
  18957. enumerable: true,
  18958. configurable: true
  18959. });
  18960. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18961. get: function () {
  18962. return VertexBuffer._UV2Kind;
  18963. },
  18964. enumerable: true,
  18965. configurable: true
  18966. });
  18967. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18968. get: function () {
  18969. return VertexBuffer._UV3Kind;
  18970. },
  18971. enumerable: true,
  18972. configurable: true
  18973. });
  18974. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18975. get: function () {
  18976. return VertexBuffer._UV4Kind;
  18977. },
  18978. enumerable: true,
  18979. configurable: true
  18980. });
  18981. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18982. get: function () {
  18983. return VertexBuffer._UV5Kind;
  18984. },
  18985. enumerable: true,
  18986. configurable: true
  18987. });
  18988. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18989. get: function () {
  18990. return VertexBuffer._UV6Kind;
  18991. },
  18992. enumerable: true,
  18993. configurable: true
  18994. });
  18995. Object.defineProperty(VertexBuffer, "ColorKind", {
  18996. get: function () {
  18997. return VertexBuffer._ColorKind;
  18998. },
  18999. enumerable: true,
  19000. configurable: true
  19001. });
  19002. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  19003. get: function () {
  19004. return VertexBuffer._MatricesIndicesKind;
  19005. },
  19006. enumerable: true,
  19007. configurable: true
  19008. });
  19009. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  19010. get: function () {
  19011. return VertexBuffer._MatricesWeightsKind;
  19012. },
  19013. enumerable: true,
  19014. configurable: true
  19015. });
  19016. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  19017. get: function () {
  19018. return VertexBuffer._MatricesIndicesExtraKind;
  19019. },
  19020. enumerable: true,
  19021. configurable: true
  19022. });
  19023. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  19024. get: function () {
  19025. return VertexBuffer._MatricesWeightsExtraKind;
  19026. },
  19027. enumerable: true,
  19028. configurable: true
  19029. });
  19030. // Enums
  19031. VertexBuffer._PositionKind = "position";
  19032. VertexBuffer._NormalKind = "normal";
  19033. VertexBuffer._UVKind = "uv";
  19034. VertexBuffer._UV2Kind = "uv2";
  19035. VertexBuffer._UV3Kind = "uv3";
  19036. VertexBuffer._UV4Kind = "uv4";
  19037. VertexBuffer._UV5Kind = "uv5";
  19038. VertexBuffer._UV6Kind = "uv6";
  19039. VertexBuffer._ColorKind = "color";
  19040. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  19041. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  19042. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  19043. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  19044. return VertexBuffer;
  19045. }());
  19046. BABYLON.VertexBuffer = VertexBuffer;
  19047. })(BABYLON || (BABYLON = {}));
  19048. var BABYLON;
  19049. (function (BABYLON) {
  19050. /**
  19051. * Creates an instance based on a source mesh.
  19052. */
  19053. var InstancedMesh = (function (_super) {
  19054. __extends(InstancedMesh, _super);
  19055. function InstancedMesh(name, source) {
  19056. _super.call(this, name, source.getScene());
  19057. source.instances.push(this);
  19058. this._sourceMesh = source;
  19059. this.position.copyFrom(source.position);
  19060. this.rotation.copyFrom(source.rotation);
  19061. this.scaling.copyFrom(source.scaling);
  19062. if (source.rotationQuaternion) {
  19063. this.rotationQuaternion = source.rotationQuaternion.clone();
  19064. }
  19065. this.infiniteDistance = source.infiniteDistance;
  19066. this.setPivotMatrix(source.getPivotMatrix());
  19067. this.refreshBoundingInfo();
  19068. this._syncSubMeshes();
  19069. }
  19070. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  19071. // Methods
  19072. get: function () {
  19073. return this._sourceMesh.receiveShadows;
  19074. },
  19075. enumerable: true,
  19076. configurable: true
  19077. });
  19078. Object.defineProperty(InstancedMesh.prototype, "material", {
  19079. get: function () {
  19080. return this._sourceMesh.material;
  19081. },
  19082. enumerable: true,
  19083. configurable: true
  19084. });
  19085. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  19086. get: function () {
  19087. return this._sourceMesh.visibility;
  19088. },
  19089. enumerable: true,
  19090. configurable: true
  19091. });
  19092. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  19093. get: function () {
  19094. return this._sourceMesh.skeleton;
  19095. },
  19096. enumerable: true,
  19097. configurable: true
  19098. });
  19099. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  19100. get: function () {
  19101. return this._sourceMesh.renderingGroupId;
  19102. },
  19103. enumerable: true,
  19104. configurable: true
  19105. });
  19106. InstancedMesh.prototype.getTotalVertices = function () {
  19107. return this._sourceMesh.getTotalVertices();
  19108. };
  19109. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  19110. get: function () {
  19111. return this._sourceMesh;
  19112. },
  19113. enumerable: true,
  19114. configurable: true
  19115. });
  19116. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19117. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  19118. };
  19119. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  19120. return this._sourceMesh.isVerticesDataPresent(kind);
  19121. };
  19122. InstancedMesh.prototype.getIndices = function () {
  19123. return this._sourceMesh.getIndices();
  19124. };
  19125. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  19126. get: function () {
  19127. return this._sourceMesh._positions;
  19128. },
  19129. enumerable: true,
  19130. configurable: true
  19131. });
  19132. InstancedMesh.prototype.refreshBoundingInfo = function () {
  19133. var meshBB = this._sourceMesh.getBoundingInfo();
  19134. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  19135. this._updateBoundingInfo();
  19136. };
  19137. InstancedMesh.prototype._preActivate = function () {
  19138. if (this._currentLOD) {
  19139. this._currentLOD._preActivate();
  19140. }
  19141. };
  19142. InstancedMesh.prototype._activate = function (renderId) {
  19143. if (this._currentLOD) {
  19144. this._currentLOD._registerInstanceForRenderId(this, renderId);
  19145. }
  19146. };
  19147. InstancedMesh.prototype.getLOD = function (camera) {
  19148. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  19149. if (this._currentLOD === this.sourceMesh) {
  19150. return this;
  19151. }
  19152. return this._currentLOD;
  19153. };
  19154. InstancedMesh.prototype._syncSubMeshes = function () {
  19155. this.releaseSubMeshes();
  19156. if (this._sourceMesh.subMeshes) {
  19157. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  19158. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  19159. }
  19160. }
  19161. };
  19162. InstancedMesh.prototype._generatePointsArray = function () {
  19163. return this._sourceMesh._generatePointsArray();
  19164. };
  19165. // Clone
  19166. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19167. var result = this._sourceMesh.createInstance(name);
  19168. // Deep copy
  19169. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  19170. // Bounding info
  19171. this.refreshBoundingInfo();
  19172. // Parent
  19173. if (newParent) {
  19174. result.parent = newParent;
  19175. }
  19176. if (!doNotCloneChildren) {
  19177. // Children
  19178. for (var index = 0; index < this.getScene().meshes.length; index++) {
  19179. var mesh = this.getScene().meshes[index];
  19180. if (mesh.parent === this) {
  19181. mesh.clone(mesh.name, result);
  19182. }
  19183. }
  19184. }
  19185. result.computeWorldMatrix(true);
  19186. return result;
  19187. };
  19188. // Dispoe
  19189. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  19190. // Remove from mesh
  19191. var index = this._sourceMesh.instances.indexOf(this);
  19192. this._sourceMesh.instances.splice(index, 1);
  19193. _super.prototype.dispose.call(this, doNotRecurse);
  19194. };
  19195. return InstancedMesh;
  19196. }(BABYLON.AbstractMesh));
  19197. BABYLON.InstancedMesh = InstancedMesh;
  19198. })(BABYLON || (BABYLON = {}));
  19199. var BABYLON;
  19200. (function (BABYLON) {
  19201. var _InstancesBatch = (function () {
  19202. function _InstancesBatch() {
  19203. this.mustReturn = false;
  19204. this.visibleInstances = new Array();
  19205. this.renderSelf = new Array();
  19206. }
  19207. return _InstancesBatch;
  19208. }());
  19209. BABYLON._InstancesBatch = _InstancesBatch;
  19210. var Mesh = (function (_super) {
  19211. __extends(Mesh, _super);
  19212. /**
  19213. * @constructor
  19214. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19215. * @param {Scene} scene The scene to add this mesh to.
  19216. * @param {Node} parent The parent of this mesh, if it has one
  19217. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19218. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19219. * When false, achieved by calling a clone(), also passing False.
  19220. * This will make creation of children, recursive.
  19221. */
  19222. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19223. if (parent === void 0) { parent = null; }
  19224. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19225. _super.call(this, name, scene);
  19226. // Events
  19227. /**
  19228. * An event triggered before rendering the mesh
  19229. * @type {BABYLON.Observable}
  19230. */
  19231. this.onBeforeRenderObservable = new BABYLON.Observable();
  19232. /**
  19233. * An event triggered after rendering the mesh
  19234. * @type {BABYLON.Observable}
  19235. */
  19236. this.onAfterRenderObservable = new BABYLON.Observable();
  19237. /**
  19238. * An event triggered before drawing the mesh
  19239. * @type {BABYLON.Observable}
  19240. */
  19241. this.onBeforeDrawObservable = new BABYLON.Observable();
  19242. // Members
  19243. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19244. this.instances = new Array();
  19245. this._LODLevels = new Array();
  19246. this._visibleInstances = {};
  19247. this._renderIdForInstances = new Array();
  19248. this._batchCache = new _InstancesBatch();
  19249. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19250. this._sideOrientation = Mesh._DEFAULTSIDE;
  19251. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19252. if (source) {
  19253. // Geometry
  19254. if (source._geometry) {
  19255. source._geometry.applyToMesh(this);
  19256. }
  19257. // Deep copy
  19258. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  19259. // Pivot
  19260. this.setPivotMatrix(source.getPivotMatrix());
  19261. this.id = name + "." + source.id;
  19262. // Material
  19263. this.material = source.material;
  19264. var index;
  19265. if (!doNotCloneChildren) {
  19266. // Children
  19267. for (index = 0; index < scene.meshes.length; index++) {
  19268. var mesh = scene.meshes[index];
  19269. if (mesh.parent === source) {
  19270. // doNotCloneChildren is always going to be False
  19271. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  19272. }
  19273. }
  19274. }
  19275. // Physics clone
  19276. var physicsEngine = this.getScene().getPhysicsEngine();
  19277. if (clonePhysicsImpostor && physicsEngine) {
  19278. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19279. if (impostor) {
  19280. this.physicsImpostor = impostor.clone(this);
  19281. }
  19282. }
  19283. // Particles
  19284. for (index = 0; index < scene.particleSystems.length; index++) {
  19285. var system = scene.particleSystems[index];
  19286. if (system.emitter === source) {
  19287. system.clone(system.name, this);
  19288. }
  19289. }
  19290. this.computeWorldMatrix(true);
  19291. }
  19292. // Parent
  19293. if (parent !== null) {
  19294. this.parent = parent;
  19295. }
  19296. }
  19297. Object.defineProperty(Mesh, "FRONTSIDE", {
  19298. /**
  19299. * Mesh side orientation : usually the external or front surface
  19300. */
  19301. get: function () {
  19302. return Mesh._FRONTSIDE;
  19303. },
  19304. enumerable: true,
  19305. configurable: true
  19306. });
  19307. Object.defineProperty(Mesh, "BACKSIDE", {
  19308. /**
  19309. * Mesh side orientation : usually the internal or back surface
  19310. */
  19311. get: function () {
  19312. return Mesh._BACKSIDE;
  19313. },
  19314. enumerable: true,
  19315. configurable: true
  19316. });
  19317. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19318. /**
  19319. * Mesh side orientation : both internal and external or front and back surfaces
  19320. */
  19321. get: function () {
  19322. return Mesh._DOUBLESIDE;
  19323. },
  19324. enumerable: true,
  19325. configurable: true
  19326. });
  19327. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19328. /**
  19329. * Mesh side orientation : by default, `FRONTSIDE`
  19330. */
  19331. get: function () {
  19332. return Mesh._DEFAULTSIDE;
  19333. },
  19334. enumerable: true,
  19335. configurable: true
  19336. });
  19337. Object.defineProperty(Mesh, "NO_CAP", {
  19338. /**
  19339. * Mesh cap setting : no cap
  19340. */
  19341. get: function () {
  19342. return Mesh._NO_CAP;
  19343. },
  19344. enumerable: true,
  19345. configurable: true
  19346. });
  19347. Object.defineProperty(Mesh, "CAP_START", {
  19348. /**
  19349. * Mesh cap setting : one cap at the beginning of the mesh
  19350. */
  19351. get: function () {
  19352. return Mesh._CAP_START;
  19353. },
  19354. enumerable: true,
  19355. configurable: true
  19356. });
  19357. Object.defineProperty(Mesh, "CAP_END", {
  19358. /**
  19359. * Mesh cap setting : one cap at the end of the mesh
  19360. */
  19361. get: function () {
  19362. return Mesh._CAP_END;
  19363. },
  19364. enumerable: true,
  19365. configurable: true
  19366. });
  19367. Object.defineProperty(Mesh, "CAP_ALL", {
  19368. /**
  19369. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19370. */
  19371. get: function () {
  19372. return Mesh._CAP_ALL;
  19373. },
  19374. enumerable: true,
  19375. configurable: true
  19376. });
  19377. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19378. set: function (callback) {
  19379. if (this._onBeforeDrawObserver) {
  19380. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19381. }
  19382. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19383. },
  19384. enumerable: true,
  19385. configurable: true
  19386. });
  19387. // Methods
  19388. /**
  19389. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19390. */
  19391. Mesh.prototype.toString = function (fullDetails) {
  19392. var ret = _super.prototype.toString.call(this, fullDetails);
  19393. ret += ", n vertices: " + this.getTotalVertices();
  19394. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19395. if (this.animations) {
  19396. for (var i = 0; i < this.animations.length; i++) {
  19397. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19398. }
  19399. }
  19400. if (fullDetails) {
  19401. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19402. }
  19403. return ret;
  19404. };
  19405. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19406. get: function () {
  19407. return this._LODLevels.length > 0;
  19408. },
  19409. enumerable: true,
  19410. configurable: true
  19411. });
  19412. Mesh.prototype._sortLODLevels = function () {
  19413. this._LODLevels.sort(function (a, b) {
  19414. if (a.distance < b.distance) {
  19415. return 1;
  19416. }
  19417. if (a.distance > b.distance) {
  19418. return -1;
  19419. }
  19420. return 0;
  19421. });
  19422. };
  19423. /**
  19424. * Add a mesh as LOD level triggered at the given distance.
  19425. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19426. * @param {number} distance The distance from the center of the object to show this level
  19427. * @param {Mesh} mesh The mesh to be added as LOD level
  19428. * @return {Mesh} This mesh (for chaining)
  19429. */
  19430. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19431. if (mesh && mesh._masterMesh) {
  19432. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19433. return this;
  19434. }
  19435. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19436. this._LODLevels.push(level);
  19437. if (mesh) {
  19438. mesh._masterMesh = this;
  19439. }
  19440. this._sortLODLevels();
  19441. return this;
  19442. };
  19443. /**
  19444. * Returns the LOD level mesh at the passed distance or null if not found.
  19445. * It is related to the method `addLODLevel(distance, mesh)`.
  19446. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19447. */
  19448. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19449. for (var index = 0; index < this._LODLevels.length; index++) {
  19450. var level = this._LODLevels[index];
  19451. if (level.distance === distance) {
  19452. return level.mesh;
  19453. }
  19454. }
  19455. return null;
  19456. };
  19457. /**
  19458. * Remove a mesh from the LOD array
  19459. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19460. * @param {Mesh} mesh The mesh to be removed.
  19461. * @return {Mesh} This mesh (for chaining)
  19462. */
  19463. Mesh.prototype.removeLODLevel = function (mesh) {
  19464. for (var index = 0; index < this._LODLevels.length; index++) {
  19465. if (this._LODLevels[index].mesh === mesh) {
  19466. this._LODLevels.splice(index, 1);
  19467. if (mesh) {
  19468. mesh._masterMesh = null;
  19469. }
  19470. }
  19471. }
  19472. this._sortLODLevels();
  19473. return this;
  19474. };
  19475. /**
  19476. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19477. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19478. */
  19479. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19480. if (!this._LODLevels || this._LODLevels.length === 0) {
  19481. return this;
  19482. }
  19483. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19484. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19485. if (this.onLODLevelSelection) {
  19486. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19487. }
  19488. return this;
  19489. }
  19490. for (var index = 0; index < this._LODLevels.length; index++) {
  19491. var level = this._LODLevels[index];
  19492. if (level.distance < distanceToCamera) {
  19493. if (level.mesh) {
  19494. level.mesh._preActivate();
  19495. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19496. }
  19497. if (this.onLODLevelSelection) {
  19498. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19499. }
  19500. return level.mesh;
  19501. }
  19502. }
  19503. if (this.onLODLevelSelection) {
  19504. this.onLODLevelSelection(distanceToCamera, this, this);
  19505. }
  19506. return this;
  19507. };
  19508. Object.defineProperty(Mesh.prototype, "geometry", {
  19509. /**
  19510. * Returns the mesh internal Geometry object.
  19511. */
  19512. get: function () {
  19513. return this._geometry;
  19514. },
  19515. enumerable: true,
  19516. configurable: true
  19517. });
  19518. /**
  19519. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19520. */
  19521. Mesh.prototype.getTotalVertices = function () {
  19522. if (!this._geometry) {
  19523. return 0;
  19524. }
  19525. return this._geometry.getTotalVertices();
  19526. };
  19527. /**
  19528. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19529. * 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.
  19530. * Returns null if the mesh has no geometry or no vertex buffer.
  19531. * Possible `kind` values :
  19532. * - BABYLON.VertexBuffer.PositionKind
  19533. * - BABYLON.VertexBuffer.UVKind
  19534. * - BABYLON.VertexBuffer.UV2Kind
  19535. * - BABYLON.VertexBuffer.UV3Kind
  19536. * - BABYLON.VertexBuffer.UV4Kind
  19537. * - BABYLON.VertexBuffer.UV5Kind
  19538. * - BABYLON.VertexBuffer.UV6Kind
  19539. * - BABYLON.VertexBuffer.ColorKind
  19540. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19541. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19542. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19543. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19544. */
  19545. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19546. if (!this._geometry) {
  19547. return null;
  19548. }
  19549. return this._geometry.getVerticesData(kind, copyWhenShared);
  19550. };
  19551. /**
  19552. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19553. * Returns `undefined` if the mesh has no geometry.
  19554. * Possible `kind` values :
  19555. * - BABYLON.VertexBuffer.PositionKind
  19556. * - BABYLON.VertexBuffer.UVKind
  19557. * - BABYLON.VertexBuffer.UV2Kind
  19558. * - BABYLON.VertexBuffer.UV3Kind
  19559. * - BABYLON.VertexBuffer.UV4Kind
  19560. * - BABYLON.VertexBuffer.UV5Kind
  19561. * - BABYLON.VertexBuffer.UV6Kind
  19562. * - BABYLON.VertexBuffer.ColorKind
  19563. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19564. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19565. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19566. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19567. */
  19568. Mesh.prototype.getVertexBuffer = function (kind) {
  19569. if (!this._geometry) {
  19570. return undefined;
  19571. }
  19572. return this._geometry.getVertexBuffer(kind);
  19573. };
  19574. /**
  19575. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19576. * Possible `kind` values :
  19577. * - BABYLON.VertexBuffer.PositionKind
  19578. * - BABYLON.VertexBuffer.UVKind
  19579. * - BABYLON.VertexBuffer.UV2Kind
  19580. * - BABYLON.VertexBuffer.UV3Kind
  19581. * - BABYLON.VertexBuffer.UV4Kind
  19582. * - BABYLON.VertexBuffer.UV5Kind
  19583. * - BABYLON.VertexBuffer.UV6Kind
  19584. * - BABYLON.VertexBuffer.ColorKind
  19585. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19586. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19587. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19588. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19589. */
  19590. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19591. if (!this._geometry) {
  19592. if (this._delayInfo) {
  19593. return this._delayInfo.indexOf(kind) !== -1;
  19594. }
  19595. return false;
  19596. }
  19597. return this._geometry.isVerticesDataPresent(kind);
  19598. };
  19599. /**
  19600. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19601. * Possible `kind` values :
  19602. * - BABYLON.VertexBuffer.PositionKind
  19603. * - BABYLON.VertexBuffer.UVKind
  19604. * - BABYLON.VertexBuffer.UV2Kind
  19605. * - BABYLON.VertexBuffer.UV3Kind
  19606. * - BABYLON.VertexBuffer.UV4Kind
  19607. * - BABYLON.VertexBuffer.UV5Kind
  19608. * - BABYLON.VertexBuffer.UV6Kind
  19609. * - BABYLON.VertexBuffer.ColorKind
  19610. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19611. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19612. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19613. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19614. */
  19615. Mesh.prototype.getVerticesDataKinds = function () {
  19616. if (!this._geometry) {
  19617. var result = [];
  19618. if (this._delayInfo) {
  19619. this._delayInfo.forEach(function (kind, index, array) {
  19620. result.push(kind);
  19621. });
  19622. }
  19623. return result;
  19624. }
  19625. return this._geometry.getVerticesDataKinds();
  19626. };
  19627. /**
  19628. * Returns a positive integer : the total number of indices in this mesh geometry.
  19629. * Returns zero if the mesh has no geometry.
  19630. */
  19631. Mesh.prototype.getTotalIndices = function () {
  19632. if (!this._geometry) {
  19633. return 0;
  19634. }
  19635. return this._geometry.getTotalIndices();
  19636. };
  19637. /**
  19638. * Returns an array of integers or a Int32Array populated with the mesh indices.
  19639. * 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.
  19640. * Returns an empty array if the mesh has no geometry.
  19641. */
  19642. Mesh.prototype.getIndices = function (copyWhenShared) {
  19643. if (!this._geometry) {
  19644. return [];
  19645. }
  19646. return this._geometry.getIndices(copyWhenShared);
  19647. };
  19648. Object.defineProperty(Mesh.prototype, "isBlocked", {
  19649. get: function () {
  19650. return this._masterMesh !== null && this._masterMesh !== undefined;
  19651. },
  19652. enumerable: true,
  19653. configurable: true
  19654. });
  19655. /**
  19656. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  19657. */
  19658. Mesh.prototype.isReady = function () {
  19659. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19660. return false;
  19661. }
  19662. return _super.prototype.isReady.call(this);
  19663. };
  19664. /**
  19665. * Boolean : true if the mesh has been disposed.
  19666. */
  19667. Mesh.prototype.isDisposed = function () {
  19668. return this._isDisposed;
  19669. };
  19670. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  19671. get: function () {
  19672. return this._sideOrientation;
  19673. },
  19674. /**
  19675. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  19676. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  19677. */
  19678. set: function (sideO) {
  19679. this._sideOrientation = sideO;
  19680. },
  19681. enumerable: true,
  19682. configurable: true
  19683. });
  19684. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  19685. /**
  19686. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  19687. * This property is pertinent only for updatable parametric shapes.
  19688. */
  19689. get: function () {
  19690. return this._areNormalsFrozen;
  19691. },
  19692. enumerable: true,
  19693. configurable: true
  19694. });
  19695. /**
  19696. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19697. * It has no effect at all on other shapes.
  19698. * It prevents the mesh normals from being recomputed on next `positions` array update.
  19699. */
  19700. Mesh.prototype.freezeNormals = function () {
  19701. this._areNormalsFrozen = true;
  19702. };
  19703. /**
  19704. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19705. * It has no effect at all on other shapes.
  19706. * It reactivates the mesh normals computation if it was previously frozen.
  19707. */
  19708. Mesh.prototype.unfreezeNormals = function () {
  19709. this._areNormalsFrozen = false;
  19710. };
  19711. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  19712. /**
  19713. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  19714. */
  19715. set: function (count) {
  19716. this._overridenInstanceCount = count;
  19717. },
  19718. enumerable: true,
  19719. configurable: true
  19720. });
  19721. // Methods
  19722. Mesh.prototype._preActivate = function () {
  19723. var sceneRenderId = this.getScene().getRenderId();
  19724. if (this._preActivateId === sceneRenderId) {
  19725. return;
  19726. }
  19727. this._preActivateId = sceneRenderId;
  19728. this._visibleInstances = null;
  19729. };
  19730. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19731. if (this._visibleInstances) {
  19732. this._visibleInstances.intermediateDefaultRenderId = renderId;
  19733. }
  19734. };
  19735. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19736. if (!this._visibleInstances) {
  19737. this._visibleInstances = {};
  19738. this._visibleInstances.defaultRenderId = renderId;
  19739. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19740. }
  19741. if (!this._visibleInstances[renderId]) {
  19742. this._visibleInstances[renderId] = new Array();
  19743. }
  19744. this._visibleInstances[renderId].push(instance);
  19745. };
  19746. /**
  19747. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19748. * This means the mesh underlying bounding box and sphere are recomputed.
  19749. */
  19750. Mesh.prototype.refreshBoundingInfo = function () {
  19751. if (this._boundingInfo.isLocked) {
  19752. return;
  19753. }
  19754. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19755. if (data) {
  19756. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19757. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19758. }
  19759. if (this.subMeshes) {
  19760. for (var index = 0; index < this.subMeshes.length; index++) {
  19761. this.subMeshes[index].refreshBoundingInfo();
  19762. }
  19763. }
  19764. this._updateBoundingInfo();
  19765. };
  19766. Mesh.prototype._createGlobalSubMesh = function () {
  19767. var totalVertices = this.getTotalVertices();
  19768. if (!totalVertices || !this.getIndices()) {
  19769. return null;
  19770. }
  19771. this.releaseSubMeshes();
  19772. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  19773. };
  19774. Mesh.prototype.subdivide = function (count) {
  19775. if (count < 1) {
  19776. return;
  19777. }
  19778. var totalIndices = this.getTotalIndices();
  19779. var subdivisionSize = (totalIndices / count) | 0;
  19780. var offset = 0;
  19781. // Ensure that subdivisionSize is a multiple of 3
  19782. while (subdivisionSize % 3 !== 0) {
  19783. subdivisionSize++;
  19784. }
  19785. this.releaseSubMeshes();
  19786. for (var index = 0; index < count; index++) {
  19787. if (offset >= totalIndices) {
  19788. break;
  19789. }
  19790. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  19791. offset += subdivisionSize;
  19792. }
  19793. this.synchronizeInstances();
  19794. };
  19795. /**
  19796. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19797. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19798. * The `data` are either a numeric array either a Float32Array.
  19799. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19800. * 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).
  19801. * Note that a new underlying VertexBuffer object is created each call.
  19802. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19803. *
  19804. * Possible `kind` values :
  19805. * - BABYLON.VertexBuffer.PositionKind
  19806. * - BABYLON.VertexBuffer.UVKind
  19807. * - BABYLON.VertexBuffer.UV2Kind
  19808. * - BABYLON.VertexBuffer.UV3Kind
  19809. * - BABYLON.VertexBuffer.UV4Kind
  19810. * - BABYLON.VertexBuffer.UV5Kind
  19811. * - BABYLON.VertexBuffer.UV6Kind
  19812. * - BABYLON.VertexBuffer.ColorKind
  19813. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19814. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19815. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19816. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19817. */
  19818. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19819. if (!this._geometry) {
  19820. var vertexData = new BABYLON.VertexData();
  19821. vertexData.set(data, kind);
  19822. var scene = this.getScene();
  19823. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  19824. }
  19825. else {
  19826. this._geometry.setVerticesData(kind, data, updatable, stride);
  19827. }
  19828. };
  19829. Mesh.prototype.setVerticesBuffer = function (buffer) {
  19830. if (!this._geometry) {
  19831. var scene = this.getScene();
  19832. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  19833. }
  19834. this._geometry.setVerticesBuffer(buffer);
  19835. };
  19836. /**
  19837. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19838. * If the mesh has no geometry, it is simply returned as it is.
  19839. * The `data` are either a numeric array either a Float32Array.
  19840. * No new underlying VertexBuffer object is created.
  19841. * 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.
  19842. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19843. *
  19844. * Possible `kind` values :
  19845. * - BABYLON.VertexBuffer.PositionKind
  19846. * - BABYLON.VertexBuffer.UVKind
  19847. * - BABYLON.VertexBuffer.UV2Kind
  19848. * - BABYLON.VertexBuffer.UV3Kind
  19849. * - BABYLON.VertexBuffer.UV4Kind
  19850. * - BABYLON.VertexBuffer.UV5Kind
  19851. * - BABYLON.VertexBuffer.UV6Kind
  19852. * - BABYLON.VertexBuffer.ColorKind
  19853. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19854. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19855. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19856. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19857. */
  19858. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19859. if (!this._geometry) {
  19860. return;
  19861. }
  19862. if (!makeItUnique) {
  19863. this._geometry.updateVerticesData(kind, data, updateExtends);
  19864. }
  19865. else {
  19866. this.makeGeometryUnique();
  19867. this.updateVerticesData(kind, data, updateExtends, false);
  19868. }
  19869. };
  19870. /**
  19871. * Deprecated since BabylonJS v2.3
  19872. */
  19873. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  19874. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  19875. if (!this._geometry) {
  19876. return;
  19877. }
  19878. if (!makeItUnique) {
  19879. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  19880. }
  19881. else {
  19882. this.makeGeometryUnique();
  19883. this.updateVerticesDataDirectly(kind, data, offset, false);
  19884. }
  19885. };
  19886. /**
  19887. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  19888. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  19889. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  19890. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  19891. */
  19892. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  19893. if (computeNormals === void 0) { computeNormals = true; }
  19894. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19895. positionFunction(positions);
  19896. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19897. if (computeNormals) {
  19898. var indices = this.getIndices();
  19899. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19900. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19901. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19902. }
  19903. };
  19904. Mesh.prototype.makeGeometryUnique = function () {
  19905. if (!this._geometry) {
  19906. return;
  19907. }
  19908. var oldGeometry = this._geometry;
  19909. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  19910. oldGeometry.releaseForMesh(this, true);
  19911. geometry.applyToMesh(this);
  19912. };
  19913. /**
  19914. * Sets the mesh indices.
  19915. * Expects an array populated with integers or a Int32Array.
  19916. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19917. * This method creates a new index buffer each call.
  19918. */
  19919. Mesh.prototype.setIndices = function (indices, totalVertices) {
  19920. if (!this._geometry) {
  19921. var vertexData = new BABYLON.VertexData();
  19922. vertexData.indices = indices;
  19923. var scene = this.getScene();
  19924. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  19925. }
  19926. else {
  19927. this._geometry.setIndices(indices, totalVertices);
  19928. }
  19929. };
  19930. /**
  19931. * Invert the geometry to move from a right handed system to a left handed one.
  19932. */
  19933. Mesh.prototype.toLeftHanded = function () {
  19934. if (!this._geometry) {
  19935. return;
  19936. }
  19937. this._geometry.toLeftHanded();
  19938. };
  19939. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  19940. var engine = this.getScene().getEngine();
  19941. // Wireframe
  19942. var indexToBind;
  19943. if (this._unIndexed) {
  19944. indexToBind = null;
  19945. }
  19946. else {
  19947. switch (fillMode) {
  19948. case BABYLON.Material.PointFillMode:
  19949. indexToBind = null;
  19950. break;
  19951. case BABYLON.Material.WireFrameFillMode:
  19952. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  19953. break;
  19954. default:
  19955. case BABYLON.Material.TriangleFillMode:
  19956. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  19957. break;
  19958. }
  19959. }
  19960. // VBOs
  19961. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  19962. };
  19963. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  19964. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19965. return;
  19966. }
  19967. this.onBeforeDrawObservable.notifyObservers(this);
  19968. var engine = this.getScene().getEngine();
  19969. // Draw order
  19970. switch (fillMode) {
  19971. case BABYLON.Material.PointFillMode:
  19972. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19973. break;
  19974. case BABYLON.Material.WireFrameFillMode:
  19975. if (this._unIndexed) {
  19976. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19977. }
  19978. else {
  19979. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  19980. }
  19981. break;
  19982. default:
  19983. if (this._unIndexed) {
  19984. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19985. }
  19986. else {
  19987. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  19988. }
  19989. }
  19990. };
  19991. /**
  19992. * Registers for this mesh a javascript function called just before the rendering process.
  19993. * This function is passed the current mesh and doesn't return anything.
  19994. */
  19995. Mesh.prototype.registerBeforeRender = function (func) {
  19996. this.onBeforeRenderObservable.add(func);
  19997. };
  19998. /**
  19999. * Disposes a previously registered javascript function called before the rendering.
  20000. * This function is passed the current mesh and doesn't return anything.
  20001. */
  20002. Mesh.prototype.unregisterBeforeRender = function (func) {
  20003. this.onBeforeRenderObservable.removeCallback(func);
  20004. };
  20005. /**
  20006. * Registers for this mesh a javascript function called just after the rendering is complete.
  20007. * This function is passed the current mesh and doesn't return anything.
  20008. */
  20009. Mesh.prototype.registerAfterRender = function (func) {
  20010. this.onAfterRenderObservable.add(func);
  20011. };
  20012. /**
  20013. * Disposes a previously registered javascript function called after the rendering.
  20014. * This function is passed the current mesh and doesn't return anything.
  20015. */
  20016. Mesh.prototype.unregisterAfterRender = function (func) {
  20017. this.onAfterRenderObservable.removeCallback(func);
  20018. };
  20019. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20020. var scene = this.getScene();
  20021. this._batchCache.mustReturn = false;
  20022. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20023. this._batchCache.visibleInstances[subMeshId] = null;
  20024. if (this._visibleInstances) {
  20025. var currentRenderId = scene.getRenderId();
  20026. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20027. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20028. var selfRenderId = this._renderId;
  20029. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20030. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20031. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20032. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20033. }
  20034. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20035. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20036. this._batchCache.mustReturn = true;
  20037. return this._batchCache;
  20038. }
  20039. if (currentRenderId !== selfRenderId) {
  20040. this._batchCache.renderSelf[subMeshId] = false;
  20041. }
  20042. }
  20043. this._renderIdForInstances[subMeshId] = currentRenderId;
  20044. }
  20045. return this._batchCache;
  20046. };
  20047. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20048. var visibleInstances = batch.visibleInstances[subMesh._id];
  20049. var matricesCount = visibleInstances.length + 1;
  20050. var bufferSize = matricesCount * 16 * 4;
  20051. var currentInstancesBufferSize = this._instancesBufferSize;
  20052. var instancesBuffer = this._instancesBuffer;
  20053. while (this._instancesBufferSize < bufferSize) {
  20054. this._instancesBufferSize *= 2;
  20055. }
  20056. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20057. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20058. }
  20059. var offset = 0;
  20060. var instancesCount = 0;
  20061. var world = this.getWorldMatrix();
  20062. if (batch.renderSelf[subMesh._id]) {
  20063. world.copyToArray(this._instancesData, offset);
  20064. offset += 16;
  20065. instancesCount++;
  20066. }
  20067. if (visibleInstances) {
  20068. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20069. var instance = visibleInstances[instanceIndex];
  20070. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20071. offset += 16;
  20072. instancesCount++;
  20073. }
  20074. }
  20075. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20076. if (instancesBuffer) {
  20077. instancesBuffer.dispose();
  20078. }
  20079. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20080. this._instancesBuffer = instancesBuffer;
  20081. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20082. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20083. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20084. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20085. }
  20086. else {
  20087. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20088. }
  20089. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  20090. this._draw(subMesh, fillMode, instancesCount);
  20091. engine.unbindInstanceAttributes();
  20092. };
  20093. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20094. var scene = this.getScene();
  20095. var engine = scene.getEngine();
  20096. if (hardwareInstancedRendering) {
  20097. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20098. }
  20099. else {
  20100. if (batch.renderSelf[subMesh._id]) {
  20101. // Draw
  20102. if (onBeforeDraw) {
  20103. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20104. }
  20105. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20106. }
  20107. if (batch.visibleInstances[subMesh._id]) {
  20108. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20109. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20110. // World
  20111. var world = instance.getWorldMatrix();
  20112. if (onBeforeDraw) {
  20113. onBeforeDraw(true, world, effectiveMaterial);
  20114. }
  20115. // Draw
  20116. this._draw(subMesh, fillMode);
  20117. }
  20118. }
  20119. }
  20120. };
  20121. /**
  20122. * Triggers the draw call for the mesh.
  20123. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20124. */
  20125. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20126. var scene = this.getScene();
  20127. // Managing instances
  20128. var batch = this._getInstancesRenderList(subMesh._id);
  20129. if (batch.mustReturn) {
  20130. return;
  20131. }
  20132. // Checking geometry state
  20133. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20134. return;
  20135. }
  20136. var callbackIndex;
  20137. this.onBeforeRenderObservable.notifyObservers(this);
  20138. var engine = scene.getEngine();
  20139. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20140. // Material
  20141. var effectiveMaterial = subMesh.getMaterial();
  20142. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20143. return;
  20144. }
  20145. // Outline - step 1
  20146. var savedDepthWrite = engine.getDepthWrite();
  20147. if (this.renderOutline) {
  20148. engine.setDepthWrite(false);
  20149. scene.getOutlineRenderer().render(subMesh, batch);
  20150. engine.setDepthWrite(savedDepthWrite);
  20151. }
  20152. effectiveMaterial._preBind();
  20153. var effect = effectiveMaterial.getEffect();
  20154. // Bind
  20155. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20156. this._bind(subMesh, effect, fillMode);
  20157. var world = this.getWorldMatrix();
  20158. effectiveMaterial.bind(world, this);
  20159. // Alpha mode
  20160. if (enableAlphaMode) {
  20161. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20162. }
  20163. // Draw
  20164. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20165. // Unbind
  20166. effectiveMaterial.unbind();
  20167. // Outline - step 2
  20168. if (this.renderOutline && savedDepthWrite) {
  20169. engine.setDepthWrite(true);
  20170. engine.setColorWrite(false);
  20171. scene.getOutlineRenderer().render(subMesh, batch);
  20172. engine.setColorWrite(true);
  20173. }
  20174. // Overlay
  20175. if (this.renderOverlay) {
  20176. var currentMode = engine.getAlphaMode();
  20177. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20178. scene.getOutlineRenderer().render(subMesh, batch, true);
  20179. engine.setAlphaMode(currentMode);
  20180. }
  20181. this.onAfterRenderObservable.notifyObservers(this);
  20182. };
  20183. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20184. if (isInstance) {
  20185. effectiveMaterial.bindOnlyWorldMatrix(world);
  20186. }
  20187. };
  20188. /**
  20189. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20190. */
  20191. Mesh.prototype.getEmittedParticleSystems = function () {
  20192. var results = new Array();
  20193. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20194. var particleSystem = this.getScene().particleSystems[index];
  20195. if (particleSystem.emitter === this) {
  20196. results.push(particleSystem);
  20197. }
  20198. }
  20199. return results;
  20200. };
  20201. /**
  20202. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20203. */
  20204. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20205. var results = new Array();
  20206. var descendants = this.getDescendants();
  20207. descendants.push(this);
  20208. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20209. var particleSystem = this.getScene().particleSystems[index];
  20210. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20211. results.push(particleSystem);
  20212. }
  20213. }
  20214. return results;
  20215. };
  20216. Mesh.prototype._checkDelayState = function () {
  20217. var scene = this.getScene();
  20218. if (this._geometry) {
  20219. this._geometry.load(scene);
  20220. }
  20221. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20222. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20223. this._queueLoad(this, scene);
  20224. }
  20225. };
  20226. Mesh.prototype._queueLoad = function (mesh, scene) {
  20227. var _this = this;
  20228. scene._addPendingData(mesh);
  20229. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20230. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20231. if (data instanceof ArrayBuffer) {
  20232. _this._delayLoadingFunction(data, _this);
  20233. }
  20234. else {
  20235. _this._delayLoadingFunction(JSON.parse(data), _this);
  20236. }
  20237. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20238. scene._removePendingData(_this);
  20239. }, function () { }, scene.database, getBinaryData);
  20240. };
  20241. /**
  20242. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20243. */
  20244. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20245. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20246. return false;
  20247. }
  20248. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20249. return false;
  20250. }
  20251. this._checkDelayState();
  20252. return true;
  20253. };
  20254. /**
  20255. * Sets the mesh material by the material or multiMaterial `id` property.
  20256. * The material `id` is a string identifying the material or the multiMaterial.
  20257. * This method returns nothing.
  20258. */
  20259. Mesh.prototype.setMaterialByID = function (id) {
  20260. var materials = this.getScene().materials;
  20261. var index;
  20262. for (index = 0; index < materials.length; index++) {
  20263. if (materials[index].id === id) {
  20264. this.material = materials[index];
  20265. return;
  20266. }
  20267. }
  20268. // Multi
  20269. var multiMaterials = this.getScene().multiMaterials;
  20270. for (index = 0; index < multiMaterials.length; index++) {
  20271. if (multiMaterials[index].id === id) {
  20272. this.material = multiMaterials[index];
  20273. return;
  20274. }
  20275. }
  20276. };
  20277. /**
  20278. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20279. */
  20280. Mesh.prototype.getAnimatables = function () {
  20281. var results = [];
  20282. if (this.material) {
  20283. results.push(this.material);
  20284. }
  20285. if (this.skeleton) {
  20286. results.push(this.skeleton);
  20287. }
  20288. return results;
  20289. };
  20290. /**
  20291. * Modifies the mesh geometry according to the passed transformation matrix.
  20292. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20293. * The mesh normals are modified accordingly the same transformation.
  20294. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20295. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20296. */
  20297. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20298. // Position
  20299. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20300. return;
  20301. }
  20302. var submeshes = this.subMeshes.splice(0);
  20303. this._resetPointsArrayCache();
  20304. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20305. var temp = [];
  20306. var index;
  20307. for (index = 0; index < data.length; index += 3) {
  20308. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20309. }
  20310. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20311. // Normals
  20312. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20313. return;
  20314. }
  20315. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20316. temp = [];
  20317. for (index = 0; index < data.length; index += 3) {
  20318. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20319. }
  20320. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20321. // flip faces?
  20322. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20323. this.flipFaces();
  20324. }
  20325. // Restore submeshes
  20326. this.releaseSubMeshes();
  20327. this.subMeshes = submeshes;
  20328. };
  20329. /**
  20330. * Modifies the mesh geometry according to its own current World Matrix.
  20331. * The mesh World Matrix is then reset.
  20332. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20333. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20334. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20335. */
  20336. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20337. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20338. this.scaling.copyFromFloats(1, 1, 1);
  20339. this.position.copyFromFloats(0, 0, 0);
  20340. this.rotation.copyFromFloats(0, 0, 0);
  20341. //only if quaternion is already set
  20342. if (this.rotationQuaternion) {
  20343. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20344. }
  20345. this._worldMatrix = BABYLON.Matrix.Identity();
  20346. };
  20347. // Cache
  20348. Mesh.prototype._resetPointsArrayCache = function () {
  20349. this._positions = null;
  20350. };
  20351. Mesh.prototype._generatePointsArray = function () {
  20352. if (this._positions)
  20353. return true;
  20354. this._positions = [];
  20355. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20356. if (!data) {
  20357. return false;
  20358. }
  20359. for (var index = 0; index < data.length; index += 3) {
  20360. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  20361. }
  20362. return true;
  20363. };
  20364. /**
  20365. * Returns a new Mesh object generated from the current mesh properties.
  20366. * This method must not get confused with createInstance().
  20367. * The parameter `name` is a string, the name given to the new mesh.
  20368. * The optional parameter `newParent` can be any Node object (default `null`).
  20369. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20370. * 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.
  20371. */
  20372. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20373. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20374. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20375. };
  20376. /**
  20377. * Disposes the mesh.
  20378. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20379. */
  20380. Mesh.prototype.dispose = function (doNotRecurse) {
  20381. if (this._geometry) {
  20382. this._geometry.releaseForMesh(this, true);
  20383. }
  20384. // Instances
  20385. if (this._instancesBuffer) {
  20386. this._instancesBuffer.dispose();
  20387. this._instancesBuffer = null;
  20388. }
  20389. while (this.instances.length) {
  20390. this.instances[0].dispose();
  20391. }
  20392. // Highlight layers.
  20393. var highlightLayers = this.getScene().highlightLayers;
  20394. for (var i = 0; i < highlightLayers.length; i++) {
  20395. var highlightLayer = highlightLayers[i];
  20396. if (highlightLayer) {
  20397. highlightLayer.removeMesh(this);
  20398. highlightLayer.removeExcludedMesh(this);
  20399. }
  20400. }
  20401. _super.prototype.dispose.call(this, doNotRecurse);
  20402. };
  20403. /**
  20404. * Modifies the mesh geometry according to a displacement map.
  20405. * 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.
  20406. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20407. * This method returns nothing.
  20408. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20409. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20410. * 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.
  20411. */
  20412. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  20413. var _this = this;
  20414. var scene = this.getScene();
  20415. var onload = function (img) {
  20416. // Getting height map data
  20417. var canvas = document.createElement("canvas");
  20418. var context = canvas.getContext("2d");
  20419. var heightMapWidth = img.width;
  20420. var heightMapHeight = img.height;
  20421. canvas.width = heightMapWidth;
  20422. canvas.height = heightMapHeight;
  20423. context.drawImage(img, 0, 0);
  20424. // Create VertexData from map data
  20425. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20426. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20427. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  20428. //execute success callback, if set
  20429. if (onSuccess) {
  20430. onSuccess(_this);
  20431. }
  20432. };
  20433. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20434. };
  20435. /**
  20436. * Modifies the mesh geometry according to a displacementMap buffer.
  20437. * 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.
  20438. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20439. * This method returns nothing.
  20440. * 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.
  20441. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20442. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20443. */
  20444. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  20445. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20446. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20447. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20448. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20449. return;
  20450. }
  20451. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20452. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20453. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20454. var position = BABYLON.Vector3.Zero();
  20455. var normal = BABYLON.Vector3.Zero();
  20456. var uv = BABYLON.Vector2.Zero();
  20457. for (var index = 0; index < positions.length; index += 3) {
  20458. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20459. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20460. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20461. // Compute height
  20462. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  20463. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  20464. var pos = (u + v * heightMapWidth) * 4;
  20465. var r = buffer[pos] / 255.0;
  20466. var g = buffer[pos + 1] / 255.0;
  20467. var b = buffer[pos + 2] / 255.0;
  20468. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20469. normal.normalize();
  20470. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20471. position = position.add(normal);
  20472. position.toArray(positions, index);
  20473. }
  20474. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20475. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20476. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20477. };
  20478. /**
  20479. * Modify the mesh to get a flat shading rendering.
  20480. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20481. * This method returns nothing.
  20482. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20483. */
  20484. Mesh.prototype.convertToFlatShadedMesh = function () {
  20485. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20486. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20487. var kinds = this.getVerticesDataKinds();
  20488. var vbs = [];
  20489. var data = [];
  20490. var newdata = [];
  20491. var updatableNormals = false;
  20492. var kindIndex;
  20493. var kind;
  20494. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20495. kind = kinds[kindIndex];
  20496. var vertexBuffer = this.getVertexBuffer(kind);
  20497. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20498. updatableNormals = vertexBuffer.isUpdatable();
  20499. kinds.splice(kindIndex, 1);
  20500. kindIndex--;
  20501. continue;
  20502. }
  20503. vbs[kind] = vertexBuffer;
  20504. data[kind] = vbs[kind].getData();
  20505. newdata[kind] = [];
  20506. }
  20507. // Save previous submeshes
  20508. var previousSubmeshes = this.subMeshes.slice(0);
  20509. var indices = this.getIndices();
  20510. var totalIndices = this.getTotalIndices();
  20511. // Generating unique vertices per face
  20512. var index;
  20513. for (index = 0; index < totalIndices; index++) {
  20514. var vertexIndex = indices[index];
  20515. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20516. kind = kinds[kindIndex];
  20517. var stride = vbs[kind].getStrideSize();
  20518. for (var offset = 0; offset < stride; offset++) {
  20519. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20520. }
  20521. }
  20522. }
  20523. // Updating faces & normal
  20524. var normals = [];
  20525. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20526. for (index = 0; index < totalIndices; index += 3) {
  20527. indices[index] = index;
  20528. indices[index + 1] = index + 1;
  20529. indices[index + 2] = index + 2;
  20530. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20531. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20532. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20533. var p1p2 = p1.subtract(p2);
  20534. var p3p2 = p3.subtract(p2);
  20535. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20536. // Store same normals for every vertex
  20537. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20538. normals.push(normal.x);
  20539. normals.push(normal.y);
  20540. normals.push(normal.z);
  20541. }
  20542. }
  20543. this.setIndices(indices);
  20544. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20545. // Updating vertex buffers
  20546. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20547. kind = kinds[kindIndex];
  20548. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20549. }
  20550. // Updating submeshes
  20551. this.releaseSubMeshes();
  20552. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20553. var previousOne = previousSubmeshes[submeshIndex];
  20554. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20555. }
  20556. this.synchronizeInstances();
  20557. };
  20558. /**
  20559. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20560. * In other words, more vertices, no more indices and a single bigger VBO.
  20561. * This method returns nothing.
  20562. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20563. *
  20564. */
  20565. Mesh.prototype.convertToUnIndexedMesh = function () {
  20566. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20567. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20568. var kinds = this.getVerticesDataKinds();
  20569. var vbs = [];
  20570. var data = [];
  20571. var newdata = [];
  20572. var updatableNormals = false;
  20573. var kindIndex;
  20574. var kind;
  20575. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20576. kind = kinds[kindIndex];
  20577. var vertexBuffer = this.getVertexBuffer(kind);
  20578. vbs[kind] = vertexBuffer;
  20579. data[kind] = vbs[kind].getData();
  20580. newdata[kind] = [];
  20581. }
  20582. // Save previous submeshes
  20583. var previousSubmeshes = this.subMeshes.slice(0);
  20584. var indices = this.getIndices();
  20585. var totalIndices = this.getTotalIndices();
  20586. // Generating unique vertices per face
  20587. var index;
  20588. for (index = 0; index < totalIndices; index++) {
  20589. var vertexIndex = indices[index];
  20590. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20591. kind = kinds[kindIndex];
  20592. var stride = vbs[kind].getStrideSize();
  20593. for (var offset = 0; offset < stride; offset++) {
  20594. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20595. }
  20596. }
  20597. }
  20598. // Updating indices
  20599. for (index = 0; index < totalIndices; index += 3) {
  20600. indices[index] = index;
  20601. indices[index + 1] = index + 1;
  20602. indices[index + 2] = index + 2;
  20603. }
  20604. this.setIndices(indices);
  20605. // Updating vertex buffers
  20606. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20607. kind = kinds[kindIndex];
  20608. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20609. }
  20610. // Updating submeshes
  20611. this.releaseSubMeshes();
  20612. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20613. var previousOne = previousSubmeshes[submeshIndex];
  20614. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20615. }
  20616. this._unIndexed = true;
  20617. this.synchronizeInstances();
  20618. };
  20619. /**
  20620. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  20621. * This method returns nothing.
  20622. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  20623. */
  20624. Mesh.prototype.flipFaces = function (flipNormals) {
  20625. if (flipNormals === void 0) { flipNormals = false; }
  20626. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  20627. var i;
  20628. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20629. for (i = 0; i < vertex_data.normals.length; i++) {
  20630. vertex_data.normals[i] *= -1;
  20631. }
  20632. }
  20633. var temp;
  20634. for (i = 0; i < vertex_data.indices.length; i += 3) {
  20635. // reassign indices
  20636. temp = vertex_data.indices[i + 1];
  20637. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  20638. vertex_data.indices[i + 2] = temp;
  20639. }
  20640. vertex_data.applyToMesh(this);
  20641. };
  20642. // Instances
  20643. /**
  20644. * Creates a new InstancedMesh object from the mesh model.
  20645. * An instance shares the same properties and the same material than its model.
  20646. * Only these properties of each instance can then be set individually :
  20647. * - position
  20648. * - rotation
  20649. * - rotationQuaternion
  20650. * - setPivotMatrix
  20651. * - scaling
  20652. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  20653. * Warning : this method is not supported for Line mesh and LineSystem
  20654. */
  20655. Mesh.prototype.createInstance = function (name) {
  20656. return new BABYLON.InstancedMesh(name, this);
  20657. };
  20658. /**
  20659. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  20660. * After this call, all the mesh instances have the same submeshes than the current mesh.
  20661. * This method returns nothing.
  20662. */
  20663. Mesh.prototype.synchronizeInstances = function () {
  20664. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  20665. var instance = this.instances[instanceIndex];
  20666. instance._syncSubMeshes();
  20667. }
  20668. };
  20669. /**
  20670. * Simplify the mesh according to the given array of settings.
  20671. * Function will return immediately and will simplify async. It returns nothing.
  20672. * @param settings a collection of simplification settings.
  20673. * @param parallelProcessing should all levels calculate parallel or one after the other.
  20674. * @param type the type of simplification to run.
  20675. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  20676. */
  20677. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  20678. if (parallelProcessing === void 0) { parallelProcessing = true; }
  20679. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  20680. this.getScene().simplificationQueue.addTask({
  20681. settings: settings,
  20682. parallelProcessing: parallelProcessing,
  20683. mesh: this,
  20684. simplificationType: simplificationType,
  20685. successCallback: successCallback
  20686. });
  20687. };
  20688. /**
  20689. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  20690. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  20691. * This should be used together with the simplification to avoid disappearing triangles.
  20692. * @param successCallback an optional success callback to be called after the optimization finished.
  20693. */
  20694. Mesh.prototype.optimizeIndices = function (successCallback) {
  20695. var _this = this;
  20696. var indices = this.getIndices();
  20697. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20698. var vectorPositions = [];
  20699. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  20700. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  20701. }
  20702. var dupes = [];
  20703. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  20704. var realPos = vectorPositions.length - 1 - iteration;
  20705. var testedPosition = vectorPositions[realPos];
  20706. for (var j = 0; j < realPos; ++j) {
  20707. var againstPosition = vectorPositions[j];
  20708. if (testedPosition.equals(againstPosition)) {
  20709. dupes[realPos] = j;
  20710. break;
  20711. }
  20712. }
  20713. }, function () {
  20714. for (var i = 0; i < indices.length; ++i) {
  20715. indices[i] = dupes[indices[i]] || indices[i];
  20716. }
  20717. //indices are now reordered
  20718. var originalSubMeshes = _this.subMeshes.slice(0);
  20719. _this.setIndices(indices);
  20720. _this.subMeshes = originalSubMeshes;
  20721. if (successCallback) {
  20722. successCallback(_this);
  20723. }
  20724. });
  20725. };
  20726. // Statics
  20727. /**
  20728. * Returns a new Mesh object what is a deep copy of the passed mesh.
  20729. * The parameter `parsedMesh` is the mesh to be copied.
  20730. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20731. */
  20732. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  20733. var mesh = new Mesh(parsedMesh.name, scene);
  20734. mesh.id = parsedMesh.id;
  20735. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20736. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20737. if (parsedMesh.metadata !== undefined) {
  20738. mesh.metadata = parsedMesh.metadata;
  20739. }
  20740. if (parsedMesh.rotationQuaternion) {
  20741. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20742. }
  20743. else if (parsedMesh.rotation) {
  20744. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20745. }
  20746. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20747. if (parsedMesh.localMatrix) {
  20748. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20749. }
  20750. else if (parsedMesh.pivotMatrix) {
  20751. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20752. }
  20753. mesh.setEnabled(parsedMesh.isEnabled);
  20754. mesh.isVisible = parsedMesh.isVisible;
  20755. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20756. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20757. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20758. if (parsedMesh.applyFog !== undefined) {
  20759. mesh.applyFog = parsedMesh.applyFog;
  20760. }
  20761. if (parsedMesh.pickable !== undefined) {
  20762. mesh.isPickable = parsedMesh.pickable;
  20763. }
  20764. if (parsedMesh.alphaIndex !== undefined) {
  20765. mesh.alphaIndex = parsedMesh.alphaIndex;
  20766. }
  20767. mesh.receiveShadows = parsedMesh.receiveShadows;
  20768. mesh.billboardMode = parsedMesh.billboardMode;
  20769. if (parsedMesh.visibility !== undefined) {
  20770. mesh.visibility = parsedMesh.visibility;
  20771. }
  20772. mesh.checkCollisions = parsedMesh.checkCollisions;
  20773. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20774. // freezeWorldMatrix
  20775. if (parsedMesh.freezeWorldMatrix) {
  20776. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20777. }
  20778. // Parent
  20779. if (parsedMesh.parentId) {
  20780. mesh._waitingParentId = parsedMesh.parentId;
  20781. }
  20782. // Actions
  20783. if (parsedMesh.actions !== undefined) {
  20784. mesh._waitingActions = parsedMesh.actions;
  20785. }
  20786. // Geometry
  20787. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20788. if (parsedMesh.delayLoadingFile) {
  20789. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20790. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20791. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20792. if (parsedMesh._binaryInfo) {
  20793. mesh._binaryInfo = parsedMesh._binaryInfo;
  20794. }
  20795. mesh._delayInfo = [];
  20796. if (parsedMesh.hasUVs) {
  20797. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20798. }
  20799. if (parsedMesh.hasUVs2) {
  20800. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20801. }
  20802. if (parsedMesh.hasUVs3) {
  20803. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20804. }
  20805. if (parsedMesh.hasUVs4) {
  20806. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20807. }
  20808. if (parsedMesh.hasUVs5) {
  20809. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20810. }
  20811. if (parsedMesh.hasUVs6) {
  20812. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20813. }
  20814. if (parsedMesh.hasColors) {
  20815. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20816. }
  20817. if (parsedMesh.hasMatricesIndices) {
  20818. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20819. }
  20820. if (parsedMesh.hasMatricesWeights) {
  20821. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20822. }
  20823. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  20824. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20825. mesh._checkDelayState();
  20826. }
  20827. }
  20828. else {
  20829. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  20830. }
  20831. // Material
  20832. if (parsedMesh.materialId) {
  20833. mesh.setMaterialByID(parsedMesh.materialId);
  20834. }
  20835. else {
  20836. mesh.material = null;
  20837. }
  20838. // Skeleton
  20839. if (parsedMesh.skeletonId > -1) {
  20840. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20841. if (parsedMesh.numBoneInfluencers) {
  20842. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  20843. }
  20844. }
  20845. // Animations
  20846. if (parsedMesh.animations) {
  20847. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20848. var parsedAnimation = parsedMesh.animations[animationIndex];
  20849. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20850. }
  20851. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  20852. }
  20853. if (parsedMesh.autoAnimate) {
  20854. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  20855. }
  20856. // Layer Mask
  20857. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20858. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20859. }
  20860. else {
  20861. mesh.layerMask = 0x0FFFFFFF;
  20862. }
  20863. //(Deprecated) physics
  20864. if (parsedMesh.physicsImpostor) {
  20865. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  20866. mass: parsedMesh.physicsMass,
  20867. friction: parsedMesh.physicsFriction,
  20868. restitution: parsedMesh.physicsRestitution
  20869. }, scene);
  20870. }
  20871. // Instances
  20872. if (parsedMesh.instances) {
  20873. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20874. var parsedInstance = parsedMesh.instances[index];
  20875. var instance = mesh.createInstance(parsedInstance.name);
  20876. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20877. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20878. if (parsedInstance.parentId) {
  20879. instance._waitingParentId = parsedInstance.parentId;
  20880. }
  20881. if (parsedInstance.rotationQuaternion) {
  20882. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20883. }
  20884. else if (parsedInstance.rotation) {
  20885. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20886. }
  20887. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20888. instance.checkCollisions = mesh.checkCollisions;
  20889. if (parsedMesh.animations) {
  20890. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20891. parsedAnimation = parsedMesh.animations[animationIndex];
  20892. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20893. }
  20894. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  20895. }
  20896. }
  20897. }
  20898. return mesh;
  20899. };
  20900. /**
  20901. * Creates a ribbon mesh.
  20902. * Please consider using the same method from the MeshBuilder class instead.
  20903. * 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.
  20904. *
  20905. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20906. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20907. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20908. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20909. * 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.
  20910. * 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.
  20911. * 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
  20912. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20913. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20914. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20915. */
  20916. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  20917. return BABYLON.MeshBuilder.CreateRibbon(name, {
  20918. pathArray: pathArray,
  20919. closeArray: closeArray,
  20920. closePath: closePath,
  20921. offset: offset,
  20922. updatable: updatable,
  20923. sideOrientation: sideOrientation,
  20924. instance: instance
  20925. }, scene);
  20926. };
  20927. /**
  20928. * Creates a plane polygonal mesh. By default, this is a disc.
  20929. * Please consider using the same method from the MeshBuilder class instead.
  20930. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20931. * 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.
  20932. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20933. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20934. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20935. */
  20936. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  20937. var options = {
  20938. radius: radius,
  20939. tessellation: tessellation,
  20940. sideOrientation: sideOrientation,
  20941. updatable: updatable
  20942. };
  20943. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  20944. };
  20945. /**
  20946. * Creates a box mesh.
  20947. * Please consider using the same method from the MeshBuilder class instead.
  20948. * The parameter `size` sets the size (float) of each box side (default 1).
  20949. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20950. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20951. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20952. */
  20953. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  20954. var options = {
  20955. size: size,
  20956. sideOrientation: sideOrientation,
  20957. updatable: updatable
  20958. };
  20959. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  20960. };
  20961. /**
  20962. * Creates a sphere mesh.
  20963. * Please consider using the same method from the MeshBuilder class instead.
  20964. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20965. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20966. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20967. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20968. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20969. */
  20970. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  20971. var options = {
  20972. segments: segments,
  20973. diameterX: diameter,
  20974. diameterY: diameter,
  20975. diameterZ: diameter,
  20976. sideOrientation: sideOrientation,
  20977. updatable: updatable
  20978. };
  20979. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  20980. };
  20981. /**
  20982. * Creates a cylinder or a cone mesh.
  20983. * Please consider using the same method from the MeshBuilder class instead.
  20984. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20985. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20986. * 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.
  20987. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20988. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20989. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20990. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20991. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20992. */
  20993. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  20994. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  20995. if (scene !== undefined) {
  20996. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  20997. updatable = scene;
  20998. }
  20999. scene = subdivisions;
  21000. subdivisions = 1;
  21001. }
  21002. var options = {
  21003. height: height,
  21004. diameterTop: diameterTop,
  21005. diameterBottom: diameterBottom,
  21006. tessellation: tessellation,
  21007. subdivisions: subdivisions,
  21008. sideOrientation: sideOrientation,
  21009. updatable: updatable
  21010. };
  21011. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21012. };
  21013. // Torus (Code from SharpDX.org)
  21014. /**
  21015. * Creates a torus mesh.
  21016. * Please consider using the same method from the MeshBuilder class instead.
  21017. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21018. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21019. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21020. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21021. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21022. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21023. */
  21024. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21025. var options = {
  21026. diameter: diameter,
  21027. thickness: thickness,
  21028. tessellation: tessellation,
  21029. sideOrientation: sideOrientation,
  21030. updatable: updatable
  21031. };
  21032. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21033. };
  21034. /**
  21035. * Creates a torus knot mesh.
  21036. * Please consider using the same method from the MeshBuilder class instead.
  21037. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21038. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21039. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21040. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21041. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21042. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21043. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21044. */
  21045. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21046. var options = {
  21047. radius: radius,
  21048. tube: tube,
  21049. radialSegments: radialSegments,
  21050. tubularSegments: tubularSegments,
  21051. p: p,
  21052. q: q,
  21053. sideOrientation: sideOrientation,
  21054. updatable: updatable
  21055. };
  21056. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21057. };
  21058. /**
  21059. * Creates a line mesh.
  21060. * Please consider using the same method from the MeshBuilder class instead.
  21061. * 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.
  21062. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21063. * The parameter `points` is an array successive Vector3.
  21064. * 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
  21065. * When updating an instance, remember that only point positions can change, not the number of points.
  21066. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21067. */
  21068. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21069. var options = {
  21070. points: points,
  21071. updatable: updatable,
  21072. instance: instance
  21073. };
  21074. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21075. };
  21076. /**
  21077. * Creates a dashed line mesh.
  21078. * Please consider using the same method from the MeshBuilder class instead.
  21079. * 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.
  21080. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21081. * The parameter `points` is an array successive Vector3.
  21082. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21083. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21084. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21085. * 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
  21086. * When updating an instance, remember that only point positions can change, not the number of points.
  21087. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21088. */
  21089. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21090. var options = {
  21091. points: points,
  21092. dashSize: dashSize,
  21093. gapSize: gapSize,
  21094. dashNb: dashNb,
  21095. updatable: updatable,
  21096. instance: instance
  21097. };
  21098. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21099. };
  21100. /**
  21101. * Creates an extruded shape mesh.
  21102. * 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.
  21103. * Please consider using the same method from the MeshBuilder class instead.
  21104. *
  21105. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21106. * 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
  21107. * extruded along the Z axis.
  21108. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21109. * 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.
  21110. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21111. * 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
  21112. * 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
  21113. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21114. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21115. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21116. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21117. */
  21118. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21119. var options = {
  21120. shape: shape,
  21121. path: path,
  21122. scale: scale,
  21123. rotation: rotation,
  21124. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21125. sideOrientation: sideOrientation,
  21126. instance: instance,
  21127. updatable: updatable
  21128. };
  21129. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21130. };
  21131. /**
  21132. * Creates an custom extruded shape mesh.
  21133. * 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.
  21134. * Please consider using the same method from the MeshBuilder class instead.
  21135. *
  21136. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21137. * 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
  21138. * extruded along the Z axis.
  21139. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21140. * 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
  21141. * and the distance of this point from the begining of the path :
  21142. * ```javascript
  21143. * var rotationFunction = function(i, distance) {
  21144. * // do things
  21145. * return rotationValue; }
  21146. * ```
  21147. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21148. * 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
  21149. * and the distance of this point from the begining of the path :
  21150. * ```javascript
  21151. * var scaleFunction = function(i, distance) {
  21152. * // do things
  21153. * return scaleValue;}
  21154. * ```
  21155. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21156. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21157. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21158. * 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
  21159. * 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
  21160. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21161. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21162. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21163. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21164. */
  21165. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21166. var options = {
  21167. shape: shape,
  21168. path: path,
  21169. scaleFunction: scaleFunction,
  21170. rotationFunction: rotationFunction,
  21171. ribbonCloseArray: ribbonCloseArray,
  21172. ribbonClosePath: ribbonClosePath,
  21173. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21174. sideOrientation: sideOrientation,
  21175. instance: instance,
  21176. updatable: updatable
  21177. };
  21178. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21179. };
  21180. /**
  21181. * Creates lathe mesh.
  21182. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21183. * Please consider using the same method from the MeshBuilder class instead.
  21184. * 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
  21185. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21186. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21187. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21188. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21189. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21190. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21191. */
  21192. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21193. var options = {
  21194. shape: shape,
  21195. radius: radius,
  21196. tessellation: tessellation,
  21197. sideOrientation: sideOrientation,
  21198. updatable: updatable
  21199. };
  21200. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21201. };
  21202. /**
  21203. * Creates a plane mesh.
  21204. * Please consider using the same method from the MeshBuilder class instead.
  21205. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21206. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21207. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21208. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21209. */
  21210. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21211. var options = {
  21212. size: size,
  21213. width: size,
  21214. height: size,
  21215. sideOrientation: sideOrientation,
  21216. updatable: updatable
  21217. };
  21218. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21219. };
  21220. /**
  21221. * Creates a ground mesh.
  21222. * Please consider using the same method from the MeshBuilder class instead.
  21223. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21224. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21225. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21226. */
  21227. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21228. var options = {
  21229. width: width,
  21230. height: height,
  21231. subdivisions: subdivisions,
  21232. updatable: updatable
  21233. };
  21234. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21235. };
  21236. /**
  21237. * Creates a tiled ground mesh.
  21238. * Please consider using the same method from the MeshBuilder class instead.
  21239. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21240. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21241. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21242. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21243. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21244. * numbers of subdivisions on the ground width and height of each tile.
  21245. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21246. */
  21247. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21248. var options = {
  21249. xmin: xmin,
  21250. zmin: zmin,
  21251. xmax: xmax,
  21252. zmax: zmax,
  21253. subdivisions: subdivisions,
  21254. precision: precision,
  21255. updatable: updatable
  21256. };
  21257. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21258. };
  21259. /**
  21260. * Creates a ground mesh from a height map.
  21261. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21262. * Please consider using the same method from the MeshBuilder class instead.
  21263. * The parameter `url` sets the URL of the height map image resource.
  21264. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21265. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21266. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21267. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21268. * 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).
  21269. * This function is passed the newly built mesh :
  21270. * ```javascript
  21271. * function(mesh) { // do things
  21272. * return; }
  21273. * ```
  21274. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21275. */
  21276. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21277. var options = {
  21278. width: width,
  21279. height: height,
  21280. subdivisions: subdivisions,
  21281. minHeight: minHeight,
  21282. maxHeight: maxHeight,
  21283. updatable: updatable,
  21284. onReady: onReady
  21285. };
  21286. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21287. };
  21288. /**
  21289. * Creates a tube mesh.
  21290. * 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.
  21291. * Please consider using the same method from the MeshBuilder class instead.
  21292. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21293. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21294. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21295. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21296. * 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.
  21297. * It must return a radius value (positive float) :
  21298. * ```javascript
  21299. * var radiusFunction = function(i, distance) {
  21300. * // do things
  21301. * return radius; }
  21302. * ```
  21303. * 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
  21304. * 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
  21305. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21306. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21307. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21308. */
  21309. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21310. var options = {
  21311. path: path,
  21312. radius: radius,
  21313. tessellation: tessellation,
  21314. radiusFunction: radiusFunction,
  21315. arc: 1,
  21316. cap: cap,
  21317. updatable: updatable,
  21318. sideOrientation: sideOrientation,
  21319. instance: instance
  21320. };
  21321. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21322. };
  21323. /**
  21324. * Creates a polyhedron mesh.
  21325. * Please consider using the same method from the MeshBuilder class instead.
  21326. * 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
  21327. * to choose the wanted type.
  21328. * The parameter `size` (positive float, default 1) sets the polygon size.
  21329. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21330. * 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`.
  21331. * 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
  21332. * 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)`).
  21333. * 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
  21334. * 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.
  21335. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21336. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21337. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21338. */
  21339. Mesh.CreatePolyhedron = function (name, options, scene) {
  21340. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21341. };
  21342. /**
  21343. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21344. * Please consider using the same method from the MeshBuilder class instead.
  21345. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21346. * 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`).
  21347. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21348. * 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.
  21349. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21350. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21351. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21352. */
  21353. Mesh.CreateIcoSphere = function (name, options, scene) {
  21354. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21355. };
  21356. /**
  21357. * Creates a decal mesh.
  21358. * Please consider using the same method from the MeshBuilder class instead.
  21359. * 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.
  21360. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21361. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21362. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21363. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21364. */
  21365. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21366. var options = {
  21367. position: position,
  21368. normal: normal,
  21369. size: size,
  21370. angle: angle
  21371. };
  21372. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21373. };
  21374. // Skeletons
  21375. /**
  21376. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21377. */
  21378. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21379. var source;
  21380. if (!this._sourcePositions) {
  21381. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21382. this._sourcePositions = new Float32Array(source);
  21383. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21384. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21385. }
  21386. }
  21387. return this._sourcePositions;
  21388. };
  21389. /**
  21390. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21391. */
  21392. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21393. var source;
  21394. if (!this._sourceNormals) {
  21395. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21396. this._sourceNormals = new Float32Array(source);
  21397. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21398. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21399. }
  21400. }
  21401. return this._sourceNormals;
  21402. };
  21403. /**
  21404. * Update the vertex buffers by applying transformation from the bones
  21405. * @param {skeleton} skeleton to apply
  21406. */
  21407. Mesh.prototype.applySkeleton = function (skeleton) {
  21408. if (!this.geometry) {
  21409. return;
  21410. }
  21411. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21412. return;
  21413. }
  21414. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21415. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21416. return this;
  21417. }
  21418. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21419. return this;
  21420. }
  21421. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21422. return this;
  21423. }
  21424. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21425. return this;
  21426. }
  21427. if (!this._sourcePositions) {
  21428. var submeshes = this.subMeshes.slice();
  21429. this.setPositionsForCPUSkinning();
  21430. this.subMeshes = submeshes;
  21431. }
  21432. if (!this._sourceNormals) {
  21433. this.setNormalsForCPUSkinning();
  21434. }
  21435. // positionsData checks for not being Float32Array will only pass at most once
  21436. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21437. if (!(positionsData instanceof Float32Array)) {
  21438. positionsData = new Float32Array(positionsData);
  21439. }
  21440. // normalsData checks for not being Float32Array will only pass at most once
  21441. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21442. if (!(normalsData instanceof Float32Array)) {
  21443. normalsData = new Float32Array(normalsData);
  21444. }
  21445. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21446. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21447. var needExtras = this.numBoneInfluencers > 4;
  21448. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21449. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21450. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21451. var tempVector3 = BABYLON.Vector3.Zero();
  21452. var finalMatrix = new BABYLON.Matrix();
  21453. var tempMatrix = new BABYLON.Matrix();
  21454. var matWeightIdx = 0;
  21455. var inf;
  21456. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21457. var weight;
  21458. for (inf = 0; inf < 4; inf++) {
  21459. weight = matricesWeightsData[matWeightIdx + inf];
  21460. if (weight > 0) {
  21461. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21462. finalMatrix.addToSelf(tempMatrix);
  21463. }
  21464. else
  21465. break;
  21466. }
  21467. if (needExtras) {
  21468. for (inf = 0; inf < 4; inf++) {
  21469. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21470. if (weight > 0) {
  21471. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21472. finalMatrix.addToSelf(tempMatrix);
  21473. }
  21474. else
  21475. break;
  21476. }
  21477. }
  21478. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21479. tempVector3.toArray(positionsData, index);
  21480. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21481. tempVector3.toArray(normalsData, index);
  21482. finalMatrix.reset();
  21483. }
  21484. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21485. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21486. return this;
  21487. };
  21488. // Tools
  21489. /**
  21490. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21491. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  21492. */
  21493. Mesh.MinMax = function (meshes) {
  21494. var minVector = null;
  21495. var maxVector = null;
  21496. meshes.forEach(function (mesh, index, array) {
  21497. var boundingBox = mesh.getBoundingInfo().boundingBox;
  21498. if (!minVector) {
  21499. minVector = boundingBox.minimumWorld;
  21500. maxVector = boundingBox.maximumWorld;
  21501. }
  21502. else {
  21503. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  21504. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  21505. }
  21506. });
  21507. return {
  21508. min: minVector,
  21509. max: maxVector
  21510. };
  21511. };
  21512. /**
  21513. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  21514. */
  21515. Mesh.Center = function (meshesOrMinMaxVector) {
  21516. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  21517. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  21518. };
  21519. /**
  21520. * Merge the array of meshes into a single mesh for performance reasons.
  21521. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  21522. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  21523. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  21524. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  21525. */
  21526. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  21527. if (disposeSource === void 0) { disposeSource = true; }
  21528. var index;
  21529. if (!allow32BitsIndices) {
  21530. var totalVertices = 0;
  21531. // Counting vertices
  21532. for (index = 0; index < meshes.length; index++) {
  21533. if (meshes[index]) {
  21534. totalVertices += meshes[index].getTotalVertices();
  21535. if (totalVertices > 65536) {
  21536. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  21537. return null;
  21538. }
  21539. }
  21540. }
  21541. }
  21542. // Merge
  21543. var vertexData;
  21544. var otherVertexData;
  21545. var source;
  21546. for (index = 0; index < meshes.length; index++) {
  21547. if (meshes[index]) {
  21548. meshes[index].computeWorldMatrix(true);
  21549. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  21550. otherVertexData.transform(meshes[index].getWorldMatrix());
  21551. if (vertexData) {
  21552. vertexData.merge(otherVertexData);
  21553. }
  21554. else {
  21555. vertexData = otherVertexData;
  21556. source = meshes[index];
  21557. }
  21558. }
  21559. }
  21560. if (!meshSubclass) {
  21561. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  21562. }
  21563. vertexData.applyToMesh(meshSubclass);
  21564. // Setting properties
  21565. meshSubclass.material = source.material;
  21566. meshSubclass.checkCollisions = source.checkCollisions;
  21567. // Cleaning
  21568. if (disposeSource) {
  21569. for (index = 0; index < meshes.length; index++) {
  21570. if (meshes[index]) {
  21571. meshes[index].dispose();
  21572. }
  21573. }
  21574. }
  21575. return meshSubclass;
  21576. };
  21577. // Consts
  21578. Mesh._FRONTSIDE = 0;
  21579. Mesh._BACKSIDE = 1;
  21580. Mesh._DOUBLESIDE = 2;
  21581. Mesh._DEFAULTSIDE = 0;
  21582. Mesh._NO_CAP = 0;
  21583. Mesh._CAP_START = 1;
  21584. Mesh._CAP_END = 2;
  21585. Mesh._CAP_ALL = 3;
  21586. return Mesh;
  21587. }(BABYLON.AbstractMesh));
  21588. BABYLON.Mesh = Mesh;
  21589. })(BABYLON || (BABYLON = {}));
  21590. var BABYLON;
  21591. (function (BABYLON) {
  21592. var SubMesh = (function () {
  21593. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  21594. if (createBoundingBox === void 0) { createBoundingBox = true; }
  21595. this.materialIndex = materialIndex;
  21596. this.verticesStart = verticesStart;
  21597. this.verticesCount = verticesCount;
  21598. this.indexStart = indexStart;
  21599. this.indexCount = indexCount;
  21600. this._renderId = 0;
  21601. this._mesh = mesh;
  21602. this._renderingMesh = renderingMesh || mesh;
  21603. mesh.subMeshes.push(this);
  21604. this._trianglePlanes = [];
  21605. this._id = mesh.subMeshes.length - 1;
  21606. if (createBoundingBox) {
  21607. this.refreshBoundingInfo();
  21608. mesh.computeWorldMatrix(true);
  21609. }
  21610. }
  21611. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  21612. get: function () {
  21613. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  21614. },
  21615. enumerable: true,
  21616. configurable: true
  21617. });
  21618. SubMesh.prototype.getBoundingInfo = function () {
  21619. if (this.IsGlobal) {
  21620. return this._mesh.getBoundingInfo();
  21621. }
  21622. return this._boundingInfo;
  21623. };
  21624. SubMesh.prototype.getMesh = function () {
  21625. return this._mesh;
  21626. };
  21627. SubMesh.prototype.getRenderingMesh = function () {
  21628. return this._renderingMesh;
  21629. };
  21630. SubMesh.prototype.getMaterial = function () {
  21631. var rootMaterial = this._renderingMesh.material;
  21632. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  21633. var multiMaterial = rootMaterial;
  21634. return multiMaterial.getSubMaterial(this.materialIndex);
  21635. }
  21636. if (!rootMaterial) {
  21637. return this._mesh.getScene().defaultMaterial;
  21638. }
  21639. return rootMaterial;
  21640. };
  21641. // Methods
  21642. SubMesh.prototype.refreshBoundingInfo = function () {
  21643. this._lastColliderWorldVertices = null;
  21644. if (this.IsGlobal) {
  21645. return;
  21646. }
  21647. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21648. if (!data) {
  21649. this._boundingInfo = this._mesh._boundingInfo;
  21650. return;
  21651. }
  21652. var indices = this._renderingMesh.getIndices();
  21653. var extend;
  21654. //is this the only submesh?
  21655. if (this.indexStart === 0 && this.indexCount === indices.length) {
  21656. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  21657. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  21658. }
  21659. else {
  21660. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  21661. }
  21662. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21663. };
  21664. SubMesh.prototype._checkCollision = function (collider) {
  21665. return this.getBoundingInfo()._checkCollision(collider);
  21666. };
  21667. SubMesh.prototype.updateBoundingInfo = function (world) {
  21668. if (!this.getBoundingInfo()) {
  21669. this.refreshBoundingInfo();
  21670. }
  21671. this.getBoundingInfo().update(world);
  21672. };
  21673. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  21674. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  21675. };
  21676. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21677. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  21678. };
  21679. SubMesh.prototype.render = function (enableAlphaMode) {
  21680. this._renderingMesh.render(this, enableAlphaMode);
  21681. };
  21682. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  21683. if (!this._linesIndexBuffer) {
  21684. var linesIndices = [];
  21685. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21686. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  21687. }
  21688. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  21689. this.linesIndexCount = linesIndices.length;
  21690. }
  21691. return this._linesIndexBuffer;
  21692. };
  21693. SubMesh.prototype.canIntersects = function (ray) {
  21694. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  21695. };
  21696. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  21697. var intersectInfo = null;
  21698. // LineMesh first as it's also a Mesh...
  21699. if (this._mesh instanceof BABYLON.LinesMesh) {
  21700. var lineMesh = this._mesh;
  21701. // Line test
  21702. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  21703. var p0 = positions[indices[index]];
  21704. var p1 = positions[indices[index + 1]];
  21705. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  21706. if (length < 0) {
  21707. continue;
  21708. }
  21709. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  21710. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  21711. if (fastCheck) {
  21712. break;
  21713. }
  21714. }
  21715. }
  21716. }
  21717. else {
  21718. // Triangles test
  21719. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21720. var p0 = positions[indices[index]];
  21721. var p1 = positions[indices[index + 1]];
  21722. var p2 = positions[indices[index + 2]];
  21723. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  21724. if (currentIntersectInfo) {
  21725. if (currentIntersectInfo.distance < 0) {
  21726. continue;
  21727. }
  21728. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21729. intersectInfo = currentIntersectInfo;
  21730. intersectInfo.faceId = index / 3;
  21731. if (fastCheck) {
  21732. break;
  21733. }
  21734. }
  21735. }
  21736. }
  21737. }
  21738. return intersectInfo;
  21739. };
  21740. // Clone
  21741. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  21742. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  21743. if (!this.IsGlobal) {
  21744. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  21745. }
  21746. return result;
  21747. };
  21748. // Dispose
  21749. SubMesh.prototype.dispose = function () {
  21750. if (this._linesIndexBuffer) {
  21751. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  21752. this._linesIndexBuffer = null;
  21753. }
  21754. // Remove from mesh
  21755. var index = this._mesh.subMeshes.indexOf(this);
  21756. this._mesh.subMeshes.splice(index, 1);
  21757. };
  21758. // Statics
  21759. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  21760. var minVertexIndex = Number.MAX_VALUE;
  21761. var maxVertexIndex = -Number.MAX_VALUE;
  21762. renderingMesh = renderingMesh || mesh;
  21763. var indices = renderingMesh.getIndices();
  21764. for (var index = startIndex; index < startIndex + indexCount; index++) {
  21765. var vertexIndex = indices[index];
  21766. if (vertexIndex < minVertexIndex)
  21767. minVertexIndex = vertexIndex;
  21768. if (vertexIndex > maxVertexIndex)
  21769. maxVertexIndex = vertexIndex;
  21770. }
  21771. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  21772. };
  21773. return SubMesh;
  21774. }());
  21775. BABYLON.SubMesh = SubMesh;
  21776. })(BABYLON || (BABYLON = {}));
  21777. var BABYLON;
  21778. (function (BABYLON) {
  21779. var MeshBuilder = (function () {
  21780. function MeshBuilder() {
  21781. }
  21782. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  21783. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  21784. return BABYLON.Mesh.DOUBLESIDE;
  21785. }
  21786. if (orientation === undefined || orientation === null) {
  21787. return BABYLON.Mesh.FRONTSIDE;
  21788. }
  21789. return orientation;
  21790. };
  21791. /**
  21792. * Creates a box mesh.
  21793. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  21794. * The parameter `size` sets the size (float) of each box side (default 1).
  21795. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  21796. * 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).
  21797. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  21798. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21799. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21800. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21801. */
  21802. MeshBuilder.CreateBox = function (name, options, scene) {
  21803. var box = new BABYLON.Mesh(name, scene);
  21804. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21805. var vertexData = BABYLON.VertexData.CreateBox(options);
  21806. vertexData.applyToMesh(box, options.updatable);
  21807. return box;
  21808. };
  21809. /**
  21810. * Creates a sphere mesh.
  21811. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  21812. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21813. * 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`).
  21814. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21815. * 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
  21816. * 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).
  21817. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21818. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21819. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21820. */
  21821. MeshBuilder.CreateSphere = function (name, options, scene) {
  21822. var sphere = new BABYLON.Mesh(name, scene);
  21823. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21824. var vertexData = BABYLON.VertexData.CreateSphere(options);
  21825. vertexData.applyToMesh(sphere, options.updatable);
  21826. return sphere;
  21827. };
  21828. /**
  21829. * Creates a plane polygonal mesh. By default, this is a disc.
  21830. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  21831. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21832. * 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.
  21833. * 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
  21834. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21835. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21836. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21837. */
  21838. MeshBuilder.CreateDisc = function (name, options, scene) {
  21839. var disc = new BABYLON.Mesh(name, scene);
  21840. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21841. var vertexData = BABYLON.VertexData.CreateDisc(options);
  21842. vertexData.applyToMesh(disc, options.updatable);
  21843. return disc;
  21844. };
  21845. /**
  21846. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21847. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  21848. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21849. * 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`).
  21850. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21851. * 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.
  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. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  21857. var sphere = new BABYLON.Mesh(name, scene);
  21858. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21859. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  21860. vertexData.applyToMesh(sphere, options.updatable);
  21861. return sphere;
  21862. };
  21863. ;
  21864. /**
  21865. * Creates a ribbon mesh.
  21866. * 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.
  21867. *
  21868. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21869. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21870. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21871. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21872. * 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.
  21873. * 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.
  21874. * 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
  21875. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21876. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21877. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21878. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21879. */
  21880. MeshBuilder.CreateRibbon = function (name, options, scene) {
  21881. var pathArray = options.pathArray;
  21882. var closeArray = options.closeArray;
  21883. var closePath = options.closePath;
  21884. var offset = options.offset;
  21885. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21886. var instance = options.instance;
  21887. var updatable = options.updatable;
  21888. if (instance) {
  21889. // positionFunction : ribbon case
  21890. // only pathArray and sideOrientation parameters are taken into account for positions update
  21891. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  21892. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  21893. var positionFunction = function (positions) {
  21894. var minlg = pathArray[0].length;
  21895. var i = 0;
  21896. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  21897. for (var si = 1; si <= ns; si++) {
  21898. for (var p = 0; p < pathArray.length; p++) {
  21899. var path = pathArray[p];
  21900. var l = path.length;
  21901. minlg = (minlg < l) ? minlg : l;
  21902. var j = 0;
  21903. while (j < minlg) {
  21904. positions[i] = path[j].x;
  21905. positions[i + 1] = path[j].y;
  21906. positions[i + 2] = path[j].z;
  21907. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  21908. BABYLON.Tmp.Vector3[0].x = path[j].x;
  21909. }
  21910. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  21911. BABYLON.Tmp.Vector3[1].x = path[j].x;
  21912. }
  21913. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  21914. BABYLON.Tmp.Vector3[0].y = path[j].y;
  21915. }
  21916. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  21917. BABYLON.Tmp.Vector3[1].y = path[j].y;
  21918. }
  21919. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  21920. BABYLON.Tmp.Vector3[0].z = path[j].z;
  21921. }
  21922. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  21923. BABYLON.Tmp.Vector3[1].z = path[j].z;
  21924. }
  21925. j++;
  21926. i += 3;
  21927. }
  21928. if (instance._closePath) {
  21929. positions[i] = path[0].x;
  21930. positions[i + 1] = path[0].y;
  21931. positions[i + 2] = path[0].z;
  21932. i += 3;
  21933. }
  21934. }
  21935. }
  21936. };
  21937. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21938. positionFunction(positions);
  21939. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  21940. instance._boundingInfo.update(instance._worldMatrix);
  21941. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21942. if (!(instance.areNormalsFrozen)) {
  21943. var indices = instance.getIndices();
  21944. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21945. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21946. if (instance._closePath) {
  21947. var indexFirst = 0;
  21948. var indexLast = 0;
  21949. for (var p = 0; p < pathArray.length; p++) {
  21950. indexFirst = instance._idx[p] * 3;
  21951. if (p + 1 < pathArray.length) {
  21952. indexLast = (instance._idx[p + 1] - 1) * 3;
  21953. }
  21954. else {
  21955. indexLast = normals.length - 3;
  21956. }
  21957. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  21958. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  21959. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  21960. normals[indexLast] = normals[indexFirst];
  21961. normals[indexLast + 1] = normals[indexFirst + 1];
  21962. normals[indexLast + 2] = normals[indexFirst + 2];
  21963. }
  21964. }
  21965. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21966. }
  21967. return instance;
  21968. }
  21969. else {
  21970. var ribbon = new BABYLON.Mesh(name, scene);
  21971. ribbon.sideOrientation = sideOrientation;
  21972. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  21973. if (closePath) {
  21974. ribbon._idx = vertexData._idx;
  21975. }
  21976. ribbon._closePath = closePath;
  21977. ribbon._closeArray = closeArray;
  21978. vertexData.applyToMesh(ribbon, updatable);
  21979. return ribbon;
  21980. }
  21981. };
  21982. /**
  21983. * Creates a cylinder or a cone mesh.
  21984. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  21985. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21986. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21987. * 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.
  21988. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21989. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21990. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  21991. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  21992. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  21993. * 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).
  21994. * 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
  21995. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  21996. * 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
  21997. * 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.
  21998. * If `enclose` is false, a ring surface is one element.
  21999. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  22000. * 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
  22001. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22002. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22003. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22004. */
  22005. MeshBuilder.CreateCylinder = function (name, options, scene) {
  22006. var cylinder = new BABYLON.Mesh(name, scene);
  22007. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22008. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  22009. vertexData.applyToMesh(cylinder, options.updatable);
  22010. return cylinder;
  22011. };
  22012. /**
  22013. * Creates a torus mesh.
  22014. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  22015. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  22016. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  22017. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  22018. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22019. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22020. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22021. */
  22022. MeshBuilder.CreateTorus = function (name, options, scene) {
  22023. var torus = new BABYLON.Mesh(name, scene);
  22024. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22025. var vertexData = BABYLON.VertexData.CreateTorus(options);
  22026. vertexData.applyToMesh(torus, options.updatable);
  22027. return torus;
  22028. };
  22029. /**
  22030. * Creates a torus knot mesh.
  22031. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  22032. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  22033. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  22034. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  22035. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  22036. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22037. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22038. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22039. */
  22040. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  22041. var torusKnot = new BABYLON.Mesh(name, scene);
  22042. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22043. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  22044. vertexData.applyToMesh(torusKnot, options.updatable);
  22045. return torusKnot;
  22046. };
  22047. /**
  22048. * Creates a line system mesh.
  22049. * A line system is a pool of many lines gathered in a single mesh.
  22050. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  22051. * 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.
  22052. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  22053. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  22054. * 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
  22055. * 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
  22056. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  22057. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22058. */
  22059. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  22060. var instance = options.instance;
  22061. var lines = options.lines;
  22062. if (instance) {
  22063. var positionFunction = function (positions) {
  22064. var i = 0;
  22065. for (var l = 0; l < lines.length; l++) {
  22066. var points = lines[l];
  22067. for (var p = 0; p < points.length; p++) {
  22068. positions[i] = points[p].x;
  22069. positions[i + 1] = points[p].y;
  22070. positions[i + 2] = points[p].z;
  22071. i += 3;
  22072. }
  22073. }
  22074. };
  22075. instance.updateMeshPositions(positionFunction, false);
  22076. return instance;
  22077. }
  22078. // line system creation
  22079. var lineSystem = new BABYLON.LinesMesh(name, scene);
  22080. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  22081. vertexData.applyToMesh(lineSystem, options.updatable);
  22082. return lineSystem;
  22083. };
  22084. /**
  22085. * Creates a line mesh.
  22086. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  22087. * 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.
  22088. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22089. * The parameter `points` is an array successive Vector3.
  22090. * 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
  22091. * When updating an instance, remember that only point positions can change, not the number of points.
  22092. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22093. */
  22094. MeshBuilder.CreateLines = function (name, options, scene) {
  22095. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  22096. return lines;
  22097. };
  22098. /**
  22099. * Creates a dashed line mesh.
  22100. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  22101. * 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.
  22102. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22103. * The parameter `points` is an array successive Vector3.
  22104. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  22105. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  22106. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  22107. * 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
  22108. * When updating an instance, remember that only point positions can change, not the number of points.
  22109. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22110. */
  22111. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  22112. var points = options.points;
  22113. var instance = options.instance;
  22114. var gapSize = options.gapSize;
  22115. var dashNb = options.dashNb;
  22116. var dashSize = options.dashSize;
  22117. if (instance) {
  22118. var positionFunction = function (positions) {
  22119. var curvect = BABYLON.Vector3.Zero();
  22120. var nbSeg = positions.length / 6;
  22121. var lg = 0;
  22122. var nb = 0;
  22123. var shft = 0;
  22124. var dashshft = 0;
  22125. var curshft = 0;
  22126. var p = 0;
  22127. var i = 0;
  22128. var j = 0;
  22129. for (i = 0; i < points.length - 1; i++) {
  22130. points[i + 1].subtractToRef(points[i], curvect);
  22131. lg += curvect.length();
  22132. }
  22133. shft = lg / nbSeg;
  22134. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  22135. for (i = 0; i < points.length - 1; i++) {
  22136. points[i + 1].subtractToRef(points[i], curvect);
  22137. nb = Math.floor(curvect.length() / shft);
  22138. curvect.normalize();
  22139. j = 0;
  22140. while (j < nb && p < positions.length) {
  22141. curshft = shft * j;
  22142. positions[p] = points[i].x + curshft * curvect.x;
  22143. positions[p + 1] = points[i].y + curshft * curvect.y;
  22144. positions[p + 2] = points[i].z + curshft * curvect.z;
  22145. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  22146. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  22147. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  22148. p += 6;
  22149. j++;
  22150. }
  22151. }
  22152. while (p < positions.length) {
  22153. positions[p] = points[i].x;
  22154. positions[p + 1] = points[i].y;
  22155. positions[p + 2] = points[i].z;
  22156. p += 3;
  22157. }
  22158. };
  22159. instance.updateMeshPositions(positionFunction, false);
  22160. return instance;
  22161. }
  22162. // dashed lines creation
  22163. var dashedLines = new BABYLON.LinesMesh(name, scene);
  22164. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  22165. vertexData.applyToMesh(dashedLines, options.updatable);
  22166. dashedLines.dashSize = dashSize;
  22167. dashedLines.gapSize = gapSize;
  22168. return dashedLines;
  22169. };
  22170. /**
  22171. * Creates an extruded shape mesh.
  22172. * 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.
  22173. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  22174. *
  22175. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22176. * 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
  22177. * extruded along the Z axis.
  22178. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22179. * 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.
  22180. * The parameter `scale` (float, default 1) is the value to scale the shape.
  22181. * 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
  22182. * 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
  22183. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22184. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22185. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22186. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22187. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22188. */
  22189. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  22190. var path = options.path;
  22191. var shape = options.shape;
  22192. var scale = options.scale || 1;
  22193. var rotation = options.rotation || 0;
  22194. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  22195. var updatable = options.updatable;
  22196. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22197. var instance = options.instance;
  22198. var invertUV = options.invertUV || false;
  22199. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  22200. };
  22201. /**
  22202. * Creates an custom extruded shape mesh.
  22203. * 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.
  22204. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  22205. *
  22206. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22207. * 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
  22208. * extruded along the Z axis.
  22209. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22210. * 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
  22211. * and the distance of this point from the begining of the path :
  22212. * ```javascript
  22213. * var rotationFunction = function(i, distance) {
  22214. * // do things
  22215. * return rotationValue; }
  22216. * ```
  22217. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  22218. * 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
  22219. * and the distance of this point from the begining of the path :
  22220. * ```javascript
  22221. * var scaleFunction = function(i, distance) {
  22222. * // do things
  22223. * return scaleValue;}
  22224. * ```
  22225. * It must returns a float value that will be the scale value applied to the shape on each path point.
  22226. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  22227. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  22228. * 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
  22229. * 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
  22230. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22231. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22232. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22233. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22234. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22235. */
  22236. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  22237. var path = options.path;
  22238. var shape = options.shape;
  22239. var scaleFunction = options.scaleFunction || (function () { return 1; });
  22240. var rotationFunction = options.rotationFunction || (function () { return 0; });
  22241. var ribbonCloseArray = options.ribbonCloseArray || false;
  22242. var ribbonClosePath = options.ribbonClosePath || false;
  22243. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  22244. var updatable = options.updatable;
  22245. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22246. var instance = options.instance;
  22247. var invertUV = options.invertUV || false;
  22248. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  22249. };
  22250. /**
  22251. * Creates lathe mesh.
  22252. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  22253. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  22254. *
  22255. * 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
  22256. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  22257. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  22258. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  22259. * 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.
  22260. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  22261. * 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
  22262. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22263. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22264. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22265. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22266. */
  22267. MeshBuilder.CreateLathe = function (name, options, scene) {
  22268. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  22269. var closed = (options.closed === undefined) ? true : options.closed;
  22270. var shape = options.shape;
  22271. var radius = options.radius || 1;
  22272. var tessellation = options.tessellation || 64;
  22273. var updatable = options.updatable;
  22274. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22275. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22276. var pi2 = Math.PI * 2;
  22277. var paths = new Array();
  22278. var invertUV = options.invertUV || false;
  22279. var i = 0;
  22280. var p = 0;
  22281. var step = pi2 / tessellation * arc;
  22282. var rotated;
  22283. var path = new Array();
  22284. ;
  22285. for (i = 0; i <= tessellation; i++) {
  22286. var path = [];
  22287. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  22288. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  22289. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  22290. }
  22291. for (p = 0; p < shape.length; p++) {
  22292. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  22293. path.push(rotated);
  22294. }
  22295. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  22296. 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));
  22297. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  22298. }
  22299. paths.push(path);
  22300. }
  22301. // lathe ribbon
  22302. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  22303. return lathe;
  22304. };
  22305. /**
  22306. * Creates a plane mesh.
  22307. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22308. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22309. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  22310. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  22311. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22312. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22313. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22314. */
  22315. MeshBuilder.CreatePlane = function (name, options, scene) {
  22316. var plane = new BABYLON.Mesh(name, scene);
  22317. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22318. var vertexData = BABYLON.VertexData.CreatePlane(options);
  22319. vertexData.applyToMesh(plane, options.updatable);
  22320. if (options.sourcePlane) {
  22321. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  22322. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  22323. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  22324. plane.rotate(vectorProduct, product);
  22325. }
  22326. return plane;
  22327. };
  22328. /**
  22329. * Creates a ground mesh.
  22330. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22331. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22332. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22333. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22334. */
  22335. MeshBuilder.CreateGround = function (name, options, scene) {
  22336. var ground = new BABYLON.GroundMesh(name, scene);
  22337. ground._setReady(false);
  22338. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  22339. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  22340. ground._width = options.width || 1;
  22341. ground._height = options.height || 1;
  22342. ground._maxX = ground._width / 2;
  22343. ground._maxZ = ground._height / 2;
  22344. ground._minX = -ground._maxX;
  22345. ground._minZ = -ground._maxZ;
  22346. var vertexData = BABYLON.VertexData.CreateGround(options);
  22347. vertexData.applyToMesh(ground, options.updatable);
  22348. ground._setReady(true);
  22349. return ground;
  22350. };
  22351. /**
  22352. * Creates a tiled ground mesh.
  22353. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  22354. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22355. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22356. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22357. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22358. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22359. * numbers of subdivisions on the ground width and height of each tile.
  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.CreateTiledGround = function (name, options, scene) {
  22363. var tiledGround = new BABYLON.Mesh(name, scene);
  22364. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  22365. vertexData.applyToMesh(tiledGround, options.updatable);
  22366. return tiledGround;
  22367. };
  22368. /**
  22369. * Creates a ground mesh from a height map.
  22370. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22371. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  22372. * The parameter `url` sets the URL of the height map image resource.
  22373. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22374. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22375. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22376. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22377. * 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).
  22378. * This function is passed the newly built mesh :
  22379. * ```javascript
  22380. * function(mesh) { // do things
  22381. * return; }
  22382. * ```
  22383. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22384. */
  22385. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  22386. var width = options.width || 10.0;
  22387. var height = options.height || 10.0;
  22388. var subdivisions = options.subdivisions || 1 | 0;
  22389. var minHeight = options.minHeight || 0.0;
  22390. var maxHeight = options.maxHeight || 10.0;
  22391. var updatable = options.updatable;
  22392. var onReady = options.onReady;
  22393. var ground = new BABYLON.GroundMesh(name, scene);
  22394. ground._subdivisionsX = subdivisions;
  22395. ground._subdivisionsY = subdivisions;
  22396. ground._width = width;
  22397. ground._height = height;
  22398. ground._maxX = ground._width / 2.0;
  22399. ground._maxZ = ground._height / 2.0;
  22400. ground._minX = -ground._maxX;
  22401. ground._minZ = -ground._maxZ;
  22402. ground._setReady(false);
  22403. var onload = function (img) {
  22404. // Getting height map data
  22405. var canvas = document.createElement("canvas");
  22406. var context = canvas.getContext("2d");
  22407. var bufferWidth = img.width;
  22408. var bufferHeight = img.height;
  22409. canvas.width = bufferWidth;
  22410. canvas.height = bufferHeight;
  22411. context.drawImage(img, 0, 0);
  22412. // Create VertexData from map data
  22413. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22414. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  22415. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  22416. width: width, height: height,
  22417. subdivisions: subdivisions,
  22418. minHeight: minHeight, maxHeight: maxHeight,
  22419. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  22420. });
  22421. vertexData.applyToMesh(ground, updatable);
  22422. ground._setReady(true);
  22423. //execute ready callback, if set
  22424. if (onReady) {
  22425. onReady(ground);
  22426. }
  22427. };
  22428. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22429. return ground;
  22430. };
  22431. /**
  22432. * Creates a tube mesh.
  22433. * 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.
  22434. *
  22435. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  22436. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22437. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22438. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22439. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22440. * 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.
  22441. * It must return a radius value (positive float) :
  22442. * ```javascript
  22443. * var radiusFunction = function(i, distance) {
  22444. * // do things
  22445. * return radius; }
  22446. * ```
  22447. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  22448. * 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
  22449. * 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
  22450. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22451. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22452. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22453. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22454. */
  22455. MeshBuilder.CreateTube = function (name, options, scene) {
  22456. var path = options.path;
  22457. var radius = options.radius || 1.0;
  22458. var tessellation = options.tessellation || 64 | 0;
  22459. var radiusFunction = options.radiusFunction;
  22460. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22461. var invertUV = options.invertUV || false;
  22462. var updatable = options.updatable;
  22463. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22464. var instance = options.instance;
  22465. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  22466. // tube geometry
  22467. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  22468. var tangents = path3D.getTangents();
  22469. var normals = path3D.getNormals();
  22470. var distances = path3D.getDistances();
  22471. var pi2 = Math.PI * 2;
  22472. var step = pi2 / tessellation * arc;
  22473. var returnRadius = function () { return radius; };
  22474. var radiusFunctionFinal = radiusFunction || returnRadius;
  22475. var circlePath;
  22476. var rad;
  22477. var normal;
  22478. var rotated;
  22479. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22480. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22481. for (var i = 0; i < path.length; i++) {
  22482. rad = radiusFunctionFinal(i, distances[i]); // current radius
  22483. circlePath = Array(); // current circle array
  22484. normal = normals[i]; // current normal
  22485. for (var t = 0; t < tessellation; t++) {
  22486. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  22487. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  22488. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  22489. rotated.scaleInPlace(rad).addInPlace(path[i]);
  22490. circlePath[t] = rotated;
  22491. }
  22492. circlePaths[index] = circlePath;
  22493. index++;
  22494. }
  22495. // cap
  22496. var capPath = function (nbPoints, pathIndex) {
  22497. var pointCap = Array();
  22498. for (var i = 0; i < nbPoints; i++) {
  22499. pointCap.push(path[pathIndex]);
  22500. }
  22501. return pointCap;
  22502. };
  22503. switch (cap) {
  22504. case BABYLON.Mesh.NO_CAP:
  22505. break;
  22506. case BABYLON.Mesh.CAP_START:
  22507. circlePaths[0] = capPath(tessellation, 0);
  22508. circlePaths[1] = circlePaths[2].slice(0);
  22509. break;
  22510. case BABYLON.Mesh.CAP_END:
  22511. circlePaths[index] = circlePaths[index - 1].slice(0);
  22512. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22513. break;
  22514. case BABYLON.Mesh.CAP_ALL:
  22515. circlePaths[0] = capPath(tessellation, 0);
  22516. circlePaths[1] = circlePaths[2].slice(0);
  22517. circlePaths[index] = circlePaths[index - 1].slice(0);
  22518. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22519. break;
  22520. default:
  22521. break;
  22522. }
  22523. return circlePaths;
  22524. };
  22525. var path3D;
  22526. var pathArray;
  22527. if (instance) {
  22528. var arc = options.arc || instance.arc;
  22529. path3D = (instance.path3D).update(path);
  22530. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  22531. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  22532. instance.path3D = path3D;
  22533. instance.pathArray = pathArray;
  22534. instance.arc = arc;
  22535. return instance;
  22536. }
  22537. // tube creation
  22538. path3D = new BABYLON.Path3D(path);
  22539. var newPathArray = new Array();
  22540. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22541. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  22542. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  22543. tube.pathArray = pathArray;
  22544. tube.path3D = path3D;
  22545. tube.tessellation = tessellation;
  22546. tube.cap = cap;
  22547. tube.arc = options.arc;
  22548. return tube;
  22549. };
  22550. /**
  22551. * Creates a polyhedron mesh.
  22552. *
  22553. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  22554. * 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
  22555. * to choose the wanted type.
  22556. * The parameter `size` (positive float, default 1) sets the polygon size.
  22557. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22558. * 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`.
  22559. * 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
  22560. * 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)`).
  22561. * 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
  22562. * 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.
  22563. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22564. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22565. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22566. */
  22567. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  22568. var polyhedron = new BABYLON.Mesh(name, scene);
  22569. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22570. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  22571. vertexData.applyToMesh(polyhedron, options.updatable);
  22572. return polyhedron;
  22573. };
  22574. /**
  22575. * Creates a decal mesh.
  22576. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  22577. * 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.
  22578. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22579. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22580. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22581. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22582. */
  22583. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  22584. var indices = sourceMesh.getIndices();
  22585. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22586. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22587. var position = options.position || BABYLON.Vector3.Zero();
  22588. var normal = options.normal || BABYLON.Vector3.Up();
  22589. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  22590. var angle = options.angle || 0;
  22591. // Getting correct rotation
  22592. if (!normal) {
  22593. var target = new BABYLON.Vector3(0, 0, 1);
  22594. var camera = sourceMesh.getScene().activeCamera;
  22595. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  22596. normal = camera.globalPosition.subtract(cameraWorldTarget);
  22597. }
  22598. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  22599. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  22600. var pitch = Math.atan2(normal.y, len);
  22601. // Matrix
  22602. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  22603. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  22604. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  22605. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  22606. var vertexData = new BABYLON.VertexData();
  22607. vertexData.indices = [];
  22608. vertexData.positions = [];
  22609. vertexData.normals = [];
  22610. vertexData.uvs = [];
  22611. var currentVertexDataIndex = 0;
  22612. var extractDecalVector3 = function (indexId) {
  22613. var vertexId = indices[indexId];
  22614. var result = new BABYLON.PositionNormalVertex();
  22615. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  22616. // Send vector to decal local world
  22617. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  22618. // Get normal
  22619. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  22620. return result;
  22621. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  22622. var clip = function (vertices, axis) {
  22623. if (vertices.length === 0) {
  22624. return vertices;
  22625. }
  22626. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  22627. var clipVertices = function (v0, v1) {
  22628. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  22629. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  22630. };
  22631. var result = new Array();
  22632. for (var index = 0; index < vertices.length; index += 3) {
  22633. var v1Out;
  22634. var v2Out;
  22635. var v3Out;
  22636. var total = 0;
  22637. var nV1, nV2, nV3, nV4;
  22638. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  22639. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  22640. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  22641. v1Out = d1 > 0;
  22642. v2Out = d2 > 0;
  22643. v3Out = d3 > 0;
  22644. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  22645. switch (total) {
  22646. case 0:
  22647. result.push(vertices[index]);
  22648. result.push(vertices[index + 1]);
  22649. result.push(vertices[index + 2]);
  22650. break;
  22651. case 1:
  22652. if (v1Out) {
  22653. nV1 = vertices[index + 1];
  22654. nV2 = vertices[index + 2];
  22655. nV3 = clipVertices(vertices[index], nV1);
  22656. nV4 = clipVertices(vertices[index], nV2);
  22657. }
  22658. if (v2Out) {
  22659. nV1 = vertices[index];
  22660. nV2 = vertices[index + 2];
  22661. nV3 = clipVertices(vertices[index + 1], nV1);
  22662. nV4 = clipVertices(vertices[index + 1], nV2);
  22663. result.push(nV3);
  22664. result.push(nV2.clone());
  22665. result.push(nV1.clone());
  22666. result.push(nV2.clone());
  22667. result.push(nV3.clone());
  22668. result.push(nV4);
  22669. break;
  22670. }
  22671. if (v3Out) {
  22672. nV1 = vertices[index];
  22673. nV2 = vertices[index + 1];
  22674. nV3 = clipVertices(vertices[index + 2], nV1);
  22675. nV4 = clipVertices(vertices[index + 2], nV2);
  22676. }
  22677. result.push(nV1.clone());
  22678. result.push(nV2.clone());
  22679. result.push(nV3);
  22680. result.push(nV4);
  22681. result.push(nV3.clone());
  22682. result.push(nV2.clone());
  22683. break;
  22684. case 2:
  22685. if (!v1Out) {
  22686. nV1 = vertices[index].clone();
  22687. nV2 = clipVertices(nV1, vertices[index + 1]);
  22688. nV3 = clipVertices(nV1, vertices[index + 2]);
  22689. result.push(nV1);
  22690. result.push(nV2);
  22691. result.push(nV3);
  22692. }
  22693. if (!v2Out) {
  22694. nV1 = vertices[index + 1].clone();
  22695. nV2 = clipVertices(nV1, vertices[index + 2]);
  22696. nV3 = clipVertices(nV1, vertices[index]);
  22697. result.push(nV1);
  22698. result.push(nV2);
  22699. result.push(nV3);
  22700. }
  22701. if (!v3Out) {
  22702. nV1 = vertices[index + 2].clone();
  22703. nV2 = clipVertices(nV1, vertices[index]);
  22704. nV3 = clipVertices(nV1, vertices[index + 1]);
  22705. result.push(nV1);
  22706. result.push(nV2);
  22707. result.push(nV3);
  22708. }
  22709. break;
  22710. case 3:
  22711. break;
  22712. }
  22713. }
  22714. return result;
  22715. };
  22716. for (var index = 0; index < indices.length; index += 3) {
  22717. var faceVertices = new Array();
  22718. faceVertices.push(extractDecalVector3(index));
  22719. faceVertices.push(extractDecalVector3(index + 1));
  22720. faceVertices.push(extractDecalVector3(index + 2));
  22721. // Clip
  22722. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  22723. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  22724. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  22725. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  22726. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  22727. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  22728. if (faceVertices.length === 0) {
  22729. continue;
  22730. }
  22731. // Add UVs and get back to world
  22732. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  22733. var vertex = faceVertices[vIndex];
  22734. //TODO check for Int32Array
  22735. vertexData.indices.push(currentVertexDataIndex);
  22736. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  22737. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  22738. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  22739. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  22740. currentVertexDataIndex++;
  22741. }
  22742. }
  22743. // Return mesh
  22744. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  22745. vertexData.applyToMesh(decal);
  22746. decal.position = position.clone();
  22747. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  22748. return decal;
  22749. };
  22750. // Privates
  22751. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  22752. // extrusion geometry
  22753. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  22754. var tangents = path3D.getTangents();
  22755. var normals = path3D.getNormals();
  22756. var binormals = path3D.getBinormals();
  22757. var distances = path3D.getDistances();
  22758. var angle = 0;
  22759. var returnScale = function () { return scale; };
  22760. var returnRotation = function () { return rotation; };
  22761. var rotate = custom ? rotateFunction : returnRotation;
  22762. var scl = custom ? scaleFunction : returnScale;
  22763. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22764. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22765. for (var i = 0; i < curve.length; i++) {
  22766. var shapePath = new Array();
  22767. var angleStep = rotate(i, distances[i]);
  22768. var scaleRatio = scl(i, distances[i]);
  22769. for (var p = 0; p < shape.length; p++) {
  22770. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  22771. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  22772. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  22773. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  22774. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  22775. shapePath[p] = rotated;
  22776. }
  22777. shapePaths[index] = shapePath;
  22778. angle += angleStep;
  22779. index++;
  22780. }
  22781. // cap
  22782. var capPath = function (shapePath) {
  22783. var pointCap = Array();
  22784. var barycenter = BABYLON.Vector3.Zero();
  22785. var i;
  22786. for (i = 0; i < shapePath.length; i++) {
  22787. barycenter.addInPlace(shapePath[i]);
  22788. }
  22789. barycenter.scaleInPlace(1 / shapePath.length);
  22790. for (i = 0; i < shapePath.length; i++) {
  22791. pointCap.push(barycenter);
  22792. }
  22793. return pointCap;
  22794. };
  22795. switch (cap) {
  22796. case BABYLON.Mesh.NO_CAP:
  22797. break;
  22798. case BABYLON.Mesh.CAP_START:
  22799. shapePaths[0] = capPath(shapePaths[2]);
  22800. shapePaths[1] = shapePaths[2].slice(0);
  22801. break;
  22802. case BABYLON.Mesh.CAP_END:
  22803. shapePaths[index] = shapePaths[index - 1];
  22804. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  22805. break;
  22806. case BABYLON.Mesh.CAP_ALL:
  22807. shapePaths[0] = capPath(shapePaths[2]);
  22808. shapePaths[1] = shapePaths[2].slice(0);
  22809. shapePaths[index] = shapePaths[index - 1];
  22810. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  22811. break;
  22812. default:
  22813. break;
  22814. }
  22815. return shapePaths;
  22816. };
  22817. var path3D;
  22818. var pathArray;
  22819. if (instance) {
  22820. path3D = (instance.path3D).update(curve);
  22821. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  22822. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  22823. return instance;
  22824. }
  22825. // extruded shape creation
  22826. path3D = new BABYLON.Path3D(curve);
  22827. var newShapePaths = new Array();
  22828. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22829. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  22830. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  22831. extrudedGeneric.pathArray = pathArray;
  22832. extrudedGeneric.path3D = path3D;
  22833. extrudedGeneric.cap = cap;
  22834. return extrudedGeneric;
  22835. };
  22836. return MeshBuilder;
  22837. }());
  22838. BABYLON.MeshBuilder = MeshBuilder;
  22839. })(BABYLON || (BABYLON = {}));
  22840. var BABYLON;
  22841. (function (BABYLON) {
  22842. var BaseTexture = (function () {
  22843. function BaseTexture(scene) {
  22844. this.hasAlpha = false;
  22845. this.getAlphaFromRGB = false;
  22846. this.level = 1;
  22847. this.coordinatesIndex = 0;
  22848. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  22849. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22850. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22851. this.anisotropicFilteringLevel = 4;
  22852. this.isCube = false;
  22853. this.isRenderTarget = false;
  22854. this.animations = new Array();
  22855. /**
  22856. * An event triggered when the texture is disposed.
  22857. * @type {BABYLON.Observable}
  22858. */
  22859. this.onDisposeObservable = new BABYLON.Observable();
  22860. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22861. this._scene = scene;
  22862. this._scene.textures.push(this);
  22863. this._uid = null;
  22864. }
  22865. Object.defineProperty(BaseTexture.prototype, "uid", {
  22866. get: function () {
  22867. if (!this._uid) {
  22868. this._uid = BABYLON.Tools.RandomId();
  22869. }
  22870. return this._uid;
  22871. },
  22872. enumerable: true,
  22873. configurable: true
  22874. });
  22875. BaseTexture.prototype.toString = function () {
  22876. return this.name;
  22877. };
  22878. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  22879. set: function (callback) {
  22880. if (this._onDisposeObserver) {
  22881. this.onDisposeObservable.remove(this._onDisposeObserver);
  22882. }
  22883. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22884. },
  22885. enumerable: true,
  22886. configurable: true
  22887. });
  22888. BaseTexture.prototype.getScene = function () {
  22889. return this._scene;
  22890. };
  22891. BaseTexture.prototype.getTextureMatrix = function () {
  22892. return null;
  22893. };
  22894. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  22895. return null;
  22896. };
  22897. BaseTexture.prototype.getInternalTexture = function () {
  22898. return this._texture;
  22899. };
  22900. BaseTexture.prototype.isReady = function () {
  22901. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22902. return true;
  22903. }
  22904. if (this._texture) {
  22905. return this._texture.isReady;
  22906. }
  22907. return false;
  22908. };
  22909. BaseTexture.prototype.getSize = function () {
  22910. if (this._texture._width) {
  22911. return new BABYLON.Size(this._texture._width, this._texture._height);
  22912. }
  22913. if (this._texture._size) {
  22914. return new BABYLON.Size(this._texture._size, this._texture._size);
  22915. }
  22916. return BABYLON.Size.Zero();
  22917. };
  22918. BaseTexture.prototype.getBaseSize = function () {
  22919. if (!this.isReady() || !this._texture)
  22920. return BABYLON.Size.Zero();
  22921. if (this._texture._size) {
  22922. return new BABYLON.Size(this._texture._size, this._texture._size);
  22923. }
  22924. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  22925. };
  22926. BaseTexture.prototype.scale = function (ratio) {
  22927. };
  22928. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22929. get: function () {
  22930. return false;
  22931. },
  22932. enumerable: true,
  22933. configurable: true
  22934. });
  22935. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  22936. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22937. for (var index = 0; index < texturesCache.length; index++) {
  22938. var texturesCacheEntry = texturesCache[index];
  22939. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22940. texturesCache.splice(index, 1);
  22941. return;
  22942. }
  22943. }
  22944. };
  22945. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22946. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22947. for (var index = 0; index < texturesCache.length; index++) {
  22948. var texturesCacheEntry = texturesCache[index];
  22949. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22950. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22951. texturesCacheEntry.references++;
  22952. return texturesCacheEntry;
  22953. }
  22954. }
  22955. }
  22956. return null;
  22957. };
  22958. BaseTexture.prototype.delayLoad = function () {
  22959. };
  22960. BaseTexture.prototype.clone = function () {
  22961. return null;
  22962. };
  22963. BaseTexture.prototype.releaseInternalTexture = function () {
  22964. if (this._texture) {
  22965. this._scene.getEngine().releaseInternalTexture(this._texture);
  22966. delete this._texture;
  22967. }
  22968. };
  22969. BaseTexture.prototype.dispose = function () {
  22970. // Animations
  22971. this.getScene().stopAnimation(this);
  22972. // Remove from scene
  22973. var index = this._scene.textures.indexOf(this);
  22974. if (index >= 0) {
  22975. this._scene.textures.splice(index, 1);
  22976. }
  22977. if (this._texture === undefined) {
  22978. return;
  22979. }
  22980. // Release
  22981. this.releaseInternalTexture();
  22982. // Callback
  22983. this.onDisposeObservable.notifyObservers(this);
  22984. this.onDisposeObservable.clear();
  22985. };
  22986. BaseTexture.prototype.serialize = function () {
  22987. if (!this.name) {
  22988. return null;
  22989. }
  22990. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22991. // Animations
  22992. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22993. return serializationObject;
  22994. };
  22995. __decorate([
  22996. BABYLON.serialize()
  22997. ], BaseTexture.prototype, "name", void 0);
  22998. __decorate([
  22999. BABYLON.serialize()
  23000. ], BaseTexture.prototype, "hasAlpha", void 0);
  23001. __decorate([
  23002. BABYLON.serialize()
  23003. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  23004. __decorate([
  23005. BABYLON.serialize()
  23006. ], BaseTexture.prototype, "level", void 0);
  23007. __decorate([
  23008. BABYLON.serialize()
  23009. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  23010. __decorate([
  23011. BABYLON.serialize()
  23012. ], BaseTexture.prototype, "coordinatesMode", void 0);
  23013. __decorate([
  23014. BABYLON.serialize()
  23015. ], BaseTexture.prototype, "wrapU", void 0);
  23016. __decorate([
  23017. BABYLON.serialize()
  23018. ], BaseTexture.prototype, "wrapV", void 0);
  23019. __decorate([
  23020. BABYLON.serialize()
  23021. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  23022. __decorate([
  23023. BABYLON.serialize()
  23024. ], BaseTexture.prototype, "isCube", void 0);
  23025. __decorate([
  23026. BABYLON.serialize()
  23027. ], BaseTexture.prototype, "isRenderTarget", void 0);
  23028. return BaseTexture;
  23029. }());
  23030. BABYLON.BaseTexture = BaseTexture;
  23031. })(BABYLON || (BABYLON = {}));
  23032. var BABYLON;
  23033. (function (BABYLON) {
  23034. var Texture = (function (_super) {
  23035. __extends(Texture, _super);
  23036. function Texture(urlOrList, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  23037. var _this = this;
  23038. if (noMipmap === void 0) { noMipmap = false; }
  23039. if (invertY === void 0) { invertY = true; }
  23040. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23041. if (onLoad === void 0) { onLoad = null; }
  23042. if (onError === void 0) { onError = null; }
  23043. if (buffer === void 0) { buffer = null; }
  23044. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23045. _super.call(this, scene);
  23046. this.uOffset = 0;
  23047. this.vOffset = 0;
  23048. this.uScale = 1.0;
  23049. this.vScale = 1.0;
  23050. this.uAng = 0;
  23051. this.vAng = 0;
  23052. this.wAng = 0;
  23053. var url = ((urlOrList instanceof Array) ? urlOrList[0] : urlOrList);
  23054. this.name = url;
  23055. this.url = url;
  23056. this._delayReloadData = urlOrList;
  23057. this._noMipmap = noMipmap;
  23058. this._invertY = invertY;
  23059. this._samplingMode = samplingMode;
  23060. this._buffer = buffer;
  23061. this._deleteBuffer = deleteBuffer;
  23062. if (!url) {
  23063. return;
  23064. }
  23065. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  23066. var load = function () {
  23067. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  23068. _this.onLoadObservable.notifyObservers(true);
  23069. }
  23070. if (onLoad) {
  23071. onLoad();
  23072. }
  23073. };
  23074. if (!this._texture) {
  23075. if (!scene.useDelayedTextureLoading) {
  23076. this._texture = scene.getEngine().createTexture(urlOrList, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
  23077. if (deleteBuffer) {
  23078. delete this._buffer;
  23079. }
  23080. }
  23081. else {
  23082. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23083. this._delayedOnLoad = load;
  23084. this._delayedOnError = onError;
  23085. }
  23086. }
  23087. else {
  23088. if (this._texture.isReady) {
  23089. BABYLON.Tools.SetImmediate(function () { return load(); });
  23090. }
  23091. else {
  23092. this._texture.onLoadedCallbacks.push(load);
  23093. }
  23094. }
  23095. }
  23096. Object.defineProperty(Texture.prototype, "noMipmap", {
  23097. get: function () {
  23098. return this._noMipmap;
  23099. },
  23100. enumerable: true,
  23101. configurable: true
  23102. });
  23103. Texture.prototype.delayLoad = function () {
  23104. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23105. return;
  23106. }
  23107. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23108. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  23109. if (!this._texture) {
  23110. this._texture = this.getScene().getEngine().createTexture(this._delayReloadData, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  23111. if (this._deleteBuffer) {
  23112. delete this._buffer;
  23113. }
  23114. }
  23115. };
  23116. Texture.prototype.updateSamplingMode = function (samplingMode) {
  23117. if (!this._texture) {
  23118. return;
  23119. }
  23120. this._samplingMode = samplingMode;
  23121. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  23122. };
  23123. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  23124. x *= this.uScale;
  23125. y *= this.vScale;
  23126. x -= 0.5 * this.uScale;
  23127. y -= 0.5 * this.vScale;
  23128. z -= 0.5;
  23129. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  23130. t.x += 0.5 * this.uScale + this.uOffset;
  23131. t.y += 0.5 * this.vScale + this.vOffset;
  23132. t.z += 0.5;
  23133. };
  23134. Texture.prototype.getTextureMatrix = function () {
  23135. if (this.uOffset === this._cachedUOffset &&
  23136. this.vOffset === this._cachedVOffset &&
  23137. this.uScale === this._cachedUScale &&
  23138. this.vScale === this._cachedVScale &&
  23139. this.uAng === this._cachedUAng &&
  23140. this.vAng === this._cachedVAng &&
  23141. this.wAng === this._cachedWAng) {
  23142. return this._cachedTextureMatrix;
  23143. }
  23144. this._cachedUOffset = this.uOffset;
  23145. this._cachedVOffset = this.vOffset;
  23146. this._cachedUScale = this.uScale;
  23147. this._cachedVScale = this.vScale;
  23148. this._cachedUAng = this.uAng;
  23149. this._cachedVAng = this.vAng;
  23150. this._cachedWAng = this.wAng;
  23151. if (!this._cachedTextureMatrix) {
  23152. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23153. this._rowGenerationMatrix = new BABYLON.Matrix();
  23154. this._t0 = BABYLON.Vector3.Zero();
  23155. this._t1 = BABYLON.Vector3.Zero();
  23156. this._t2 = BABYLON.Vector3.Zero();
  23157. }
  23158. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  23159. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  23160. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  23161. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  23162. this._t1.subtractInPlace(this._t0);
  23163. this._t2.subtractInPlace(this._t0);
  23164. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23165. this._cachedTextureMatrix.m[0] = this._t1.x;
  23166. this._cachedTextureMatrix.m[1] = this._t1.y;
  23167. this._cachedTextureMatrix.m[2] = this._t1.z;
  23168. this._cachedTextureMatrix.m[4] = this._t2.x;
  23169. this._cachedTextureMatrix.m[5] = this._t2.y;
  23170. this._cachedTextureMatrix.m[6] = this._t2.z;
  23171. this._cachedTextureMatrix.m[8] = this._t0.x;
  23172. this._cachedTextureMatrix.m[9] = this._t0.y;
  23173. this._cachedTextureMatrix.m[10] = this._t0.z;
  23174. return this._cachedTextureMatrix;
  23175. };
  23176. Texture.prototype.getReflectionTextureMatrix = function () {
  23177. if (this.uOffset === this._cachedUOffset &&
  23178. this.vOffset === this._cachedVOffset &&
  23179. this.uScale === this._cachedUScale &&
  23180. this.vScale === this._cachedVScale &&
  23181. this.coordinatesMode === this._cachedCoordinatesMode) {
  23182. return this._cachedTextureMatrix;
  23183. }
  23184. if (!this._cachedTextureMatrix) {
  23185. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23186. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  23187. }
  23188. this._cachedCoordinatesMode = this.coordinatesMode;
  23189. switch (this.coordinatesMode) {
  23190. case Texture.PLANAR_MODE:
  23191. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23192. this._cachedTextureMatrix[0] = this.uScale;
  23193. this._cachedTextureMatrix[5] = this.vScale;
  23194. this._cachedTextureMatrix[12] = this.uOffset;
  23195. this._cachedTextureMatrix[13] = this.vOffset;
  23196. break;
  23197. case Texture.PROJECTION_MODE:
  23198. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  23199. this._projectionModeMatrix.m[0] = 0.5;
  23200. this._projectionModeMatrix.m[5] = -0.5;
  23201. this._projectionModeMatrix.m[10] = 0.0;
  23202. this._projectionModeMatrix.m[12] = 0.5;
  23203. this._projectionModeMatrix.m[13] = 0.5;
  23204. this._projectionModeMatrix.m[14] = 1.0;
  23205. this._projectionModeMatrix.m[15] = 1.0;
  23206. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  23207. break;
  23208. default:
  23209. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23210. break;
  23211. }
  23212. return this._cachedTextureMatrix;
  23213. };
  23214. Texture.prototype.clone = function () {
  23215. var _this = this;
  23216. return BABYLON.SerializationHelper.Clone(function () {
  23217. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  23218. }, this);
  23219. };
  23220. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  23221. get: function () {
  23222. if (!this._onLoadObservarble) {
  23223. this._onLoadObservarble = new BABYLON.Observable();
  23224. }
  23225. return this._onLoadObservarble;
  23226. },
  23227. enumerable: true,
  23228. configurable: true
  23229. });
  23230. // Statics
  23231. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  23232. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23233. if (onLoad === void 0) { onLoad = null; }
  23234. if (onError === void 0) { onError = null; }
  23235. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  23236. };
  23237. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  23238. if (parsedTexture.customType) {
  23239. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  23240. return customTexture.Parse(parsedTexture, scene, rootUrl);
  23241. }
  23242. if (parsedTexture.isCube) {
  23243. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  23244. }
  23245. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  23246. return null;
  23247. }
  23248. var texture = BABYLON.SerializationHelper.Parse(function () {
  23249. if (parsedTexture.mirrorPlane) {
  23250. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  23251. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  23252. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  23253. return mirrorTexture;
  23254. }
  23255. else if (parsedTexture.isRenderTarget) {
  23256. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  23257. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  23258. return renderTargetTexture;
  23259. }
  23260. else {
  23261. var texture;
  23262. if (parsedTexture.base64String) {
  23263. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  23264. }
  23265. else if (parsedTexture.name instanceof Array) {
  23266. for (var i = 0, len = parsedTexture.name.length; i < len; i++) {
  23267. parsedTexture.name[i] = rootUrl + parsedTexture.name[i];
  23268. }
  23269. texture = new Texture(parsedTexture.name, scene);
  23270. }
  23271. else {
  23272. texture = new Texture(rootUrl + parsedTexture.name, scene);
  23273. }
  23274. return texture;
  23275. }
  23276. }, parsedTexture, scene);
  23277. // Animations
  23278. if (parsedTexture.animations) {
  23279. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23280. var parsedAnimation = parsedTexture.animations[animationIndex];
  23281. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23282. }
  23283. }
  23284. return texture;
  23285. };
  23286. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError) {
  23287. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23288. if (noMipmap === void 0) { noMipmap = false; }
  23289. if (invertY === void 0) { invertY = true; }
  23290. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23291. if (onLoad === void 0) { onLoad = null; }
  23292. if (onError === void 0) { onError = null; }
  23293. if (name.substr(0, 5) !== "data:") {
  23294. name = "data:" + name;
  23295. }
  23296. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer);
  23297. };
  23298. // Constants
  23299. Texture.NEAREST_SAMPLINGMODE = 1;
  23300. Texture.BILINEAR_SAMPLINGMODE = 2;
  23301. Texture.TRILINEAR_SAMPLINGMODE = 3;
  23302. Texture.EXPLICIT_MODE = 0;
  23303. Texture.SPHERICAL_MODE = 1;
  23304. Texture.PLANAR_MODE = 2;
  23305. Texture.CUBIC_MODE = 3;
  23306. Texture.PROJECTION_MODE = 4;
  23307. Texture.SKYBOX_MODE = 5;
  23308. Texture.INVCUBIC_MODE = 6;
  23309. Texture.EQUIRECTANGULAR_MODE = 7;
  23310. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  23311. Texture.CLAMP_ADDRESSMODE = 0;
  23312. Texture.WRAP_ADDRESSMODE = 1;
  23313. Texture.MIRROR_ADDRESSMODE = 2;
  23314. __decorate([
  23315. BABYLON.serialize()
  23316. ], Texture.prototype, "url", void 0);
  23317. __decorate([
  23318. BABYLON.serialize()
  23319. ], Texture.prototype, "uOffset", void 0);
  23320. __decorate([
  23321. BABYLON.serialize()
  23322. ], Texture.prototype, "vOffset", void 0);
  23323. __decorate([
  23324. BABYLON.serialize()
  23325. ], Texture.prototype, "uScale", void 0);
  23326. __decorate([
  23327. BABYLON.serialize()
  23328. ], Texture.prototype, "vScale", void 0);
  23329. __decorate([
  23330. BABYLON.serialize()
  23331. ], Texture.prototype, "uAng", void 0);
  23332. __decorate([
  23333. BABYLON.serialize()
  23334. ], Texture.prototype, "vAng", void 0);
  23335. __decorate([
  23336. BABYLON.serialize()
  23337. ], Texture.prototype, "wAng", void 0);
  23338. return Texture;
  23339. }(BABYLON.BaseTexture));
  23340. BABYLON.Texture = Texture;
  23341. })(BABYLON || (BABYLON = {}));
  23342. var BABYLON;
  23343. (function (BABYLON) {
  23344. var CubeTexture = (function (_super) {
  23345. __extends(CubeTexture, _super);
  23346. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError) {
  23347. if (onLoad === void 0) { onLoad = null; }
  23348. if (onError === void 0) { onError = null; }
  23349. _super.call(this, scene);
  23350. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  23351. this.name = rootUrl;
  23352. this.url = rootUrl;
  23353. this._noMipmap = noMipmap;
  23354. this.hasAlpha = false;
  23355. if (!rootUrl && !files) {
  23356. return;
  23357. }
  23358. this._texture = this._getFromCache(rootUrl, noMipmap);
  23359. if (!files) {
  23360. if (!extensions) {
  23361. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  23362. }
  23363. files = [];
  23364. for (var index = 0; index < extensions.length; index++) {
  23365. files.push(rootUrl + extensions[index]);
  23366. }
  23367. this._extensions = extensions;
  23368. }
  23369. this._files = files;
  23370. if (!this._texture) {
  23371. if (!scene.useDelayedTextureLoading) {
  23372. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError);
  23373. }
  23374. else {
  23375. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23376. }
  23377. }
  23378. else if (onLoad) {
  23379. if (this._texture.isReady) {
  23380. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  23381. }
  23382. else {
  23383. this._texture.onLoadedCallbacks.push(onLoad);
  23384. }
  23385. }
  23386. this.isCube = true;
  23387. this._textureMatrix = BABYLON.Matrix.Identity();
  23388. }
  23389. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  23390. return new CubeTexture("", scene, null, noMipmap, files);
  23391. };
  23392. // Methods
  23393. CubeTexture.prototype.delayLoad = function () {
  23394. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23395. return;
  23396. }
  23397. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23398. this._texture = this._getFromCache(this.url, this._noMipmap);
  23399. if (!this._texture) {
  23400. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  23401. }
  23402. };
  23403. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  23404. return this._textureMatrix;
  23405. };
  23406. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  23407. var texture = BABYLON.SerializationHelper.Parse(function () {
  23408. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  23409. }, parsedTexture, scene);
  23410. // Animations
  23411. if (parsedTexture.animations) {
  23412. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23413. var parsedAnimation = parsedTexture.animations[animationIndex];
  23414. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23415. }
  23416. }
  23417. return texture;
  23418. };
  23419. CubeTexture.prototype.clone = function () {
  23420. var _this = this;
  23421. return BABYLON.SerializationHelper.Clone(function () {
  23422. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  23423. }, this);
  23424. };
  23425. return CubeTexture;
  23426. }(BABYLON.BaseTexture));
  23427. BABYLON.CubeTexture = CubeTexture;
  23428. })(BABYLON || (BABYLON = {}));
  23429. var BABYLON;
  23430. (function (BABYLON) {
  23431. var RenderTargetTexture = (function (_super) {
  23432. __extends(RenderTargetTexture, _super);
  23433. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  23434. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  23435. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23436. if (isCube === void 0) { isCube = false; }
  23437. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23438. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  23439. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  23440. _super.call(this, null, scene, !generateMipMaps);
  23441. this.isCube = isCube;
  23442. /**
  23443. * Use this list to define the list of mesh you want to render.
  23444. */
  23445. this.renderList = new Array();
  23446. this.renderParticles = true;
  23447. this.renderSprites = false;
  23448. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  23449. // Events
  23450. /**
  23451. * An event triggered when the texture is unbind.
  23452. * @type {BABYLON.Observable}
  23453. */
  23454. this.onAfterUnbindObservable = new BABYLON.Observable();
  23455. /**
  23456. * An event triggered before rendering the texture
  23457. * @type {BABYLON.Observable}
  23458. */
  23459. this.onBeforeRenderObservable = new BABYLON.Observable();
  23460. /**
  23461. * An event triggered after rendering the texture
  23462. * @type {BABYLON.Observable}
  23463. */
  23464. this.onAfterRenderObservable = new BABYLON.Observable();
  23465. /**
  23466. * An event triggered after the texture clear
  23467. * @type {BABYLON.Observable}
  23468. */
  23469. this.onClearObservable = new BABYLON.Observable();
  23470. this._currentRefreshId = -1;
  23471. this._refreshRate = 1;
  23472. this.name = name;
  23473. this.isRenderTarget = true;
  23474. this._size = size;
  23475. this._generateMipMaps = generateMipMaps;
  23476. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  23477. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  23478. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23479. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23480. }
  23481. if (isCube) {
  23482. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, {
  23483. generateMipMaps: generateMipMaps,
  23484. samplingMode: samplingMode,
  23485. generateDepthBuffer: generateDepthBuffer,
  23486. generateStencilBuffer: generateStencilBuffer
  23487. });
  23488. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  23489. this._textureMatrix = BABYLON.Matrix.Identity();
  23490. }
  23491. else {
  23492. this._texture = scene.getEngine().createRenderTargetTexture(size, {
  23493. generateMipMaps: generateMipMaps,
  23494. type: type,
  23495. samplingMode: samplingMode,
  23496. generateDepthBuffer: generateDepthBuffer,
  23497. generateStencilBuffer: generateStencilBuffer
  23498. });
  23499. }
  23500. // Rendering groups
  23501. this._renderingManager = new BABYLON.RenderingManager(scene);
  23502. }
  23503. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  23504. get: function () {
  23505. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  23506. },
  23507. enumerable: true,
  23508. configurable: true
  23509. });
  23510. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  23511. get: function () {
  23512. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  23513. },
  23514. enumerable: true,
  23515. configurable: true
  23516. });
  23517. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  23518. get: function () {
  23519. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  23520. },
  23521. enumerable: true,
  23522. configurable: true
  23523. });
  23524. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  23525. set: function (callback) {
  23526. if (this._onAfterUnbindObserver) {
  23527. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  23528. }
  23529. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  23530. },
  23531. enumerable: true,
  23532. configurable: true
  23533. });
  23534. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  23535. set: function (callback) {
  23536. if (this._onBeforeRenderObserver) {
  23537. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23538. }
  23539. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23540. },
  23541. enumerable: true,
  23542. configurable: true
  23543. });
  23544. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  23545. set: function (callback) {
  23546. if (this._onAfterRenderObserver) {
  23547. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23548. }
  23549. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23550. },
  23551. enumerable: true,
  23552. configurable: true
  23553. });
  23554. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  23555. set: function (callback) {
  23556. if (this._onClearObserver) {
  23557. this.onClearObservable.remove(this._onClearObserver);
  23558. }
  23559. this._onClearObserver = this.onClearObservable.add(callback);
  23560. },
  23561. enumerable: true,
  23562. configurable: true
  23563. });
  23564. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  23565. this._currentRefreshId = -1;
  23566. };
  23567. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  23568. get: function () {
  23569. return this._refreshRate;
  23570. },
  23571. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23572. set: function (value) {
  23573. this._refreshRate = value;
  23574. this.resetRefreshCounter();
  23575. },
  23576. enumerable: true,
  23577. configurable: true
  23578. });
  23579. RenderTargetTexture.prototype._shouldRender = function () {
  23580. if (this._currentRefreshId === -1) {
  23581. this._currentRefreshId = 1;
  23582. return true;
  23583. }
  23584. if (this.refreshRate === this._currentRefreshId) {
  23585. this._currentRefreshId = 1;
  23586. return true;
  23587. }
  23588. this._currentRefreshId++;
  23589. return false;
  23590. };
  23591. RenderTargetTexture.prototype.isReady = function () {
  23592. if (!this.getScene().renderTargetsEnabled) {
  23593. return false;
  23594. }
  23595. return _super.prototype.isReady.call(this);
  23596. };
  23597. RenderTargetTexture.prototype.getRenderSize = function () {
  23598. return this._size;
  23599. };
  23600. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  23601. get: function () {
  23602. return true;
  23603. },
  23604. enumerable: true,
  23605. configurable: true
  23606. });
  23607. RenderTargetTexture.prototype.scale = function (ratio) {
  23608. var newSize = this._size * ratio;
  23609. this.resize(newSize, this._generateMipMaps);
  23610. };
  23611. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  23612. if (this.isCube) {
  23613. return this._textureMatrix;
  23614. }
  23615. return _super.prototype.getReflectionTextureMatrix.call(this);
  23616. };
  23617. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  23618. this.releaseInternalTexture();
  23619. if (this.isCube) {
  23620. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  23621. }
  23622. else {
  23623. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  23624. }
  23625. };
  23626. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  23627. var scene = this.getScene();
  23628. if (this.useCameraPostProcesses !== undefined) {
  23629. useCameraPostProcess = this.useCameraPostProcesses;
  23630. }
  23631. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  23632. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  23633. }
  23634. if (this._waitingRenderList) {
  23635. this.renderList = [];
  23636. for (var index = 0; index < this._waitingRenderList.length; index++) {
  23637. var id = this._waitingRenderList[index];
  23638. this.renderList.push(scene.getMeshByID(id));
  23639. }
  23640. delete this._waitingRenderList;
  23641. }
  23642. // Is predicate defined?
  23643. if (this.renderListPredicate) {
  23644. this.renderList.splice(0); // Clear previous renderList
  23645. var sceneMeshes = this.getScene().meshes;
  23646. for (var index = 0; index < sceneMeshes.length; index++) {
  23647. var mesh = sceneMeshes[index];
  23648. if (this.renderListPredicate(mesh)) {
  23649. this.renderList.push(mesh);
  23650. }
  23651. }
  23652. }
  23653. if (this.renderList && this.renderList.length === 0) {
  23654. return;
  23655. }
  23656. // Prepare renderingManager
  23657. this._renderingManager.reset();
  23658. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  23659. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  23660. var sceneRenderId = scene.getRenderId();
  23661. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  23662. var mesh = currentRenderList[meshIndex];
  23663. if (mesh) {
  23664. if (!mesh.isReady()) {
  23665. // Reset _currentRefreshId
  23666. this.resetRefreshCounter();
  23667. continue;
  23668. }
  23669. mesh._preActivateForIntermediateRendering(sceneRenderId);
  23670. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  23671. mesh._activate(sceneRenderId);
  23672. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  23673. var subMesh = mesh.subMeshes[subIndex];
  23674. scene._activeIndices.addCount(subMesh.indexCount, false);
  23675. this._renderingManager.dispatch(subMesh);
  23676. }
  23677. }
  23678. }
  23679. }
  23680. if (this.isCube) {
  23681. for (var face = 0; face < 6; face++) {
  23682. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  23683. scene.incrementRenderId();
  23684. scene.resetCachedMaterial();
  23685. }
  23686. }
  23687. else {
  23688. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  23689. }
  23690. this.onAfterUnbindObservable.notifyObservers(this);
  23691. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  23692. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  23693. }
  23694. scene.resetCachedMaterial();
  23695. };
  23696. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  23697. var scene = this.getScene();
  23698. var engine = scene.getEngine();
  23699. // Bind
  23700. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  23701. if (this.isCube) {
  23702. engine.bindFramebuffer(this._texture, faceIndex);
  23703. }
  23704. else {
  23705. engine.bindFramebuffer(this._texture);
  23706. }
  23707. }
  23708. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  23709. // Clear
  23710. if (this.onClearObservable.hasObservers()) {
  23711. this.onClearObservable.notifyObservers(engine);
  23712. }
  23713. else {
  23714. engine.clear(scene.clearColor, true, true, true);
  23715. }
  23716. if (!this._doNotChangeAspectRatio) {
  23717. scene.updateTransformMatrix(true);
  23718. }
  23719. // Render
  23720. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  23721. if (useCameraPostProcess) {
  23722. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  23723. }
  23724. if (!this._doNotChangeAspectRatio) {
  23725. scene.updateTransformMatrix(true);
  23726. }
  23727. this.onAfterRenderObservable.notifyObservers(faceIndex);
  23728. // Dump ?
  23729. if (dumpForDebug) {
  23730. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  23731. }
  23732. // Unbind
  23733. if (!this.isCube || faceIndex === 5) {
  23734. if (this.isCube) {
  23735. if (faceIndex === 5) {
  23736. engine.generateMipMapsForCubemap(this._texture);
  23737. }
  23738. }
  23739. engine.unBindFramebuffer(this._texture, this.isCube);
  23740. }
  23741. };
  23742. /**
  23743. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23744. * This allowed control for front to back rendering or reversly depending of the special needs.
  23745. *
  23746. * @param renderingGroupId The rendering group id corresponding to its index
  23747. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23748. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23749. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23750. */
  23751. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23752. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23753. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23754. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23755. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23756. };
  23757. /**
  23758. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23759. *
  23760. * @param renderingGroupId The rendering group id corresponding to its index
  23761. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23762. */
  23763. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  23764. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  23765. };
  23766. RenderTargetTexture.prototype.clone = function () {
  23767. var textureSize = this.getSize();
  23768. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23769. // Base texture
  23770. newTexture.hasAlpha = this.hasAlpha;
  23771. newTexture.level = this.level;
  23772. // RenderTarget Texture
  23773. newTexture.coordinatesMode = this.coordinatesMode;
  23774. newTexture.renderList = this.renderList.slice(0);
  23775. return newTexture;
  23776. };
  23777. RenderTargetTexture.prototype.serialize = function () {
  23778. if (!this.name) {
  23779. return null;
  23780. }
  23781. var serializationObject = _super.prototype.serialize.call(this);
  23782. serializationObject.renderTargetSize = this.getRenderSize();
  23783. serializationObject.renderList = [];
  23784. for (var index = 0; index < this.renderList.length; index++) {
  23785. serializationObject.renderList.push(this.renderList[index].id);
  23786. }
  23787. return serializationObject;
  23788. };
  23789. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  23790. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  23791. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  23792. return RenderTargetTexture;
  23793. }(BABYLON.Texture));
  23794. BABYLON.RenderTargetTexture = RenderTargetTexture;
  23795. })(BABYLON || (BABYLON = {}));
  23796. var BABYLON;
  23797. (function (BABYLON) {
  23798. var ProceduralTexture = (function (_super) {
  23799. __extends(ProceduralTexture, _super);
  23800. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  23801. if (generateMipMaps === void 0) { generateMipMaps = true; }
  23802. if (isCube === void 0) { isCube = false; }
  23803. _super.call(this, null, scene, !generateMipMaps);
  23804. this.isCube = isCube;
  23805. this.isEnabled = true;
  23806. this._currentRefreshId = -1;
  23807. this._refreshRate = 1;
  23808. this._vertexBuffers = {};
  23809. this._uniforms = new Array();
  23810. this._samplers = new Array();
  23811. this._textures = new Array();
  23812. this._floats = new Array();
  23813. this._floatsArrays = {};
  23814. this._colors3 = new Array();
  23815. this._colors4 = new Array();
  23816. this._vectors2 = new Array();
  23817. this._vectors3 = new Array();
  23818. this._matrices = new Array();
  23819. this._fallbackTextureUsed = false;
  23820. scene._proceduralTextures.push(this);
  23821. this.name = name;
  23822. this.isRenderTarget = true;
  23823. this._size = size;
  23824. this._generateMipMaps = generateMipMaps;
  23825. this.setFragment(fragment);
  23826. this._fallbackTexture = fallbackTexture;
  23827. var engine = scene.getEngine();
  23828. if (isCube) {
  23829. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  23830. this.setFloat("face", 0);
  23831. }
  23832. else {
  23833. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  23834. }
  23835. // VBO
  23836. var vertices = [];
  23837. vertices.push(1, 1);
  23838. vertices.push(-1, 1);
  23839. vertices.push(-1, -1);
  23840. vertices.push(1, -1);
  23841. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  23842. // Indices
  23843. var indices = [];
  23844. indices.push(0);
  23845. indices.push(1);
  23846. indices.push(2);
  23847. indices.push(0);
  23848. indices.push(2);
  23849. indices.push(3);
  23850. this._indexBuffer = engine.createIndexBuffer(indices);
  23851. }
  23852. ProceduralTexture.prototype.reset = function () {
  23853. if (this._effect === undefined) {
  23854. return;
  23855. }
  23856. var engine = this.getScene().getEngine();
  23857. engine._releaseEffect(this._effect);
  23858. };
  23859. ProceduralTexture.prototype.isReady = function () {
  23860. var _this = this;
  23861. var engine = this.getScene().getEngine();
  23862. var shaders;
  23863. if (!this._fragment) {
  23864. return false;
  23865. }
  23866. if (this._fallbackTextureUsed) {
  23867. return true;
  23868. }
  23869. if (this._fragment.fragmentElement !== undefined) {
  23870. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  23871. }
  23872. else {
  23873. shaders = { vertex: "procedural", fragment: this._fragment };
  23874. }
  23875. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  23876. _this.releaseInternalTexture();
  23877. if (_this._fallbackTexture) {
  23878. _this._texture = _this._fallbackTexture._texture;
  23879. _this._texture.references++;
  23880. }
  23881. _this._fallbackTextureUsed = true;
  23882. });
  23883. return this._effect.isReady();
  23884. };
  23885. ProceduralTexture.prototype.resetRefreshCounter = function () {
  23886. this._currentRefreshId = -1;
  23887. };
  23888. ProceduralTexture.prototype.setFragment = function (fragment) {
  23889. this._fragment = fragment;
  23890. };
  23891. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  23892. get: function () {
  23893. return this._refreshRate;
  23894. },
  23895. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23896. set: function (value) {
  23897. this._refreshRate = value;
  23898. this.resetRefreshCounter();
  23899. },
  23900. enumerable: true,
  23901. configurable: true
  23902. });
  23903. ProceduralTexture.prototype._shouldRender = function () {
  23904. if (!this.isEnabled || !this.isReady() || !this._texture) {
  23905. return false;
  23906. }
  23907. if (this._fallbackTextureUsed) {
  23908. return false;
  23909. }
  23910. if (this._currentRefreshId === -1) {
  23911. this._currentRefreshId = 1;
  23912. return true;
  23913. }
  23914. if (this.refreshRate === this._currentRefreshId) {
  23915. this._currentRefreshId = 1;
  23916. return true;
  23917. }
  23918. this._currentRefreshId++;
  23919. return false;
  23920. };
  23921. ProceduralTexture.prototype.getRenderSize = function () {
  23922. return this._size;
  23923. };
  23924. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  23925. if (this._fallbackTextureUsed) {
  23926. return;
  23927. }
  23928. this.releaseInternalTexture();
  23929. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  23930. };
  23931. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  23932. if (this._uniforms.indexOf(uniformName) === -1) {
  23933. this._uniforms.push(uniformName);
  23934. }
  23935. };
  23936. ProceduralTexture.prototype.setTexture = function (name, texture) {
  23937. if (this._samplers.indexOf(name) === -1) {
  23938. this._samplers.push(name);
  23939. }
  23940. this._textures[name] = texture;
  23941. return this;
  23942. };
  23943. ProceduralTexture.prototype.setFloat = function (name, value) {
  23944. this._checkUniform(name);
  23945. this._floats[name] = value;
  23946. return this;
  23947. };
  23948. ProceduralTexture.prototype.setFloats = function (name, value) {
  23949. this._checkUniform(name);
  23950. this._floatsArrays[name] = value;
  23951. return this;
  23952. };
  23953. ProceduralTexture.prototype.setColor3 = function (name, value) {
  23954. this._checkUniform(name);
  23955. this._colors3[name] = value;
  23956. return this;
  23957. };
  23958. ProceduralTexture.prototype.setColor4 = function (name, value) {
  23959. this._checkUniform(name);
  23960. this._colors4[name] = value;
  23961. return this;
  23962. };
  23963. ProceduralTexture.prototype.setVector2 = function (name, value) {
  23964. this._checkUniform(name);
  23965. this._vectors2[name] = value;
  23966. return this;
  23967. };
  23968. ProceduralTexture.prototype.setVector3 = function (name, value) {
  23969. this._checkUniform(name);
  23970. this._vectors3[name] = value;
  23971. return this;
  23972. };
  23973. ProceduralTexture.prototype.setMatrix = function (name, value) {
  23974. this._checkUniform(name);
  23975. this._matrices[name] = value;
  23976. return this;
  23977. };
  23978. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  23979. var scene = this.getScene();
  23980. var engine = scene.getEngine();
  23981. // Render
  23982. engine.enableEffect(this._effect);
  23983. engine.setState(false);
  23984. // Texture
  23985. for (var name in this._textures) {
  23986. this._effect.setTexture(name, this._textures[name]);
  23987. }
  23988. // Float
  23989. for (name in this._floats) {
  23990. this._effect.setFloat(name, this._floats[name]);
  23991. }
  23992. // Floats
  23993. for (name in this._floatsArrays) {
  23994. this._effect.setArray(name, this._floatsArrays[name]);
  23995. }
  23996. // Color3
  23997. for (name in this._colors3) {
  23998. this._effect.setColor3(name, this._colors3[name]);
  23999. }
  24000. // Color4
  24001. for (name in this._colors4) {
  24002. var color = this._colors4[name];
  24003. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  24004. }
  24005. // Vector2
  24006. for (name in this._vectors2) {
  24007. this._effect.setVector2(name, this._vectors2[name]);
  24008. }
  24009. // Vector3
  24010. for (name in this._vectors3) {
  24011. this._effect.setVector3(name, this._vectors3[name]);
  24012. }
  24013. // Matrix
  24014. for (name in this._matrices) {
  24015. this._effect.setMatrix(name, this._matrices[name]);
  24016. }
  24017. // VBOs
  24018. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  24019. if (this.isCube) {
  24020. for (var face = 0; face < 6; face++) {
  24021. engine.bindFramebuffer(this._texture, face);
  24022. this._effect.setFloat("face", face);
  24023. // Clear
  24024. engine.clear(scene.clearColor, true, true, true);
  24025. // Draw order
  24026. engine.draw(true, 0, 6);
  24027. // Mipmaps
  24028. if (face === 5) {
  24029. engine.generateMipMapsForCubemap(this._texture);
  24030. }
  24031. }
  24032. }
  24033. else {
  24034. engine.bindFramebuffer(this._texture);
  24035. // Clear
  24036. engine.clear(scene.clearColor, true, true, true);
  24037. // Draw order
  24038. engine.draw(true, 0, 6);
  24039. }
  24040. // Unbind
  24041. engine.unBindFramebuffer(this._texture, this.isCube);
  24042. if (this.onGenerated) {
  24043. this.onGenerated();
  24044. }
  24045. };
  24046. ProceduralTexture.prototype.clone = function () {
  24047. var textureSize = this.getSize();
  24048. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  24049. // Base texture
  24050. newTexture.hasAlpha = this.hasAlpha;
  24051. newTexture.level = this.level;
  24052. // RenderTarget Texture
  24053. newTexture.coordinatesMode = this.coordinatesMode;
  24054. return newTexture;
  24055. };
  24056. ProceduralTexture.prototype.dispose = function () {
  24057. var index = this.getScene()._proceduralTextures.indexOf(this);
  24058. if (index >= 0) {
  24059. this.getScene()._proceduralTextures.splice(index, 1);
  24060. }
  24061. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  24062. if (vertexBuffer) {
  24063. vertexBuffer.dispose();
  24064. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  24065. }
  24066. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  24067. this._indexBuffer = null;
  24068. }
  24069. _super.prototype.dispose.call(this);
  24070. };
  24071. return ProceduralTexture;
  24072. }(BABYLON.Texture));
  24073. BABYLON.ProceduralTexture = ProceduralTexture;
  24074. })(BABYLON || (BABYLON = {}));
  24075. var BABYLON;
  24076. (function (BABYLON) {
  24077. var MirrorTexture = (function (_super) {
  24078. __extends(MirrorTexture, _super);
  24079. function MirrorTexture(name, size, scene, generateMipMaps) {
  24080. var _this = this;
  24081. _super.call(this, name, size, scene, generateMipMaps, true);
  24082. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  24083. this._transformMatrix = BABYLON.Matrix.Zero();
  24084. this._mirrorMatrix = BABYLON.Matrix.Zero();
  24085. this.onBeforeRenderObservable.add(function () {
  24086. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  24087. _this._savedViewMatrix = scene.getViewMatrix();
  24088. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  24089. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  24090. scene.clipPlane = _this.mirrorPlane;
  24091. scene.getEngine().cullBackFaces = false;
  24092. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  24093. });
  24094. this.onAfterRenderObservable.add(function () {
  24095. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  24096. scene.getEngine().cullBackFaces = true;
  24097. scene._mirroredCameraPosition = null;
  24098. delete scene.clipPlane;
  24099. });
  24100. }
  24101. MirrorTexture.prototype.clone = function () {
  24102. var textureSize = this.getSize();
  24103. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24104. // Base texture
  24105. newTexture.hasAlpha = this.hasAlpha;
  24106. newTexture.level = this.level;
  24107. // Mirror Texture
  24108. newTexture.mirrorPlane = this.mirrorPlane.clone();
  24109. newTexture.renderList = this.renderList.slice(0);
  24110. return newTexture;
  24111. };
  24112. MirrorTexture.prototype.serialize = function () {
  24113. if (!this.name) {
  24114. return null;
  24115. }
  24116. var serializationObject = _super.prototype.serialize.call(this);
  24117. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  24118. return serializationObject;
  24119. };
  24120. return MirrorTexture;
  24121. }(BABYLON.RenderTargetTexture));
  24122. BABYLON.MirrorTexture = MirrorTexture;
  24123. })(BABYLON || (BABYLON = {}));
  24124. var BABYLON;
  24125. (function (BABYLON) {
  24126. /**
  24127. * Creates a refraction texture used by refraction channel of the standard material.
  24128. * @param name the texture name
  24129. * @param size size of the underlying texture
  24130. * @param scene root scene
  24131. */
  24132. var RefractionTexture = (function (_super) {
  24133. __extends(RefractionTexture, _super);
  24134. function RefractionTexture(name, size, scene, generateMipMaps) {
  24135. var _this = this;
  24136. _super.call(this, name, size, scene, generateMipMaps, true);
  24137. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  24138. this.depth = 2.0;
  24139. this.onBeforeRenderObservable.add(function () {
  24140. scene.clipPlane = _this.refractionPlane;
  24141. });
  24142. this.onAfterRenderObservable.add(function () {
  24143. delete scene.clipPlane;
  24144. });
  24145. }
  24146. RefractionTexture.prototype.clone = function () {
  24147. var textureSize = this.getSize();
  24148. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24149. // Base texture
  24150. newTexture.hasAlpha = this.hasAlpha;
  24151. newTexture.level = this.level;
  24152. // Refraction Texture
  24153. newTexture.refractionPlane = this.refractionPlane.clone();
  24154. newTexture.renderList = this.renderList.slice(0);
  24155. newTexture.depth = this.depth;
  24156. return newTexture;
  24157. };
  24158. RefractionTexture.prototype.serialize = function () {
  24159. if (!this.name) {
  24160. return null;
  24161. }
  24162. var serializationObject = _super.prototype.serialize.call(this);
  24163. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  24164. serializationObject.depth = this.depth;
  24165. return serializationObject;
  24166. };
  24167. return RefractionTexture;
  24168. }(BABYLON.RenderTargetTexture));
  24169. BABYLON.RefractionTexture = RefractionTexture;
  24170. })(BABYLON || (BABYLON = {}));
  24171. var BABYLON;
  24172. (function (BABYLON) {
  24173. var DynamicTexture = (function (_super) {
  24174. __extends(DynamicTexture, _super);
  24175. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  24176. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24177. _super.call(this, null, scene, !generateMipMaps);
  24178. this.name = name;
  24179. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24180. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24181. this._generateMipMaps = generateMipMaps;
  24182. if (options.getContext) {
  24183. this._canvas = options;
  24184. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  24185. }
  24186. else {
  24187. this._canvas = document.createElement("canvas");
  24188. if (options.width) {
  24189. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  24190. }
  24191. else {
  24192. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  24193. }
  24194. }
  24195. var textureSize = this.getSize();
  24196. this._canvas.width = textureSize.width;
  24197. this._canvas.height = textureSize.height;
  24198. this._context = this._canvas.getContext("2d");
  24199. }
  24200. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  24201. get: function () {
  24202. return true;
  24203. },
  24204. enumerable: true,
  24205. configurable: true
  24206. });
  24207. DynamicTexture.prototype.scale = function (ratio) {
  24208. var textureSize = this.getSize();
  24209. textureSize.width *= ratio;
  24210. textureSize.height *= ratio;
  24211. this._canvas.width = textureSize.width;
  24212. this._canvas.height = textureSize.height;
  24213. this.releaseInternalTexture();
  24214. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  24215. };
  24216. DynamicTexture.prototype.getContext = function () {
  24217. return this._context;
  24218. };
  24219. DynamicTexture.prototype.clear = function () {
  24220. var size = this.getSize();
  24221. this._context.fillRect(0, 0, size.width, size.height);
  24222. };
  24223. DynamicTexture.prototype.update = function (invertY) {
  24224. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  24225. };
  24226. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  24227. if (update === void 0) { update = true; }
  24228. var size = this.getSize();
  24229. if (clearColor) {
  24230. this._context.fillStyle = clearColor;
  24231. this._context.fillRect(0, 0, size.width, size.height);
  24232. }
  24233. this._context.font = font;
  24234. if (x === null) {
  24235. var textSize = this._context.measureText(text);
  24236. x = (size.width - textSize.width) / 2;
  24237. }
  24238. this._context.fillStyle = color;
  24239. this._context.fillText(text, x, y);
  24240. if (update) {
  24241. this.update(invertY);
  24242. }
  24243. };
  24244. DynamicTexture.prototype.clone = function () {
  24245. var textureSize = this.getSize();
  24246. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  24247. // Base texture
  24248. newTexture.hasAlpha = this.hasAlpha;
  24249. newTexture.level = this.level;
  24250. // Dynamic Texture
  24251. newTexture.wrapU = this.wrapU;
  24252. newTexture.wrapV = this.wrapV;
  24253. return newTexture;
  24254. };
  24255. return DynamicTexture;
  24256. }(BABYLON.Texture));
  24257. BABYLON.DynamicTexture = DynamicTexture;
  24258. })(BABYLON || (BABYLON = {}));
  24259. var BABYLON;
  24260. (function (BABYLON) {
  24261. var VideoTexture = (function (_super) {
  24262. __extends(VideoTexture, _super);
  24263. /**
  24264. * Creates a video texture.
  24265. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  24266. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  24267. * @param {BABYLON.Scene} scene is obviously the current scene.
  24268. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  24269. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  24270. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  24271. */
  24272. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  24273. var _this = this;
  24274. if (generateMipMaps === void 0) { generateMipMaps = false; }
  24275. if (invertY === void 0) { invertY = false; }
  24276. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24277. _super.call(this, null, scene, !generateMipMaps, invertY);
  24278. this._autoLaunch = true;
  24279. var urls;
  24280. this.name = name;
  24281. if (urlsOrVideo instanceof HTMLVideoElement) {
  24282. this.video = urlsOrVideo;
  24283. }
  24284. else {
  24285. urls = urlsOrVideo;
  24286. this.video = document.createElement("video");
  24287. this.video.autoplay = false;
  24288. this.video.loop = true;
  24289. }
  24290. this._generateMipMaps = generateMipMaps;
  24291. this._samplingMode = samplingMode;
  24292. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  24293. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24294. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24295. }
  24296. else {
  24297. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24298. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24299. this._generateMipMaps = false;
  24300. }
  24301. if (urls) {
  24302. this.video.addEventListener("canplaythrough", function () {
  24303. _this._createTexture();
  24304. });
  24305. urls.forEach(function (url) {
  24306. var source = document.createElement("source");
  24307. source.src = url;
  24308. _this.video.appendChild(source);
  24309. });
  24310. }
  24311. else {
  24312. this._createTexture();
  24313. }
  24314. this._lastUpdate = BABYLON.Tools.Now;
  24315. }
  24316. VideoTexture.prototype._createTexture = function () {
  24317. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  24318. this._texture.isReady = true;
  24319. };
  24320. VideoTexture.prototype.update = function () {
  24321. if (this._autoLaunch) {
  24322. this._autoLaunch = false;
  24323. this.video.play();
  24324. }
  24325. var now = BABYLON.Tools.Now;
  24326. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  24327. return false;
  24328. }
  24329. this._lastUpdate = now;
  24330. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  24331. return true;
  24332. };
  24333. return VideoTexture;
  24334. }(BABYLON.Texture));
  24335. BABYLON.VideoTexture = VideoTexture;
  24336. })(BABYLON || (BABYLON = {}));
  24337. var BABYLON;
  24338. (function (BABYLON) {
  24339. var CustomProceduralTexture = (function (_super) {
  24340. __extends(CustomProceduralTexture, _super);
  24341. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  24342. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  24343. this._animate = true;
  24344. this._time = 0;
  24345. this._texturePath = texturePath;
  24346. //Try to load json
  24347. this.loadJson(texturePath);
  24348. this.refreshRate = 1;
  24349. }
  24350. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  24351. var _this = this;
  24352. var that = this;
  24353. function noConfigFile() {
  24354. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  24355. try {
  24356. that.setFragment(that._texturePath);
  24357. }
  24358. catch (ex) {
  24359. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  24360. }
  24361. }
  24362. var configFileUrl = jsonUrl + "/config.json";
  24363. var xhr = new XMLHttpRequest();
  24364. xhr.open("GET", configFileUrl, true);
  24365. xhr.addEventListener("load", function () {
  24366. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  24367. try {
  24368. _this._config = JSON.parse(xhr.response);
  24369. _this.updateShaderUniforms();
  24370. _this.updateTextures();
  24371. _this.setFragment(_this._texturePath + "/custom");
  24372. _this._animate = _this._config.animate;
  24373. _this.refreshRate = _this._config.refreshrate;
  24374. }
  24375. catch (ex) {
  24376. noConfigFile();
  24377. }
  24378. }
  24379. else {
  24380. noConfigFile();
  24381. }
  24382. }, false);
  24383. xhr.addEventListener("error", function () {
  24384. noConfigFile();
  24385. }, false);
  24386. try {
  24387. xhr.send();
  24388. }
  24389. catch (ex) {
  24390. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  24391. }
  24392. };
  24393. CustomProceduralTexture.prototype.isReady = function () {
  24394. if (!_super.prototype.isReady.call(this)) {
  24395. return false;
  24396. }
  24397. for (var name in this._textures) {
  24398. var texture = this._textures[name];
  24399. if (!texture.isReady()) {
  24400. return false;
  24401. }
  24402. }
  24403. return true;
  24404. };
  24405. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  24406. if (this._animate) {
  24407. this._time += this.getScene().getAnimationRatio() * 0.03;
  24408. this.updateShaderUniforms();
  24409. }
  24410. _super.prototype.render.call(this, useCameraPostProcess);
  24411. };
  24412. CustomProceduralTexture.prototype.updateTextures = function () {
  24413. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  24414. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  24415. }
  24416. };
  24417. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  24418. if (this._config) {
  24419. for (var j = 0; j < this._config.uniforms.length; j++) {
  24420. var uniform = this._config.uniforms[j];
  24421. switch (uniform.type) {
  24422. case "float":
  24423. this.setFloat(uniform.name, uniform.value);
  24424. break;
  24425. case "color3":
  24426. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  24427. break;
  24428. case "color4":
  24429. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  24430. break;
  24431. case "vector2":
  24432. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  24433. break;
  24434. case "vector3":
  24435. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  24436. break;
  24437. }
  24438. }
  24439. }
  24440. this.setFloat("time", this._time);
  24441. };
  24442. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  24443. get: function () {
  24444. return this._animate;
  24445. },
  24446. set: function (value) {
  24447. this._animate = value;
  24448. },
  24449. enumerable: true,
  24450. configurable: true
  24451. });
  24452. return CustomProceduralTexture;
  24453. }(BABYLON.ProceduralTexture));
  24454. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  24455. })(BABYLON || (BABYLON = {}));
  24456. var BABYLON;
  24457. (function (BABYLON) {
  24458. var EffectFallbacks = (function () {
  24459. function EffectFallbacks() {
  24460. this._defines = {};
  24461. this._currentRank = 32;
  24462. this._maxRank = -1;
  24463. }
  24464. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24465. if (!this._defines[rank]) {
  24466. if (rank < this._currentRank) {
  24467. this._currentRank = rank;
  24468. }
  24469. if (rank > this._maxRank) {
  24470. this._maxRank = rank;
  24471. }
  24472. this._defines[rank] = new Array();
  24473. }
  24474. this._defines[rank].push(define);
  24475. };
  24476. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24477. this._meshRank = rank;
  24478. this._mesh = mesh;
  24479. if (rank > this._maxRank) {
  24480. this._maxRank = rank;
  24481. }
  24482. };
  24483. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24484. get: function () {
  24485. return this._currentRank <= this._maxRank;
  24486. },
  24487. enumerable: true,
  24488. configurable: true
  24489. });
  24490. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24491. var currentFallbacks = this._defines[this._currentRank];
  24492. for (var index = 0; index < currentFallbacks.length; index++) {
  24493. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24494. }
  24495. if (this._mesh && this._currentRank === this._meshRank) {
  24496. this._mesh.computeBonesUsingShaders = false;
  24497. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24498. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24499. }
  24500. this._currentRank++;
  24501. return currentDefines;
  24502. };
  24503. return EffectFallbacks;
  24504. }());
  24505. BABYLON.EffectFallbacks = EffectFallbacks;
  24506. var Effect = (function () {
  24507. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24508. var _this = this;
  24509. this._isReady = false;
  24510. this._compilationError = "";
  24511. this._valueCache = {};
  24512. this._engine = engine;
  24513. this.name = baseName;
  24514. this.defines = defines;
  24515. this._uniformsNames = uniformsNames.concat(samplers);
  24516. this._samplers = samplers;
  24517. this._attributesNames = attributesNames;
  24518. this.onError = onError;
  24519. this.onCompiled = onCompiled;
  24520. this._indexParameters = indexParameters;
  24521. var vertexSource;
  24522. var fragmentSource;
  24523. if (baseName.vertexElement) {
  24524. vertexSource = document.getElementById(baseName.vertexElement);
  24525. if (!vertexSource) {
  24526. vertexSource = baseName.vertexElement;
  24527. }
  24528. }
  24529. else {
  24530. vertexSource = baseName.vertex || baseName;
  24531. }
  24532. if (baseName.fragmentElement) {
  24533. fragmentSource = document.getElementById(baseName.fragmentElement);
  24534. if (!fragmentSource) {
  24535. fragmentSource = baseName.fragmentElement;
  24536. }
  24537. }
  24538. else {
  24539. fragmentSource = baseName.fragment || baseName;
  24540. }
  24541. this._loadVertexShader(vertexSource, function (vertexCode) {
  24542. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24543. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24544. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24545. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  24546. });
  24547. });
  24548. });
  24549. });
  24550. }
  24551. // Properties
  24552. Effect.prototype.isReady = function () {
  24553. return this._isReady;
  24554. };
  24555. Effect.prototype.getProgram = function () {
  24556. return this._program;
  24557. };
  24558. Effect.prototype.getAttributesNames = function () {
  24559. return this._attributesNames;
  24560. };
  24561. Effect.prototype.getAttributeLocation = function (index) {
  24562. return this._attributes[index];
  24563. };
  24564. Effect.prototype.getAttributeLocationByName = function (name) {
  24565. var index = this._attributesNames.indexOf(name);
  24566. return this._attributes[index];
  24567. };
  24568. Effect.prototype.getAttributesCount = function () {
  24569. return this._attributes.length;
  24570. };
  24571. Effect.prototype.getUniformIndex = function (uniformName) {
  24572. return this._uniformsNames.indexOf(uniformName);
  24573. };
  24574. Effect.prototype.getUniform = function (uniformName) {
  24575. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24576. };
  24577. Effect.prototype.getSamplers = function () {
  24578. return this._samplers;
  24579. };
  24580. Effect.prototype.getCompilationError = function () {
  24581. return this._compilationError;
  24582. };
  24583. // Methods
  24584. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24585. // DOM element ?
  24586. if (vertex instanceof HTMLElement) {
  24587. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24588. callback(vertexCode);
  24589. return;
  24590. }
  24591. // Base64 encoded ?
  24592. if (vertex.substr(0, 7) === "base64:") {
  24593. var vertexBinary = window.atob(vertex.substr(7));
  24594. callback(vertexBinary);
  24595. return;
  24596. }
  24597. // Is in local store ?
  24598. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24599. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24600. return;
  24601. }
  24602. var vertexShaderUrl;
  24603. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24604. vertexShaderUrl = vertex;
  24605. }
  24606. else {
  24607. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24608. }
  24609. // Vertex shader
  24610. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24611. };
  24612. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24613. // DOM element ?
  24614. if (fragment instanceof HTMLElement) {
  24615. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24616. callback(fragmentCode);
  24617. return;
  24618. }
  24619. // Base64 encoded ?
  24620. if (fragment.substr(0, 7) === "base64:") {
  24621. var fragmentBinary = window.atob(fragment.substr(7));
  24622. callback(fragmentBinary);
  24623. return;
  24624. }
  24625. // Is in local store ?
  24626. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24627. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24628. return;
  24629. }
  24630. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24631. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24632. return;
  24633. }
  24634. var fragmentShaderUrl;
  24635. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24636. fragmentShaderUrl = fragment;
  24637. }
  24638. else {
  24639. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24640. }
  24641. // Fragment shader
  24642. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24643. };
  24644. Effect.prototype._dumpShadersName = function () {
  24645. if (this.name.vertexElement) {
  24646. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  24647. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  24648. }
  24649. else if (this.name.vertex) {
  24650. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  24651. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  24652. }
  24653. else {
  24654. BABYLON.Tools.Error("Vertex shader:" + this.name);
  24655. BABYLON.Tools.Error("Fragment shader:" + this.name);
  24656. }
  24657. };
  24658. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24659. var _this = this;
  24660. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24661. var match = regex.exec(sourceCode);
  24662. var returnValue = new String(sourceCode);
  24663. while (match != null) {
  24664. var includeFile = match[1];
  24665. if (Effect.IncludesShadersStore[includeFile]) {
  24666. // Substitution
  24667. var includeContent = Effect.IncludesShadersStore[includeFile];
  24668. if (match[2]) {
  24669. var splits = match[3].split(",");
  24670. for (var index = 0; index < splits.length; index += 2) {
  24671. var source = new RegExp(splits[index], "g");
  24672. var dest = splits[index + 1];
  24673. includeContent = includeContent.replace(source, dest);
  24674. }
  24675. }
  24676. if (match[4]) {
  24677. var indexString = match[5];
  24678. if (indexString.indexOf("..") !== -1) {
  24679. var indexSplits = indexString.split("..");
  24680. var minIndex = parseInt(indexSplits[0]);
  24681. var maxIndex = parseInt(indexSplits[1]);
  24682. var sourceIncludeContent = includeContent.slice(0);
  24683. includeContent = "";
  24684. if (isNaN(maxIndex)) {
  24685. maxIndex = this._indexParameters[indexSplits[1]];
  24686. }
  24687. for (var i = minIndex; i <= maxIndex; i++) {
  24688. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24689. }
  24690. }
  24691. else {
  24692. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24693. }
  24694. }
  24695. // Replace
  24696. returnValue = returnValue.replace(match[0], includeContent);
  24697. }
  24698. else {
  24699. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24700. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24701. Effect.IncludesShadersStore[includeFile] = fileContent;
  24702. _this._processIncludes(returnValue, callback);
  24703. });
  24704. return;
  24705. }
  24706. match = regex.exec(sourceCode);
  24707. }
  24708. callback(returnValue);
  24709. };
  24710. Effect.prototype._processPrecision = function (source) {
  24711. if (source.indexOf("precision highp float") === -1) {
  24712. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24713. source = "precision mediump float;\n" + source;
  24714. }
  24715. else {
  24716. source = "precision highp float;\n" + source;
  24717. }
  24718. }
  24719. else {
  24720. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24721. source = source.replace("precision highp float", "precision mediump float");
  24722. }
  24723. }
  24724. return source;
  24725. };
  24726. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  24727. try {
  24728. var engine = this._engine;
  24729. // Precision
  24730. vertexSourceCode = this._processPrecision(vertexSourceCode);
  24731. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  24732. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  24733. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24734. this._attributes = engine.getAttributes(this._program, attributesNames);
  24735. var index;
  24736. for (index = 0; index < this._samplers.length; index++) {
  24737. var sampler = this.getUniform(this._samplers[index]);
  24738. if (sampler == null) {
  24739. this._samplers.splice(index, 1);
  24740. index--;
  24741. }
  24742. }
  24743. engine.bindSamplers(this);
  24744. this._compilationError = "";
  24745. this._isReady = true;
  24746. if (this.onCompiled) {
  24747. this.onCompiled(this);
  24748. }
  24749. }
  24750. catch (e) {
  24751. this._compilationError = e.message;
  24752. // Let's go through fallbacks then
  24753. BABYLON.Tools.Error("Unable to compile effect: ");
  24754. BABYLON.Tools.Error("Defines: " + defines);
  24755. BABYLON.Tools.Error("Error: " + this._compilationError);
  24756. this._dumpShadersName();
  24757. if (fallbacks && fallbacks.isMoreFallbacks) {
  24758. BABYLON.Tools.Error("Trying next fallback.");
  24759. defines = fallbacks.reduce(defines);
  24760. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  24761. }
  24762. else {
  24763. if (this.onError) {
  24764. this.onError(this, this._compilationError);
  24765. }
  24766. }
  24767. }
  24768. };
  24769. Object.defineProperty(Effect.prototype, "isSupported", {
  24770. get: function () {
  24771. return this._compilationError === "";
  24772. },
  24773. enumerable: true,
  24774. configurable: true
  24775. });
  24776. Effect.prototype._bindTexture = function (channel, texture) {
  24777. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24778. };
  24779. Effect.prototype.setTexture = function (channel, texture) {
  24780. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24781. };
  24782. Effect.prototype.setTextureArray = function (channel, textures) {
  24783. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24784. var initialPos = this._samplers.indexOf(channel);
  24785. for (var index = 1; index < textures.length; index++) {
  24786. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24787. }
  24788. }
  24789. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24790. };
  24791. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24792. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24793. };
  24794. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24795. var changed = false;
  24796. var cache = this._valueCache[uniformName];
  24797. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  24798. changed = true;
  24799. cache = new BABYLON.Matrix();
  24800. }
  24801. var tm = cache.m;
  24802. var om = matrix.m;
  24803. for (var index = 0; index < 16; index++) {
  24804. if (tm[index] !== om[index]) {
  24805. tm[index] = om[index];
  24806. changed = true;
  24807. }
  24808. }
  24809. this._valueCache[uniformName] = cache;
  24810. return changed;
  24811. };
  24812. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24813. var cache = this._valueCache[uniformName];
  24814. if (!cache) {
  24815. cache = [x, y];
  24816. this._valueCache[uniformName] = cache;
  24817. return true;
  24818. }
  24819. var changed = false;
  24820. if (cache[0] !== x) {
  24821. cache[0] = x;
  24822. changed = true;
  24823. }
  24824. if (cache[1] !== y) {
  24825. cache[1] = y;
  24826. changed = true;
  24827. }
  24828. return changed;
  24829. };
  24830. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24831. var cache = this._valueCache[uniformName];
  24832. if (!cache) {
  24833. cache = [x, y, z];
  24834. this._valueCache[uniformName] = cache;
  24835. return true;
  24836. }
  24837. var changed = false;
  24838. if (cache[0] !== x) {
  24839. cache[0] = x;
  24840. changed = true;
  24841. }
  24842. if (cache[1] !== y) {
  24843. cache[1] = y;
  24844. changed = true;
  24845. }
  24846. if (cache[2] !== z) {
  24847. cache[2] = z;
  24848. changed = true;
  24849. }
  24850. return changed;
  24851. };
  24852. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24853. var cache = this._valueCache[uniformName];
  24854. if (!cache) {
  24855. cache = [x, y, z, w];
  24856. this._valueCache[uniformName] = cache;
  24857. return true;
  24858. }
  24859. var changed = false;
  24860. if (cache[0] !== x) {
  24861. cache[0] = x;
  24862. changed = true;
  24863. }
  24864. if (cache[1] !== y) {
  24865. cache[1] = y;
  24866. changed = true;
  24867. }
  24868. if (cache[2] !== z) {
  24869. cache[2] = z;
  24870. changed = true;
  24871. }
  24872. if (cache[3] !== w) {
  24873. cache[3] = w;
  24874. changed = true;
  24875. }
  24876. return changed;
  24877. };
  24878. Effect.prototype.setIntArray = function (uniformName, array) {
  24879. this._valueCache[uniformName] = null;
  24880. this._engine.setIntArray(this.getUniform(uniformName), array);
  24881. return this;
  24882. };
  24883. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24884. this._valueCache[uniformName] = null;
  24885. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24886. return this;
  24887. };
  24888. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24889. this._valueCache[uniformName] = null;
  24890. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24891. return this;
  24892. };
  24893. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24894. this._valueCache[uniformName] = null;
  24895. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24896. return this;
  24897. };
  24898. Effect.prototype.setFloatArray = function (uniformName, array) {
  24899. this._valueCache[uniformName] = null;
  24900. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24901. return this;
  24902. };
  24903. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24904. this._valueCache[uniformName] = null;
  24905. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24906. return this;
  24907. };
  24908. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24909. this._valueCache[uniformName] = null;
  24910. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24911. return this;
  24912. };
  24913. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24914. this._valueCache[uniformName] = null;
  24915. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24916. return this;
  24917. };
  24918. Effect.prototype.setArray = function (uniformName, array) {
  24919. this._valueCache[uniformName] = null;
  24920. this._engine.setArray(this.getUniform(uniformName), array);
  24921. return this;
  24922. };
  24923. Effect.prototype.setArray2 = function (uniformName, array) {
  24924. this._valueCache[uniformName] = null;
  24925. this._engine.setArray2(this.getUniform(uniformName), array);
  24926. return this;
  24927. };
  24928. Effect.prototype.setArray3 = function (uniformName, array) {
  24929. this._valueCache[uniformName] = null;
  24930. this._engine.setArray3(this.getUniform(uniformName), array);
  24931. return this;
  24932. };
  24933. Effect.prototype.setArray4 = function (uniformName, array) {
  24934. this._valueCache[uniformName] = null;
  24935. this._engine.setArray4(this.getUniform(uniformName), array);
  24936. return this;
  24937. };
  24938. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24939. this._valueCache[uniformName] = null;
  24940. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24941. return this;
  24942. };
  24943. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24944. if (this._cacheMatrix(uniformName, matrix)) {
  24945. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24946. }
  24947. return this;
  24948. };
  24949. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24950. this._valueCache[uniformName] = null;
  24951. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24952. return this;
  24953. };
  24954. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24955. this._valueCache[uniformName] = null;
  24956. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24957. return this;
  24958. };
  24959. Effect.prototype.setFloat = function (uniformName, value) {
  24960. var cache = this._valueCache[uniformName];
  24961. if (cache !== undefined && cache === value)
  24962. return this;
  24963. this._valueCache[uniformName] = value;
  24964. this._engine.setFloat(this.getUniform(uniformName), value);
  24965. return this;
  24966. };
  24967. Effect.prototype.setBool = function (uniformName, bool) {
  24968. var cache = this._valueCache[uniformName];
  24969. if (cache !== undefined && cache === bool)
  24970. return this;
  24971. this._valueCache[uniformName] = bool;
  24972. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24973. return this;
  24974. };
  24975. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24976. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24977. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24978. }
  24979. return this;
  24980. };
  24981. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24982. if (this._cacheFloat2(uniformName, x, y)) {
  24983. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24984. }
  24985. return this;
  24986. };
  24987. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24988. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24989. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24990. }
  24991. return this;
  24992. };
  24993. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24994. if (this._cacheFloat3(uniformName, x, y, z)) {
  24995. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24996. }
  24997. return this;
  24998. };
  24999. Effect.prototype.setVector4 = function (uniformName, vector4) {
  25000. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  25001. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  25002. }
  25003. return this;
  25004. };
  25005. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  25006. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  25007. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  25008. }
  25009. return this;
  25010. };
  25011. Effect.prototype.setColor3 = function (uniformName, color3) {
  25012. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  25013. this._engine.setColor3(this.getUniform(uniformName), color3);
  25014. }
  25015. return this;
  25016. };
  25017. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  25018. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  25019. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  25020. }
  25021. return this;
  25022. };
  25023. // Statics
  25024. Effect.ShadersStore = {};
  25025. Effect.IncludesShadersStore = {};
  25026. return Effect;
  25027. }());
  25028. BABYLON.Effect = Effect;
  25029. })(BABYLON || (BABYLON = {}));
  25030. var BABYLON;
  25031. (function (BABYLON) {
  25032. var MaterialHelper = (function () {
  25033. function MaterialHelper() {
  25034. }
  25035. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  25036. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25037. var lightIndex = 0;
  25038. var needNormals = false;
  25039. var needRebuild = false;
  25040. var needShadows = false;
  25041. var lightmapMode = false;
  25042. for (var index = 0; index < scene.lights.length; index++) {
  25043. var light = scene.lights[index];
  25044. if (!light.isEnabled()) {
  25045. continue;
  25046. }
  25047. // Excluded check
  25048. if (light._excludedMeshesIds.length > 0) {
  25049. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  25050. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  25051. if (excludedMesh) {
  25052. light.excludedMeshes.push(excludedMesh);
  25053. }
  25054. }
  25055. light._excludedMeshesIds = [];
  25056. }
  25057. // Included check
  25058. if (light._includedOnlyMeshesIds.length > 0) {
  25059. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  25060. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  25061. if (includedOnlyMesh) {
  25062. light.includedOnlyMeshes.push(includedOnlyMesh);
  25063. }
  25064. }
  25065. light._includedOnlyMeshesIds = [];
  25066. }
  25067. if (!light.canAffectMesh(mesh)) {
  25068. continue;
  25069. }
  25070. needNormals = true;
  25071. if (defines["LIGHT" + lightIndex] === undefined) {
  25072. needRebuild = true;
  25073. }
  25074. defines["LIGHT" + lightIndex] = true;
  25075. var type;
  25076. if (light instanceof BABYLON.SpotLight) {
  25077. type = "SPOTLIGHT" + lightIndex;
  25078. }
  25079. else if (light instanceof BABYLON.HemisphericLight) {
  25080. type = "HEMILIGHT" + lightIndex;
  25081. }
  25082. else if (light instanceof BABYLON.PointLight) {
  25083. type = "POINTLIGHT" + lightIndex;
  25084. }
  25085. else {
  25086. type = "DIRLIGHT" + lightIndex;
  25087. }
  25088. if (defines[type] === undefined) {
  25089. needRebuild = true;
  25090. }
  25091. defines[type] = true;
  25092. // Specular
  25093. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  25094. defines["SPECULARTERM"] = true;
  25095. }
  25096. // Shadows
  25097. if (scene.shadowsEnabled) {
  25098. var shadowGenerator = light.getShadowGenerator();
  25099. if (mesh && mesh.receiveShadows && shadowGenerator) {
  25100. if (defines["SHADOW" + lightIndex] === undefined) {
  25101. needRebuild = true;
  25102. }
  25103. defines["SHADOW" + lightIndex] = true;
  25104. defines["SHADOWS"] = true;
  25105. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  25106. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  25107. needRebuild = true;
  25108. }
  25109. defines["SHADOWVSM" + lightIndex] = true;
  25110. }
  25111. if (shadowGenerator.usePoissonSampling) {
  25112. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  25113. needRebuild = true;
  25114. }
  25115. defines["SHADOWPCF" + lightIndex] = true;
  25116. }
  25117. needShadows = true;
  25118. }
  25119. }
  25120. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25121. lightmapMode = true;
  25122. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  25123. needRebuild = true;
  25124. }
  25125. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  25126. needRebuild = true;
  25127. }
  25128. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25129. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  25130. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  25131. }
  25132. }
  25133. lightIndex++;
  25134. if (lightIndex === maxSimultaneousLights)
  25135. break;
  25136. }
  25137. var caps = scene.getEngine().getCaps();
  25138. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  25139. if (defines["SHADOWFULLFLOAT"] === undefined) {
  25140. needRebuild = true;
  25141. }
  25142. defines["SHADOWFULLFLOAT"] = true;
  25143. }
  25144. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  25145. needRebuild = true;
  25146. }
  25147. if (lightmapMode) {
  25148. defines["LIGHTMAPEXCLUDED"] = true;
  25149. }
  25150. if (needRebuild) {
  25151. defines.rebuild();
  25152. }
  25153. return needNormals;
  25154. };
  25155. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  25156. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25157. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25158. if (!defines["LIGHT" + lightIndex]) {
  25159. break;
  25160. }
  25161. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  25162. samplersList.push("shadowSampler" + lightIndex);
  25163. }
  25164. };
  25165. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25166. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25167. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25168. if (!defines["LIGHT" + lightIndex]) {
  25169. break;
  25170. }
  25171. if (lightIndex > 0) {
  25172. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25173. }
  25174. if (defines["SHADOW" + lightIndex]) {
  25175. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25176. }
  25177. if (defines["SHADOWPCF" + lightIndex]) {
  25178. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25179. }
  25180. if (defines["SHADOWVSM" + lightIndex]) {
  25181. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  25182. }
  25183. }
  25184. };
  25185. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25186. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25187. fallbacks.addCPUSkinningFallback(0, mesh);
  25188. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25189. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25190. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25191. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25192. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25193. }
  25194. }
  25195. };
  25196. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25197. if (defines["INSTANCES"]) {
  25198. attribs.push("world0");
  25199. attribs.push("world1");
  25200. attribs.push("world2");
  25201. attribs.push("world3");
  25202. }
  25203. };
  25204. // Bindings
  25205. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  25206. var shadowGenerator = light.getShadowGenerator();
  25207. if (mesh.receiveShadows && shadowGenerator) {
  25208. if (!light.needCube()) {
  25209. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  25210. }
  25211. else {
  25212. if (!depthValuesAlreadySet) {
  25213. depthValuesAlreadySet = true;
  25214. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  25215. }
  25216. }
  25217. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  25218. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  25219. }
  25220. return depthValuesAlreadySet;
  25221. };
  25222. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25223. if (light instanceof BABYLON.PointLight) {
  25224. // Point Light
  25225. light.transferToEffect(effect, "vLightData" + lightIndex);
  25226. }
  25227. else if (light instanceof BABYLON.DirectionalLight) {
  25228. // Directional Light
  25229. light.transferToEffect(effect, "vLightData" + lightIndex);
  25230. }
  25231. else if (light instanceof BABYLON.SpotLight) {
  25232. // Spot Light
  25233. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  25234. }
  25235. else if (light instanceof BABYLON.HemisphericLight) {
  25236. // Hemispheric Light
  25237. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  25238. }
  25239. };
  25240. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  25241. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25242. var lightIndex = 0;
  25243. var depthValuesAlreadySet = false;
  25244. for (var index = 0; index < scene.lights.length; index++) {
  25245. var light = scene.lights[index];
  25246. if (!light.isEnabled()) {
  25247. continue;
  25248. }
  25249. if (!light.canAffectMesh(mesh)) {
  25250. continue;
  25251. }
  25252. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25253. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  25254. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  25255. if (defines["SPECULARTERM"]) {
  25256. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  25257. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  25258. }
  25259. // Shadows
  25260. if (scene.shadowsEnabled) {
  25261. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  25262. }
  25263. lightIndex++;
  25264. if (lightIndex === maxSimultaneousLights)
  25265. break;
  25266. }
  25267. };
  25268. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25269. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25270. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25271. effect.setColor3("vFogColor", scene.fogColor);
  25272. }
  25273. };
  25274. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25275. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25276. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25277. if (matrices) {
  25278. effect.setMatrices("mBones", matrices);
  25279. }
  25280. }
  25281. };
  25282. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25283. if (defines["LOGARITHMICDEPTH"]) {
  25284. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25285. }
  25286. };
  25287. MaterialHelper.BindClipPlane = function (effect, scene) {
  25288. if (scene.clipPlane) {
  25289. var clipPlane = scene.clipPlane;
  25290. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25291. }
  25292. };
  25293. return MaterialHelper;
  25294. }());
  25295. BABYLON.MaterialHelper = MaterialHelper;
  25296. })(BABYLON || (BABYLON = {}));
  25297. var BABYLON;
  25298. (function (BABYLON) {
  25299. var FresnelParameters = (function () {
  25300. function FresnelParameters() {
  25301. this.isEnabled = true;
  25302. this.leftColor = BABYLON.Color3.White();
  25303. this.rightColor = BABYLON.Color3.Black();
  25304. this.bias = 0;
  25305. this.power = 1;
  25306. }
  25307. FresnelParameters.prototype.clone = function () {
  25308. var newFresnelParameters = new FresnelParameters();
  25309. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  25310. return newFresnelParameters;
  25311. };
  25312. FresnelParameters.prototype.serialize = function () {
  25313. var serializationObject = {};
  25314. serializationObject.isEnabled = this.isEnabled;
  25315. serializationObject.leftColor = this.leftColor;
  25316. serializationObject.rightColor = this.rightColor;
  25317. serializationObject.bias = this.bias;
  25318. serializationObject.power = this.power;
  25319. return serializationObject;
  25320. };
  25321. FresnelParameters.Parse = function (parsedFresnelParameters) {
  25322. var fresnelParameters = new FresnelParameters();
  25323. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  25324. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  25325. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  25326. fresnelParameters.bias = parsedFresnelParameters.bias;
  25327. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  25328. return fresnelParameters;
  25329. };
  25330. return FresnelParameters;
  25331. }());
  25332. BABYLON.FresnelParameters = FresnelParameters;
  25333. })(BABYLON || (BABYLON = {}));
  25334. var BABYLON;
  25335. (function (BABYLON) {
  25336. var MaterialDefines = (function () {
  25337. function MaterialDefines() {
  25338. }
  25339. MaterialDefines.prototype.rebuild = function () {
  25340. if (this._keys) {
  25341. delete this._keys;
  25342. }
  25343. this._keys = Object.keys(this);
  25344. };
  25345. MaterialDefines.prototype.isEqual = function (other) {
  25346. if (this._keys.length !== other._keys.length) {
  25347. return false;
  25348. }
  25349. for (var index = 0; index < this._keys.length; index++) {
  25350. var prop = this._keys[index];
  25351. if (this[prop] !== other[prop]) {
  25352. return false;
  25353. }
  25354. }
  25355. return true;
  25356. };
  25357. MaterialDefines.prototype.cloneTo = function (other) {
  25358. if (this._keys.length !== other._keys.length) {
  25359. other._keys = this._keys.slice(0);
  25360. }
  25361. for (var index = 0; index < this._keys.length; index++) {
  25362. var prop = this._keys[index];
  25363. other[prop] = this[prop];
  25364. }
  25365. };
  25366. MaterialDefines.prototype.reset = function () {
  25367. for (var index = 0; index < this._keys.length; index++) {
  25368. var prop = this._keys[index];
  25369. if (typeof (this[prop]) === "number") {
  25370. this[prop] = 0;
  25371. }
  25372. else {
  25373. this[prop] = false;
  25374. }
  25375. }
  25376. };
  25377. MaterialDefines.prototype.toString = function () {
  25378. var result = "";
  25379. for (var index = 0; index < this._keys.length; index++) {
  25380. var prop = this._keys[index];
  25381. if (typeof (this[prop]) === "number") {
  25382. result += "#define " + prop + " " + this[prop] + "\n";
  25383. }
  25384. else if (this[prop]) {
  25385. result += "#define " + prop + "\n";
  25386. }
  25387. }
  25388. return result;
  25389. };
  25390. return MaterialDefines;
  25391. }());
  25392. BABYLON.MaterialDefines = MaterialDefines;
  25393. var Material = (function () {
  25394. function Material(name, scene, doNotAdd) {
  25395. this.name = name;
  25396. this.checkReadyOnEveryCall = false;
  25397. this.checkReadyOnlyOnce = false;
  25398. this.state = "";
  25399. this.alpha = 1.0;
  25400. this.backFaceCulling = true;
  25401. /**
  25402. * An event triggered when the material is disposed.
  25403. * @type {BABYLON.Observable}
  25404. */
  25405. this.onDisposeObservable = new BABYLON.Observable();
  25406. /**
  25407. * An event triggered when the material is bound.
  25408. * @type {BABYLON.Observable}
  25409. */
  25410. this.onBindObservable = new BABYLON.Observable();
  25411. /**
  25412. * An event triggered when the material is unbound.
  25413. * @type {BABYLON.Observable}
  25414. */
  25415. this.onUnBindObservable = new BABYLON.Observable();
  25416. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25417. this.disableDepthWrite = false;
  25418. this.fogEnabled = true;
  25419. this.pointSize = 1.0;
  25420. this.zOffset = 0;
  25421. this._wasPreviouslyReady = false;
  25422. this._fillMode = Material.TriangleFillMode;
  25423. this.id = name;
  25424. this._scene = scene;
  25425. if (scene.useRightHandedSystem) {
  25426. this.sideOrientation = Material.ClockWiseSideOrientation;
  25427. }
  25428. else {
  25429. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25430. }
  25431. if (!doNotAdd) {
  25432. scene.materials.push(this);
  25433. }
  25434. }
  25435. Object.defineProperty(Material, "TriangleFillMode", {
  25436. get: function () {
  25437. return Material._TriangleFillMode;
  25438. },
  25439. enumerable: true,
  25440. configurable: true
  25441. });
  25442. Object.defineProperty(Material, "WireFrameFillMode", {
  25443. get: function () {
  25444. return Material._WireFrameFillMode;
  25445. },
  25446. enumerable: true,
  25447. configurable: true
  25448. });
  25449. Object.defineProperty(Material, "PointFillMode", {
  25450. get: function () {
  25451. return Material._PointFillMode;
  25452. },
  25453. enumerable: true,
  25454. configurable: true
  25455. });
  25456. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25457. get: function () {
  25458. return Material._ClockWiseSideOrientation;
  25459. },
  25460. enumerable: true,
  25461. configurable: true
  25462. });
  25463. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25464. get: function () {
  25465. return Material._CounterClockWiseSideOrientation;
  25466. },
  25467. enumerable: true,
  25468. configurable: true
  25469. });
  25470. Object.defineProperty(Material.prototype, "onDispose", {
  25471. set: function (callback) {
  25472. if (this._onDisposeObserver) {
  25473. this.onDisposeObservable.remove(this._onDisposeObserver);
  25474. }
  25475. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25476. },
  25477. enumerable: true,
  25478. configurable: true
  25479. });
  25480. Object.defineProperty(Material.prototype, "onBind", {
  25481. set: function (callback) {
  25482. if (this._onBindObserver) {
  25483. this.onBindObservable.remove(this._onBindObserver);
  25484. }
  25485. this._onBindObserver = this.onBindObservable.add(callback);
  25486. },
  25487. enumerable: true,
  25488. configurable: true
  25489. });
  25490. Object.defineProperty(Material.prototype, "wireframe", {
  25491. get: function () {
  25492. return this._fillMode === Material.WireFrameFillMode;
  25493. },
  25494. set: function (value) {
  25495. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25496. },
  25497. enumerable: true,
  25498. configurable: true
  25499. });
  25500. Object.defineProperty(Material.prototype, "pointsCloud", {
  25501. get: function () {
  25502. return this._fillMode === Material.PointFillMode;
  25503. },
  25504. set: function (value) {
  25505. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25506. },
  25507. enumerable: true,
  25508. configurable: true
  25509. });
  25510. Object.defineProperty(Material.prototype, "fillMode", {
  25511. get: function () {
  25512. return this._fillMode;
  25513. },
  25514. set: function (value) {
  25515. this._fillMode = value;
  25516. },
  25517. enumerable: true,
  25518. configurable: true
  25519. });
  25520. /**
  25521. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25522. * subclasses should override adding information pertainent to themselves
  25523. */
  25524. Material.prototype.toString = function (fullDetails) {
  25525. var ret = "Name: " + this.name;
  25526. if (fullDetails) {
  25527. }
  25528. return ret;
  25529. };
  25530. Object.defineProperty(Material.prototype, "isFrozen", {
  25531. get: function () {
  25532. return this.checkReadyOnlyOnce;
  25533. },
  25534. enumerable: true,
  25535. configurable: true
  25536. });
  25537. Material.prototype.freeze = function () {
  25538. this.checkReadyOnlyOnce = true;
  25539. };
  25540. Material.prototype.unfreeze = function () {
  25541. this.checkReadyOnlyOnce = false;
  25542. };
  25543. Material.prototype.isReady = function (mesh, useInstances) {
  25544. return true;
  25545. };
  25546. Material.prototype.getEffect = function () {
  25547. return this._effect;
  25548. };
  25549. Material.prototype.getScene = function () {
  25550. return this._scene;
  25551. };
  25552. Material.prototype.needAlphaBlending = function () {
  25553. return (this.alpha < 1.0);
  25554. };
  25555. Material.prototype.needAlphaTesting = function () {
  25556. return false;
  25557. };
  25558. Material.prototype.getAlphaTestTexture = function () {
  25559. return null;
  25560. };
  25561. Material.prototype.markDirty = function () {
  25562. this._wasPreviouslyReady = false;
  25563. };
  25564. Material.prototype._preBind = function () {
  25565. var engine = this._scene.getEngine();
  25566. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25567. engine.enableEffect(this._effect);
  25568. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25569. };
  25570. Material.prototype.bind = function (world, mesh) {
  25571. this._scene._cachedMaterial = this;
  25572. this.onBindObservable.notifyObservers(mesh);
  25573. if (this.disableDepthWrite) {
  25574. var engine = this._scene.getEngine();
  25575. this._cachedDepthWriteState = engine.getDepthWrite();
  25576. engine.setDepthWrite(false);
  25577. }
  25578. };
  25579. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25580. };
  25581. Material.prototype.unbind = function () {
  25582. this.onUnBindObservable.notifyObservers(this);
  25583. if (this.disableDepthWrite) {
  25584. var engine = this._scene.getEngine();
  25585. engine.setDepthWrite(this._cachedDepthWriteState);
  25586. }
  25587. };
  25588. Material.prototype.clone = function (name) {
  25589. return null;
  25590. };
  25591. Material.prototype.getBindedMeshes = function () {
  25592. var result = new Array();
  25593. for (var index = 0; index < this._scene.meshes.length; index++) {
  25594. var mesh = this._scene.meshes[index];
  25595. if (mesh.material === this) {
  25596. result.push(mesh);
  25597. }
  25598. }
  25599. return result;
  25600. };
  25601. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25602. // Animations
  25603. this.getScene().stopAnimation(this);
  25604. // Remove from scene
  25605. var index = this._scene.materials.indexOf(this);
  25606. if (index >= 0) {
  25607. this._scene.materials.splice(index, 1);
  25608. }
  25609. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25610. if (forceDisposeEffect && this._effect) {
  25611. this._scene.getEngine()._releaseEffect(this._effect);
  25612. this._effect = null;
  25613. }
  25614. // Remove from meshes
  25615. for (index = 0; index < this._scene.meshes.length; index++) {
  25616. var mesh = this._scene.meshes[index];
  25617. if (mesh.material === this) {
  25618. mesh.material = null;
  25619. }
  25620. }
  25621. // Callback
  25622. this.onDisposeObservable.notifyObservers(this);
  25623. this.onDisposeObservable.clear();
  25624. this.onBindObservable.clear();
  25625. this.onUnBindObservable.clear();
  25626. };
  25627. Material.prototype.serialize = function () {
  25628. return BABYLON.SerializationHelper.Serialize(this);
  25629. };
  25630. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25631. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25632. multiMaterial.id = parsedMultiMaterial.id;
  25633. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25634. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25635. var subMatId = parsedMultiMaterial.materials[matIndex];
  25636. if (subMatId) {
  25637. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25638. }
  25639. else {
  25640. multiMaterial.subMaterials.push(null);
  25641. }
  25642. }
  25643. return multiMaterial;
  25644. };
  25645. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25646. if (!parsedMaterial.customType) {
  25647. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25648. }
  25649. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25650. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25651. ;
  25652. };
  25653. Material._TriangleFillMode = 0;
  25654. Material._WireFrameFillMode = 1;
  25655. Material._PointFillMode = 2;
  25656. Material._ClockWiseSideOrientation = 0;
  25657. Material._CounterClockWiseSideOrientation = 1;
  25658. __decorate([
  25659. BABYLON.serialize()
  25660. ], Material.prototype, "id", void 0);
  25661. __decorate([
  25662. BABYLON.serialize()
  25663. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25664. __decorate([
  25665. BABYLON.serialize()
  25666. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25667. __decorate([
  25668. BABYLON.serialize()
  25669. ], Material.prototype, "state", void 0);
  25670. __decorate([
  25671. BABYLON.serialize()
  25672. ], Material.prototype, "alpha", void 0);
  25673. __decorate([
  25674. BABYLON.serialize()
  25675. ], Material.prototype, "backFaceCulling", void 0);
  25676. __decorate([
  25677. BABYLON.serialize()
  25678. ], Material.prototype, "sideOrientation", void 0);
  25679. __decorate([
  25680. BABYLON.serialize()
  25681. ], Material.prototype, "alphaMode", void 0);
  25682. __decorate([
  25683. BABYLON.serialize()
  25684. ], Material.prototype, "disableDepthWrite", void 0);
  25685. __decorate([
  25686. BABYLON.serialize()
  25687. ], Material.prototype, "fogEnabled", void 0);
  25688. __decorate([
  25689. BABYLON.serialize()
  25690. ], Material.prototype, "pointSize", void 0);
  25691. __decorate([
  25692. BABYLON.serialize()
  25693. ], Material.prototype, "zOffset", void 0);
  25694. __decorate([
  25695. BABYLON.serialize()
  25696. ], Material.prototype, "wireframe", null);
  25697. __decorate([
  25698. BABYLON.serialize()
  25699. ], Material.prototype, "pointsCloud", null);
  25700. __decorate([
  25701. BABYLON.serialize()
  25702. ], Material.prototype, "fillMode", null);
  25703. return Material;
  25704. }());
  25705. BABYLON.Material = Material;
  25706. })(BABYLON || (BABYLON = {}));
  25707. var BABYLON;
  25708. (function (BABYLON) {
  25709. var StandardMaterialDefines = (function (_super) {
  25710. __extends(StandardMaterialDefines, _super);
  25711. function StandardMaterialDefines() {
  25712. _super.call(this);
  25713. this.DIFFUSE = false;
  25714. this.AMBIENT = false;
  25715. this.OPACITY = false;
  25716. this.OPACITYRGB = false;
  25717. this.REFLECTION = false;
  25718. this.EMISSIVE = false;
  25719. this.SPECULAR = false;
  25720. this.BUMP = false;
  25721. this.PARALLAX = false;
  25722. this.PARALLAXOCCLUSION = false;
  25723. this.SPECULAROVERALPHA = false;
  25724. this.CLIPPLANE = false;
  25725. this.ALPHATEST = false;
  25726. this.ALPHAFROMDIFFUSE = false;
  25727. this.POINTSIZE = false;
  25728. this.FOG = false;
  25729. this.SPECULARTERM = false;
  25730. this.DIFFUSEFRESNEL = false;
  25731. this.OPACITYFRESNEL = false;
  25732. this.REFLECTIONFRESNEL = false;
  25733. this.REFRACTIONFRESNEL = false;
  25734. this.EMISSIVEFRESNEL = false;
  25735. this.FRESNEL = false;
  25736. this.NORMAL = false;
  25737. this.UV1 = false;
  25738. this.UV2 = false;
  25739. this.VERTEXCOLOR = false;
  25740. this.VERTEXALPHA = false;
  25741. this.NUM_BONE_INFLUENCERS = 0;
  25742. this.BonesPerMesh = 0;
  25743. this.INSTANCES = false;
  25744. this.GLOSSINESS = false;
  25745. this.ROUGHNESS = false;
  25746. this.EMISSIVEASILLUMINATION = false;
  25747. this.LINKEMISSIVEWITHDIFFUSE = false;
  25748. this.REFLECTIONFRESNELFROMSPECULAR = false;
  25749. this.LIGHTMAP = false;
  25750. this.USELIGHTMAPASSHADOWMAP = false;
  25751. this.REFLECTIONMAP_3D = false;
  25752. this.REFLECTIONMAP_SPHERICAL = false;
  25753. this.REFLECTIONMAP_PLANAR = false;
  25754. this.REFLECTIONMAP_CUBIC = false;
  25755. this.REFLECTIONMAP_PROJECTION = false;
  25756. this.REFLECTIONMAP_SKYBOX = false;
  25757. this.REFLECTIONMAP_EXPLICIT = false;
  25758. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  25759. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  25760. this.INVERTCUBICMAP = false;
  25761. this.LOGARITHMICDEPTH = false;
  25762. this.REFRACTION = false;
  25763. this.REFRACTIONMAP_3D = false;
  25764. this.REFLECTIONOVERALPHA = false;
  25765. this.INVERTNORMALMAPX = false;
  25766. this.INVERTNORMALMAPY = false;
  25767. this.SHADOWFULLFLOAT = false;
  25768. this.CAMERACOLORGRADING = false;
  25769. this.CAMERACOLORCURVES = false;
  25770. this.rebuild();
  25771. }
  25772. return StandardMaterialDefines;
  25773. }(BABYLON.MaterialDefines));
  25774. var StandardMaterial = (function (_super) {
  25775. __extends(StandardMaterial, _super);
  25776. function StandardMaterial(name, scene) {
  25777. var _this = this;
  25778. _super.call(this, name, scene);
  25779. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  25780. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  25781. this.specularColor = new BABYLON.Color3(1, 1, 1);
  25782. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  25783. this.specularPower = 64;
  25784. this.useAlphaFromDiffuseTexture = false;
  25785. this.useEmissiveAsIllumination = false;
  25786. this.linkEmissiveWithDiffuse = false;
  25787. this.useReflectionFresnelFromSpecular = false;
  25788. this.useSpecularOverAlpha = false;
  25789. this.useReflectionOverAlpha = false;
  25790. this.disableLighting = false;
  25791. this.useParallax = false;
  25792. this.useParallaxOcclusion = false;
  25793. this.parallaxScaleBias = 0.05;
  25794. this.roughness = 0;
  25795. this.indexOfRefraction = 0.98;
  25796. this.invertRefractionY = true;
  25797. this.useLightmapAsShadowmap = false;
  25798. this.useGlossinessFromSpecularMapAlpha = false;
  25799. this.maxSimultaneousLights = 4;
  25800. /**
  25801. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  25802. */
  25803. this.invertNormalMapX = false;
  25804. /**
  25805. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  25806. */
  25807. this.invertNormalMapY = false;
  25808. /**
  25809. * Color Grading 2D Lookup Texture.
  25810. * This allows special effects like sepia, black and white to sixties rendering style.
  25811. */
  25812. this.cameraColorGradingTexture = null;
  25813. /**
  25814. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  25815. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  25816. * 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;
  25817. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  25818. */
  25819. this.cameraColorCurves = null;
  25820. this._renderTargets = new BABYLON.SmartArray(16);
  25821. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  25822. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  25823. this._defines = new StandardMaterialDefines();
  25824. this._cachedDefines = new StandardMaterialDefines();
  25825. this._cachedDefines.BonesPerMesh = -1;
  25826. this.getRenderTargetTextures = function () {
  25827. _this._renderTargets.reset();
  25828. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  25829. _this._renderTargets.push(_this.reflectionTexture);
  25830. }
  25831. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  25832. _this._renderTargets.push(_this.refractionTexture);
  25833. }
  25834. return _this._renderTargets;
  25835. };
  25836. }
  25837. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  25838. get: function () {
  25839. return this._useLogarithmicDepth;
  25840. },
  25841. set: function (value) {
  25842. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  25843. },
  25844. enumerable: true,
  25845. configurable: true
  25846. });
  25847. StandardMaterial.prototype.needAlphaBlending = function () {
  25848. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  25849. };
  25850. StandardMaterial.prototype.needAlphaTesting = function () {
  25851. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  25852. };
  25853. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  25854. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  25855. };
  25856. StandardMaterial.prototype.getAlphaTestTexture = function () {
  25857. return this.diffuseTexture;
  25858. };
  25859. // Methods
  25860. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  25861. if (!mesh) {
  25862. return true;
  25863. }
  25864. if (this._defines.INSTANCES !== useInstances) {
  25865. return false;
  25866. }
  25867. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  25868. return true;
  25869. }
  25870. return false;
  25871. };
  25872. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  25873. if (this.isFrozen) {
  25874. if (this._wasPreviouslyReady) {
  25875. return true;
  25876. }
  25877. }
  25878. var scene = this.getScene();
  25879. if (!this.checkReadyOnEveryCall) {
  25880. if (this._renderId === scene.getRenderId()) {
  25881. if (this._checkCache(scene, mesh, useInstances)) {
  25882. return true;
  25883. }
  25884. }
  25885. }
  25886. var engine = scene.getEngine();
  25887. var needNormals = false;
  25888. var needUVs = false;
  25889. this._defines.reset();
  25890. // Textures
  25891. if (scene.texturesEnabled) {
  25892. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  25893. if (!this.diffuseTexture.isReady()) {
  25894. return false;
  25895. }
  25896. else {
  25897. needUVs = true;
  25898. this._defines.DIFFUSE = true;
  25899. }
  25900. }
  25901. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  25902. if (!this.ambientTexture.isReady()) {
  25903. return false;
  25904. }
  25905. else {
  25906. needUVs = true;
  25907. this._defines.AMBIENT = true;
  25908. }
  25909. }
  25910. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  25911. if (!this.opacityTexture.isReady()) {
  25912. return false;
  25913. }
  25914. else {
  25915. needUVs = true;
  25916. this._defines.OPACITY = true;
  25917. if (this.opacityTexture.getAlphaFromRGB) {
  25918. this._defines.OPACITYRGB = true;
  25919. }
  25920. }
  25921. }
  25922. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  25923. if (!this.reflectionTexture.isReady()) {
  25924. return false;
  25925. }
  25926. else {
  25927. needNormals = true;
  25928. this._defines.REFLECTION = true;
  25929. if (this.roughness > 0) {
  25930. this._defines.ROUGHNESS = true;
  25931. }
  25932. if (this.useReflectionOverAlpha) {
  25933. this._defines.REFLECTIONOVERALPHA = true;
  25934. }
  25935. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  25936. this._defines.INVERTCUBICMAP = true;
  25937. }
  25938. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  25939. switch (this.reflectionTexture.coordinatesMode) {
  25940. case BABYLON.Texture.CUBIC_MODE:
  25941. case BABYLON.Texture.INVCUBIC_MODE:
  25942. this._defines.REFLECTIONMAP_CUBIC = true;
  25943. break;
  25944. case BABYLON.Texture.EXPLICIT_MODE:
  25945. this._defines.REFLECTIONMAP_EXPLICIT = true;
  25946. break;
  25947. case BABYLON.Texture.PLANAR_MODE:
  25948. this._defines.REFLECTIONMAP_PLANAR = true;
  25949. break;
  25950. case BABYLON.Texture.PROJECTION_MODE:
  25951. this._defines.REFLECTIONMAP_PROJECTION = true;
  25952. break;
  25953. case BABYLON.Texture.SKYBOX_MODE:
  25954. this._defines.REFLECTIONMAP_SKYBOX = true;
  25955. break;
  25956. case BABYLON.Texture.SPHERICAL_MODE:
  25957. this._defines.REFLECTIONMAP_SPHERICAL = true;
  25958. break;
  25959. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  25960. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  25961. break;
  25962. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  25963. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  25964. break;
  25965. }
  25966. }
  25967. }
  25968. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  25969. if (!this.emissiveTexture.isReady()) {
  25970. return false;
  25971. }
  25972. else {
  25973. needUVs = true;
  25974. this._defines.EMISSIVE = true;
  25975. }
  25976. }
  25977. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  25978. if (!this.lightmapTexture.isReady()) {
  25979. return false;
  25980. }
  25981. else {
  25982. needUVs = true;
  25983. this._defines.LIGHTMAP = true;
  25984. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  25985. }
  25986. }
  25987. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  25988. if (!this.specularTexture.isReady()) {
  25989. return false;
  25990. }
  25991. else {
  25992. needUVs = true;
  25993. this._defines.SPECULAR = true;
  25994. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  25995. }
  25996. }
  25997. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  25998. if (!this.bumpTexture.isReady()) {
  25999. return false;
  26000. }
  26001. else {
  26002. needUVs = true;
  26003. this._defines.BUMP = true;
  26004. if (this.useParallax) {
  26005. this._defines.PARALLAX = true;
  26006. if (this.useParallaxOcclusion) {
  26007. this._defines.PARALLAXOCCLUSION = true;
  26008. }
  26009. }
  26010. if (this.invertNormalMapX) {
  26011. this._defines.INVERTNORMALMAPX = true;
  26012. }
  26013. if (this.invertNormalMapY) {
  26014. this._defines.INVERTNORMALMAPY = true;
  26015. }
  26016. }
  26017. }
  26018. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26019. if (!this.refractionTexture.isReady()) {
  26020. return false;
  26021. }
  26022. else {
  26023. needUVs = true;
  26024. this._defines.REFRACTION = true;
  26025. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  26026. }
  26027. }
  26028. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26029. if (!this.cameraColorGradingTexture.isReady()) {
  26030. return false;
  26031. }
  26032. else {
  26033. this._defines.CAMERACOLORGRADING = true;
  26034. }
  26035. }
  26036. }
  26037. // Effect
  26038. if (scene.clipPlane) {
  26039. this._defines.CLIPPLANE = true;
  26040. }
  26041. if (engine.getAlphaTesting()) {
  26042. this._defines.ALPHATEST = true;
  26043. }
  26044. if (this._shouldUseAlphaFromDiffuseTexture()) {
  26045. this._defines.ALPHAFROMDIFFUSE = true;
  26046. }
  26047. if (this.useEmissiveAsIllumination) {
  26048. this._defines.EMISSIVEASILLUMINATION = true;
  26049. }
  26050. if (this.linkEmissiveWithDiffuse) {
  26051. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  26052. }
  26053. if (this.useLogarithmicDepth) {
  26054. this._defines.LOGARITHMICDEPTH = true;
  26055. }
  26056. if (this.cameraColorCurves) {
  26057. this._defines.CAMERACOLORCURVES = true;
  26058. }
  26059. // Point size
  26060. if (this.pointsCloud || scene.forcePointsCloud) {
  26061. this._defines.POINTSIZE = true;
  26062. }
  26063. // Fog
  26064. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26065. this._defines.FOG = true;
  26066. }
  26067. if (scene.lightsEnabled && !this.disableLighting) {
  26068. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  26069. }
  26070. if (StandardMaterial.FresnelEnabled) {
  26071. // Fresnel
  26072. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  26073. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  26074. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  26075. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  26076. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26077. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26078. this._defines.DIFFUSEFRESNEL = true;
  26079. }
  26080. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26081. this._defines.OPACITYFRESNEL = true;
  26082. }
  26083. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26084. this._defines.REFLECTIONFRESNEL = true;
  26085. if (this.useReflectionFresnelFromSpecular) {
  26086. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  26087. }
  26088. }
  26089. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26090. this._defines.REFRACTIONFRESNEL = true;
  26091. }
  26092. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26093. this._defines.EMISSIVEFRESNEL = true;
  26094. }
  26095. needNormals = true;
  26096. this._defines.FRESNEL = true;
  26097. }
  26098. }
  26099. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  26100. this._defines.SPECULAROVERALPHA = true;
  26101. }
  26102. // Attribs
  26103. if (mesh) {
  26104. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26105. this._defines.NORMAL = true;
  26106. }
  26107. if (needUVs) {
  26108. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26109. this._defines.UV1 = true;
  26110. }
  26111. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26112. this._defines.UV2 = true;
  26113. }
  26114. }
  26115. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26116. this._defines.VERTEXCOLOR = true;
  26117. if (mesh.hasVertexAlpha) {
  26118. this._defines.VERTEXALPHA = true;
  26119. }
  26120. }
  26121. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  26122. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  26123. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  26124. }
  26125. // Instances
  26126. if (useInstances) {
  26127. this._defines.INSTANCES = true;
  26128. }
  26129. }
  26130. // Get correct effect
  26131. if (!this._defines.isEqual(this._cachedDefines)) {
  26132. this._defines.cloneTo(this._cachedDefines);
  26133. scene.resetCachedMaterial();
  26134. // Fallbacks
  26135. var fallbacks = new BABYLON.EffectFallbacks();
  26136. if (this._defines.REFLECTION) {
  26137. fallbacks.addFallback(0, "REFLECTION");
  26138. }
  26139. if (this._defines.SPECULAR) {
  26140. fallbacks.addFallback(0, "SPECULAR");
  26141. }
  26142. if (this._defines.BUMP) {
  26143. fallbacks.addFallback(0, "BUMP");
  26144. }
  26145. if (this._defines.PARALLAX) {
  26146. fallbacks.addFallback(1, "PARALLAX");
  26147. }
  26148. if (this._defines.PARALLAXOCCLUSION) {
  26149. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  26150. }
  26151. if (this._defines.SPECULAROVERALPHA) {
  26152. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  26153. }
  26154. if (this._defines.FOG) {
  26155. fallbacks.addFallback(1, "FOG");
  26156. }
  26157. if (this._defines.POINTSIZE) {
  26158. fallbacks.addFallback(0, "POINTSIZE");
  26159. }
  26160. if (this._defines.LOGARITHMICDEPTH) {
  26161. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  26162. }
  26163. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  26164. if (this._defines.SPECULARTERM) {
  26165. fallbacks.addFallback(0, "SPECULARTERM");
  26166. }
  26167. if (this._defines.DIFFUSEFRESNEL) {
  26168. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  26169. }
  26170. if (this._defines.OPACITYFRESNEL) {
  26171. fallbacks.addFallback(2, "OPACITYFRESNEL");
  26172. }
  26173. if (this._defines.REFLECTIONFRESNEL) {
  26174. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  26175. }
  26176. if (this._defines.EMISSIVEFRESNEL) {
  26177. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  26178. }
  26179. if (this._defines.FRESNEL) {
  26180. fallbacks.addFallback(4, "FRESNEL");
  26181. }
  26182. //Attributes
  26183. var attribs = [BABYLON.VertexBuffer.PositionKind];
  26184. if (this._defines.NORMAL) {
  26185. attribs.push(BABYLON.VertexBuffer.NormalKind);
  26186. }
  26187. if (this._defines.UV1) {
  26188. attribs.push(BABYLON.VertexBuffer.UVKind);
  26189. }
  26190. if (this._defines.UV2) {
  26191. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26192. }
  26193. if (this._defines.VERTEXCOLOR) {
  26194. attribs.push(BABYLON.VertexBuffer.ColorKind);
  26195. }
  26196. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  26197. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  26198. var shaderName = "default";
  26199. var join = this._defines.toString();
  26200. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  26201. "vFogInfos", "vFogColor", "pointSize",
  26202. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  26203. "mBones",
  26204. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  26205. "depthValues",
  26206. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  26207. "logarithmicDepthConstant"
  26208. ];
  26209. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  26210. if (this._defines.CAMERACOLORCURVES) {
  26211. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  26212. }
  26213. if (this._defines.CAMERACOLORGRADING) {
  26214. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  26215. }
  26216. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  26217. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  26218. }
  26219. if (!this._effect.isReady()) {
  26220. return false;
  26221. }
  26222. this._renderId = scene.getRenderId();
  26223. this._wasPreviouslyReady = true;
  26224. if (mesh) {
  26225. if (!mesh._materialDefines) {
  26226. mesh._materialDefines = new StandardMaterialDefines();
  26227. }
  26228. this._defines.cloneTo(mesh._materialDefines);
  26229. }
  26230. return true;
  26231. };
  26232. StandardMaterial.prototype.unbind = function () {
  26233. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  26234. this._effect.setTexture("reflection2DSampler", null);
  26235. }
  26236. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  26237. this._effect.setTexture("refraction2DSampler", null);
  26238. }
  26239. _super.prototype.unbind.call(this);
  26240. };
  26241. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26242. this._effect.setMatrix("world", world);
  26243. };
  26244. StandardMaterial.prototype.bind = function (world, mesh) {
  26245. var scene = this.getScene();
  26246. // Matrices
  26247. this.bindOnlyWorldMatrix(world);
  26248. // Bones
  26249. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  26250. if (scene.getCachedMaterial() !== this) {
  26251. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26252. if (StandardMaterial.FresnelEnabled) {
  26253. // Fresnel
  26254. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26255. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  26256. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  26257. }
  26258. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26259. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  26260. }
  26261. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26262. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  26263. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  26264. }
  26265. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26266. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  26267. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  26268. }
  26269. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26270. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  26271. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  26272. }
  26273. }
  26274. // Textures
  26275. if (scene.texturesEnabled) {
  26276. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26277. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  26278. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  26279. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  26280. }
  26281. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26282. this._effect.setTexture("ambientSampler", this.ambientTexture);
  26283. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  26284. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  26285. }
  26286. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26287. this._effect.setTexture("opacitySampler", this.opacityTexture);
  26288. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  26289. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  26290. }
  26291. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26292. if (this.reflectionTexture.isCube) {
  26293. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  26294. }
  26295. else {
  26296. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  26297. }
  26298. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  26299. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  26300. }
  26301. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26302. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  26303. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  26304. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  26305. }
  26306. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26307. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  26308. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  26309. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  26310. }
  26311. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26312. this._effect.setTexture("specularSampler", this.specularTexture);
  26313. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  26314. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  26315. }
  26316. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  26317. this._effect.setTexture("bumpSampler", this.bumpTexture);
  26318. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  26319. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  26320. }
  26321. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26322. var depth = 1.0;
  26323. if (this.refractionTexture.isCube) {
  26324. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  26325. }
  26326. else {
  26327. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  26328. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  26329. if (this.refractionTexture.depth) {
  26330. depth = this.refractionTexture.depth;
  26331. }
  26332. }
  26333. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  26334. }
  26335. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26336. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  26337. }
  26338. }
  26339. // Clip plane
  26340. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  26341. // Point size
  26342. if (this.pointsCloud) {
  26343. this._effect.setFloat("pointSize", this.pointSize);
  26344. }
  26345. // Colors
  26346. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  26347. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  26348. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  26349. if (this._defines.SPECULARTERM) {
  26350. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  26351. }
  26352. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  26353. }
  26354. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  26355. // Diffuse
  26356. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  26357. // Lights
  26358. if (scene.lightsEnabled && !this.disableLighting) {
  26359. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  26360. }
  26361. // View
  26362. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  26363. this._effect.setMatrix("view", scene.getViewMatrix());
  26364. }
  26365. // Fog
  26366. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  26367. // Log. depth
  26368. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  26369. // Color Curves
  26370. if (this.cameraColorCurves) {
  26371. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  26372. }
  26373. }
  26374. _super.prototype.bind.call(this, world, mesh);
  26375. };
  26376. StandardMaterial.prototype.getAnimatables = function () {
  26377. var results = [];
  26378. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  26379. results.push(this.diffuseTexture);
  26380. }
  26381. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  26382. results.push(this.ambientTexture);
  26383. }
  26384. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  26385. results.push(this.opacityTexture);
  26386. }
  26387. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  26388. results.push(this.reflectionTexture);
  26389. }
  26390. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  26391. results.push(this.emissiveTexture);
  26392. }
  26393. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  26394. results.push(this.specularTexture);
  26395. }
  26396. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  26397. results.push(this.bumpTexture);
  26398. }
  26399. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  26400. results.push(this.lightmapTexture);
  26401. }
  26402. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  26403. results.push(this.refractionTexture);
  26404. }
  26405. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  26406. results.push(this.cameraColorGradingTexture);
  26407. }
  26408. return results;
  26409. };
  26410. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26411. if (forceDisposeTextures) {
  26412. if (this.diffuseTexture) {
  26413. this.diffuseTexture.dispose();
  26414. }
  26415. if (this.ambientTexture) {
  26416. this.ambientTexture.dispose();
  26417. }
  26418. if (this.opacityTexture) {
  26419. this.opacityTexture.dispose();
  26420. }
  26421. if (this.reflectionTexture) {
  26422. this.reflectionTexture.dispose();
  26423. }
  26424. if (this.emissiveTexture) {
  26425. this.emissiveTexture.dispose();
  26426. }
  26427. if (this.specularTexture) {
  26428. this.specularTexture.dispose();
  26429. }
  26430. if (this.bumpTexture) {
  26431. this.bumpTexture.dispose();
  26432. }
  26433. if (this.lightmapTexture) {
  26434. this.lightmapTexture.dispose();
  26435. }
  26436. if (this.refractionTexture) {
  26437. this.refractionTexture.dispose();
  26438. }
  26439. if (this.cameraColorGradingTexture) {
  26440. this.cameraColorGradingTexture.dispose();
  26441. }
  26442. }
  26443. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  26444. };
  26445. StandardMaterial.prototype.clone = function (name) {
  26446. var _this = this;
  26447. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  26448. };
  26449. StandardMaterial.prototype.serialize = function () {
  26450. return BABYLON.SerializationHelper.Serialize(this);
  26451. };
  26452. // Statics
  26453. StandardMaterial.Parse = function (source, scene, rootUrl) {
  26454. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  26455. };
  26456. // Flags used to enable or disable a type of texture for all Standard Materials
  26457. StandardMaterial.DiffuseTextureEnabled = true;
  26458. StandardMaterial.AmbientTextureEnabled = true;
  26459. StandardMaterial.OpacityTextureEnabled = true;
  26460. StandardMaterial.ReflectionTextureEnabled = true;
  26461. StandardMaterial.EmissiveTextureEnabled = true;
  26462. StandardMaterial.SpecularTextureEnabled = true;
  26463. StandardMaterial.BumpTextureEnabled = true;
  26464. StandardMaterial.FresnelEnabled = true;
  26465. StandardMaterial.LightmapTextureEnabled = true;
  26466. StandardMaterial.RefractionTextureEnabled = true;
  26467. StandardMaterial.ColorGradingTextureEnabled = true;
  26468. __decorate([
  26469. BABYLON.serializeAsTexture()
  26470. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  26471. __decorate([
  26472. BABYLON.serializeAsTexture()
  26473. ], StandardMaterial.prototype, "ambientTexture", void 0);
  26474. __decorate([
  26475. BABYLON.serializeAsTexture()
  26476. ], StandardMaterial.prototype, "opacityTexture", void 0);
  26477. __decorate([
  26478. BABYLON.serializeAsTexture()
  26479. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  26480. __decorate([
  26481. BABYLON.serializeAsTexture()
  26482. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  26483. __decorate([
  26484. BABYLON.serializeAsTexture()
  26485. ], StandardMaterial.prototype, "specularTexture", void 0);
  26486. __decorate([
  26487. BABYLON.serializeAsTexture()
  26488. ], StandardMaterial.prototype, "bumpTexture", void 0);
  26489. __decorate([
  26490. BABYLON.serializeAsTexture()
  26491. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  26492. __decorate([
  26493. BABYLON.serializeAsTexture()
  26494. ], StandardMaterial.prototype, "refractionTexture", void 0);
  26495. __decorate([
  26496. BABYLON.serializeAsColor3("ambient")
  26497. ], StandardMaterial.prototype, "ambientColor", void 0);
  26498. __decorate([
  26499. BABYLON.serializeAsColor3("diffuse")
  26500. ], StandardMaterial.prototype, "diffuseColor", void 0);
  26501. __decorate([
  26502. BABYLON.serializeAsColor3("specular")
  26503. ], StandardMaterial.prototype, "specularColor", void 0);
  26504. __decorate([
  26505. BABYLON.serializeAsColor3("emissive")
  26506. ], StandardMaterial.prototype, "emissiveColor", void 0);
  26507. __decorate([
  26508. BABYLON.serialize()
  26509. ], StandardMaterial.prototype, "specularPower", void 0);
  26510. __decorate([
  26511. BABYLON.serialize()
  26512. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  26513. __decorate([
  26514. BABYLON.serialize()
  26515. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  26516. __decorate([
  26517. BABYLON.serialize()
  26518. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  26519. __decorate([
  26520. BABYLON.serialize()
  26521. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  26522. __decorate([
  26523. BABYLON.serialize()
  26524. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  26525. __decorate([
  26526. BABYLON.serialize()
  26527. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  26528. __decorate([
  26529. BABYLON.serialize()
  26530. ], StandardMaterial.prototype, "disableLighting", void 0);
  26531. __decorate([
  26532. BABYLON.serialize()
  26533. ], StandardMaterial.prototype, "useParallax", void 0);
  26534. __decorate([
  26535. BABYLON.serialize()
  26536. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  26537. __decorate([
  26538. BABYLON.serialize()
  26539. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  26540. __decorate([
  26541. BABYLON.serialize()
  26542. ], StandardMaterial.prototype, "roughness", void 0);
  26543. __decorate([
  26544. BABYLON.serialize()
  26545. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  26546. __decorate([
  26547. BABYLON.serialize()
  26548. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  26549. __decorate([
  26550. BABYLON.serialize()
  26551. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  26552. __decorate([
  26553. BABYLON.serializeAsFresnelParameters()
  26554. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  26555. __decorate([
  26556. BABYLON.serializeAsFresnelParameters()
  26557. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  26558. __decorate([
  26559. BABYLON.serializeAsFresnelParameters()
  26560. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  26561. __decorate([
  26562. BABYLON.serializeAsFresnelParameters()
  26563. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  26564. __decorate([
  26565. BABYLON.serializeAsFresnelParameters()
  26566. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  26567. __decorate([
  26568. BABYLON.serialize()
  26569. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  26570. __decorate([
  26571. BABYLON.serialize()
  26572. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  26573. __decorate([
  26574. BABYLON.serialize()
  26575. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  26576. __decorate([
  26577. BABYLON.serialize()
  26578. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  26579. __decorate([
  26580. BABYLON.serializeAsTexture()
  26581. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  26582. __decorate([
  26583. BABYLON.serializeAsColorCurves()
  26584. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  26585. __decorate([
  26586. BABYLON.serialize()
  26587. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  26588. return StandardMaterial;
  26589. }(BABYLON.Material));
  26590. BABYLON.StandardMaterial = StandardMaterial;
  26591. })(BABYLON || (BABYLON = {}));
  26592. var BABYLON;
  26593. (function (BABYLON) {
  26594. var MultiMaterial = (function (_super) {
  26595. __extends(MultiMaterial, _super);
  26596. function MultiMaterial(name, scene) {
  26597. _super.call(this, name, scene, true);
  26598. this.subMaterials = new Array();
  26599. scene.multiMaterials.push(this);
  26600. }
  26601. // Properties
  26602. MultiMaterial.prototype.getSubMaterial = function (index) {
  26603. if (index < 0 || index >= this.subMaterials.length) {
  26604. return this.getScene().defaultMaterial;
  26605. }
  26606. return this.subMaterials[index];
  26607. };
  26608. // Methods
  26609. MultiMaterial.prototype.isReady = function (mesh) {
  26610. for (var index = 0; index < this.subMaterials.length; index++) {
  26611. var subMaterial = this.subMaterials[index];
  26612. if (subMaterial) {
  26613. if (!this.subMaterials[index].isReady(mesh)) {
  26614. return false;
  26615. }
  26616. }
  26617. }
  26618. return true;
  26619. };
  26620. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  26621. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  26622. for (var index = 0; index < this.subMaterials.length; index++) {
  26623. var subMaterial = null;
  26624. if (cloneChildren) {
  26625. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  26626. }
  26627. else {
  26628. subMaterial = this.subMaterials[index];
  26629. }
  26630. newMultiMaterial.subMaterials.push(subMaterial);
  26631. }
  26632. return newMultiMaterial;
  26633. };
  26634. MultiMaterial.prototype.serialize = function () {
  26635. var serializationObject = {};
  26636. serializationObject.name = this.name;
  26637. serializationObject.id = this.id;
  26638. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26639. serializationObject.materials = [];
  26640. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  26641. var subMat = this.subMaterials[matIndex];
  26642. if (subMat) {
  26643. serializationObject.materials.push(subMat.id);
  26644. }
  26645. else {
  26646. serializationObject.materials.push(null);
  26647. }
  26648. }
  26649. return serializationObject;
  26650. };
  26651. return MultiMaterial;
  26652. }(BABYLON.Material));
  26653. BABYLON.MultiMaterial = MultiMaterial;
  26654. })(BABYLON || (BABYLON = {}));
  26655. var BABYLON;
  26656. (function (BABYLON) {
  26657. var SceneLoader = (function () {
  26658. function SceneLoader() {
  26659. }
  26660. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  26661. get: function () {
  26662. return 0;
  26663. },
  26664. enumerable: true,
  26665. configurable: true
  26666. });
  26667. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  26668. get: function () {
  26669. return 1;
  26670. },
  26671. enumerable: true,
  26672. configurable: true
  26673. });
  26674. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  26675. get: function () {
  26676. return 2;
  26677. },
  26678. enumerable: true,
  26679. configurable: true
  26680. });
  26681. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  26682. get: function () {
  26683. return 3;
  26684. },
  26685. enumerable: true,
  26686. configurable: true
  26687. });
  26688. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  26689. get: function () {
  26690. return SceneLoader._ForceFullSceneLoadingForIncremental;
  26691. },
  26692. set: function (value) {
  26693. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  26694. },
  26695. enumerable: true,
  26696. configurable: true
  26697. });
  26698. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  26699. get: function () {
  26700. return SceneLoader._ShowLoadingScreen;
  26701. },
  26702. set: function (value) {
  26703. SceneLoader._ShowLoadingScreen = value;
  26704. },
  26705. enumerable: true,
  26706. configurable: true
  26707. });
  26708. Object.defineProperty(SceneLoader, "loggingLevel", {
  26709. get: function () {
  26710. return SceneLoader._loggingLevel;
  26711. },
  26712. set: function (value) {
  26713. SceneLoader._loggingLevel = value;
  26714. },
  26715. enumerable: true,
  26716. configurable: true
  26717. });
  26718. SceneLoader._getDefaultPlugin = function () {
  26719. return SceneLoader._registeredPlugins[".babylon"];
  26720. };
  26721. SceneLoader._getPluginForExtension = function (extension) {
  26722. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  26723. if (registeredPlugin) {
  26724. return registeredPlugin;
  26725. }
  26726. return SceneLoader._getDefaultPlugin();
  26727. };
  26728. SceneLoader._getPluginForFilename = function (sceneFilename) {
  26729. if (sceneFilename.name) {
  26730. sceneFilename = sceneFilename.name;
  26731. }
  26732. var dotPosition = sceneFilename.lastIndexOf(".");
  26733. var queryStringPosition = sceneFilename.indexOf("?");
  26734. if (queryStringPosition === -1) {
  26735. queryStringPosition = sceneFilename.length;
  26736. }
  26737. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  26738. return SceneLoader._getPluginForExtension(extension);
  26739. };
  26740. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  26741. SceneLoader._getDirectLoad = function (sceneFilename) {
  26742. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  26743. return sceneFilename.substr(5);
  26744. }
  26745. return null;
  26746. };
  26747. // Public functions
  26748. SceneLoader.GetPluginForExtension = function (extension) {
  26749. return SceneLoader._getPluginForExtension(extension).plugin;
  26750. };
  26751. SceneLoader.RegisterPlugin = function (plugin) {
  26752. if (typeof plugin.extensions === "string") {
  26753. var extension = plugin.extensions;
  26754. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  26755. plugin: plugin,
  26756. isBinary: false
  26757. };
  26758. }
  26759. else {
  26760. var extensions = plugin.extensions;
  26761. Object.keys(extensions).forEach(function (extension) {
  26762. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  26763. plugin: plugin,
  26764. isBinary: extensions[extension].isBinary
  26765. };
  26766. });
  26767. }
  26768. };
  26769. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  26770. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26771. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26772. return;
  26773. }
  26774. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26775. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26776. return;
  26777. }
  26778. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  26779. var loadingToken = {};
  26780. scene._addPendingData(loadingToken);
  26781. var manifestChecked = function (success) {
  26782. scene.database = database;
  26783. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  26784. var plugin = registeredPlugin.plugin;
  26785. var useArrayBuffer = registeredPlugin.isBinary;
  26786. var importMeshFromData = function (data) {
  26787. var meshes = [];
  26788. var particleSystems = [];
  26789. var skeletons = [];
  26790. try {
  26791. if (plugin.importMesh) {
  26792. var syncedPlugin = plugin;
  26793. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  26794. if (onerror) {
  26795. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  26796. }
  26797. scene._removePendingData(loadingToken);
  26798. return;
  26799. }
  26800. if (onsuccess) {
  26801. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  26802. onsuccess(meshes, particleSystems, skeletons);
  26803. scene._removePendingData(loadingToken);
  26804. }
  26805. }
  26806. else {
  26807. var asyncedPlugin = plugin;
  26808. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  26809. if (onsuccess) {
  26810. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  26811. onsuccess(meshes, particleSystems, skeletons);
  26812. scene._removePendingData(loadingToken);
  26813. }
  26814. }, function () {
  26815. if (onerror) {
  26816. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  26817. }
  26818. scene._removePendingData(loadingToken);
  26819. });
  26820. }
  26821. }
  26822. catch (e) {
  26823. if (onerror) {
  26824. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  26825. }
  26826. scene._removePendingData(loadingToken);
  26827. }
  26828. };
  26829. if (directLoad) {
  26830. importMeshFromData(directLoad);
  26831. return;
  26832. }
  26833. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  26834. importMeshFromData(data);
  26835. }, progressCallBack, database, useArrayBuffer);
  26836. };
  26837. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  26838. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  26839. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  26840. }
  26841. else {
  26842. // If the scene is a data stream or offline support is not enabled, it's a direct load
  26843. manifestChecked(true);
  26844. }
  26845. };
  26846. /**
  26847. * Load a scene
  26848. * @param rootUrl a string that defines the root url for scene and resources
  26849. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  26850. * @param engine is the instance of BABYLON.Engine to use to create the scene
  26851. */
  26852. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  26853. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  26854. };
  26855. /**
  26856. * Append a scene
  26857. * @param rootUrl a string that defines the root url for scene and resources
  26858. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  26859. * @param scene is the instance of BABYLON.Scene to append to
  26860. */
  26861. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  26862. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26863. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26864. return;
  26865. }
  26866. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  26867. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  26868. var plugin = registeredPlugin.plugin;
  26869. var useArrayBuffer = registeredPlugin.isBinary;
  26870. var database;
  26871. var loadingToken = {};
  26872. scene._addPendingData(loadingToken);
  26873. if (SceneLoader.ShowLoadingScreen) {
  26874. scene.getEngine().displayLoadingUI();
  26875. }
  26876. var loadSceneFromData = function (data) {
  26877. scene.database = database;
  26878. if (plugin.load) {
  26879. var syncedPlugin = plugin;
  26880. if (!syncedPlugin.load(scene, data, rootUrl)) {
  26881. if (onerror) {
  26882. onerror(scene);
  26883. }
  26884. scene._removePendingData(loadingToken);
  26885. scene.getEngine().hideLoadingUI();
  26886. return;
  26887. }
  26888. if (onsuccess) {
  26889. onsuccess(scene);
  26890. }
  26891. scene._removePendingData(loadingToken);
  26892. }
  26893. else {
  26894. var asyncedPlugin = plugin;
  26895. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  26896. if (onsuccess) {
  26897. onsuccess(scene);
  26898. }
  26899. scene._removePendingData(loadingToken);
  26900. }, function () {
  26901. if (onerror) {
  26902. onerror(scene);
  26903. }
  26904. scene._removePendingData(loadingToken);
  26905. scene.getEngine().hideLoadingUI();
  26906. });
  26907. }
  26908. if (SceneLoader.ShowLoadingScreen) {
  26909. scene.executeWhenReady(function () {
  26910. scene.getEngine().hideLoadingUI();
  26911. });
  26912. }
  26913. };
  26914. var manifestChecked = function (success) {
  26915. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  26916. };
  26917. if (directLoad) {
  26918. loadSceneFromData(directLoad);
  26919. return;
  26920. }
  26921. if (rootUrl.indexOf("file:") === -1) {
  26922. if (scene.getEngine().enableOfflineSupport) {
  26923. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  26924. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  26925. }
  26926. else {
  26927. manifestChecked(true);
  26928. }
  26929. }
  26930. else {
  26931. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  26932. }
  26933. };
  26934. // Flags
  26935. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  26936. SceneLoader._ShowLoadingScreen = true;
  26937. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  26938. // Members
  26939. SceneLoader._registeredPlugins = {};
  26940. return SceneLoader;
  26941. }());
  26942. BABYLON.SceneLoader = SceneLoader;
  26943. ;
  26944. })(BABYLON || (BABYLON = {}));
  26945. var BABYLON;
  26946. (function (BABYLON) {
  26947. var Internals;
  26948. (function (Internals) {
  26949. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  26950. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  26951. var parsedMaterial = parsedData.materials[index];
  26952. if (parsedMaterial.id === id) {
  26953. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  26954. }
  26955. }
  26956. return null;
  26957. };
  26958. var isDescendantOf = function (mesh, names, hierarchyIds) {
  26959. names = (names instanceof Array) ? names : [names];
  26960. for (var i in names) {
  26961. if (mesh.name === names[i]) {
  26962. hierarchyIds.push(mesh.id);
  26963. return true;
  26964. }
  26965. }
  26966. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  26967. hierarchyIds.push(mesh.id);
  26968. return true;
  26969. }
  26970. return false;
  26971. };
  26972. var logOperation = function (operation, producer) {
  26973. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  26974. };
  26975. BABYLON.SceneLoader.RegisterPlugin({
  26976. extensions: ".babylon",
  26977. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  26978. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  26979. // when SceneLoader.debugLogging = true (default), or exception encountered.
  26980. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  26981. // and avoid problems with multiple concurrent .babylon loads.
  26982. var log = "importMesh has failed JSON parse";
  26983. try {
  26984. var parsedData = JSON.parse(data);
  26985. log = "";
  26986. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  26987. var loadedSkeletonsIds = [];
  26988. var loadedMaterialsIds = [];
  26989. var hierarchyIds = [];
  26990. var index;
  26991. var cache;
  26992. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  26993. var parsedMesh = parsedData.meshes[index];
  26994. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  26995. if (meshesNames instanceof Array) {
  26996. // Remove found mesh name from list.
  26997. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  26998. }
  26999. //Geometry?
  27000. if (parsedMesh.geometryId) {
  27001. //does the file contain geometries?
  27002. if (parsedData.geometries) {
  27003. //find the correct geometry and add it to the scene
  27004. var found = false;
  27005. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  27006. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  27007. return;
  27008. }
  27009. else {
  27010. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  27011. if (parsedGeometryData.id === parsedMesh.geometryId) {
  27012. switch (geometryType) {
  27013. case "boxes":
  27014. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  27015. break;
  27016. case "spheres":
  27017. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  27018. break;
  27019. case "cylinders":
  27020. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  27021. break;
  27022. case "toruses":
  27023. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  27024. break;
  27025. case "grounds":
  27026. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  27027. break;
  27028. case "planes":
  27029. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  27030. break;
  27031. case "torusKnots":
  27032. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  27033. break;
  27034. case "vertexData":
  27035. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  27036. break;
  27037. }
  27038. found = true;
  27039. }
  27040. });
  27041. }
  27042. });
  27043. if (!found) {
  27044. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  27045. }
  27046. }
  27047. }
  27048. // Material ?
  27049. if (parsedMesh.materialId) {
  27050. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  27051. if (!materialFound && parsedData.multiMaterials) {
  27052. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  27053. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  27054. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  27055. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  27056. var subMatId = parsedMultiMaterial.materials[matIndex];
  27057. loadedMaterialsIds.push(subMatId);
  27058. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  27059. log += "\n\tMaterial " + mat.toString(fullDetails);
  27060. }
  27061. loadedMaterialsIds.push(parsedMultiMaterial.id);
  27062. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  27063. materialFound = true;
  27064. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  27065. break;
  27066. }
  27067. }
  27068. }
  27069. if (!materialFound) {
  27070. loadedMaterialsIds.push(parsedMesh.materialId);
  27071. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  27072. if (!mat) {
  27073. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  27074. }
  27075. else {
  27076. log += "\n\tMaterial " + mat.toString(fullDetails);
  27077. }
  27078. }
  27079. }
  27080. // Skeleton ?
  27081. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  27082. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  27083. if (!skeletonAlreadyLoaded) {
  27084. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  27085. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  27086. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  27087. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27088. skeletons.push(skeleton);
  27089. loadedSkeletonsIds.push(parsedSkeleton.id);
  27090. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  27091. }
  27092. }
  27093. }
  27094. }
  27095. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27096. meshes.push(mesh);
  27097. log += "\n\tMesh " + mesh.toString(fullDetails);
  27098. }
  27099. }
  27100. // Connecting parents
  27101. var currentMesh;
  27102. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27103. currentMesh = scene.meshes[index];
  27104. if (currentMesh._waitingParentId) {
  27105. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  27106. currentMesh._waitingParentId = undefined;
  27107. }
  27108. }
  27109. // freeze and compute world matrix application
  27110. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27111. currentMesh = scene.meshes[index];
  27112. if (currentMesh._waitingFreezeWorldMatrix) {
  27113. currentMesh.freezeWorldMatrix();
  27114. currentMesh._waitingFreezeWorldMatrix = undefined;
  27115. }
  27116. else {
  27117. currentMesh.computeWorldMatrix(true);
  27118. }
  27119. }
  27120. // Particles
  27121. if (parsedData.particleSystems) {
  27122. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27123. var parsedParticleSystem = parsedData.particleSystems[index];
  27124. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  27125. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  27126. }
  27127. }
  27128. }
  27129. return true;
  27130. }
  27131. catch (err) {
  27132. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  27133. log = null;
  27134. throw err;
  27135. }
  27136. finally {
  27137. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  27138. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  27139. }
  27140. }
  27141. },
  27142. load: function (scene, data, rootUrl) {
  27143. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  27144. // when SceneLoader.debugLogging = true (default), or exception encountered.
  27145. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  27146. // and avoid problems with multiple concurrent .babylon loads.
  27147. var log = "importScene has failed JSON parse";
  27148. try {
  27149. var parsedData = JSON.parse(data);
  27150. log = "";
  27151. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  27152. // Scene
  27153. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  27154. scene.autoClear = parsedData.autoClear;
  27155. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  27156. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  27157. if (parsedData.gravity) {
  27158. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  27159. }
  27160. // Fog
  27161. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  27162. scene.fogMode = parsedData.fogMode;
  27163. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  27164. scene.fogStart = parsedData.fogStart;
  27165. scene.fogEnd = parsedData.fogEnd;
  27166. scene.fogDensity = parsedData.fogDensity;
  27167. log += "\tFog mode for scene: ";
  27168. switch (scene.fogMode) {
  27169. // getters not compiling, so using hardcoded
  27170. case 1:
  27171. log += "exp\n";
  27172. break;
  27173. case 2:
  27174. log += "exp2\n";
  27175. break;
  27176. case 3:
  27177. log += "linear\n";
  27178. break;
  27179. }
  27180. }
  27181. //Physics
  27182. if (parsedData.physicsEnabled) {
  27183. var physicsPlugin;
  27184. if (parsedData.physicsEngine === "cannon") {
  27185. physicsPlugin = new BABYLON.CannonJSPlugin();
  27186. }
  27187. else if (parsedData.physicsEngine === "oimo") {
  27188. physicsPlugin = new BABYLON.OimoJSPlugin();
  27189. }
  27190. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  27191. //else - default engine, which is currently oimo
  27192. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  27193. scene.enablePhysics(physicsGravity, physicsPlugin);
  27194. }
  27195. // Metadata
  27196. if (parsedData.metadata !== undefined) {
  27197. scene.metadata = parsedData.metadata;
  27198. }
  27199. //collisions, if defined. otherwise, default is true
  27200. if (parsedData.collisionsEnabled != undefined) {
  27201. scene.collisionsEnabled = parsedData.collisionsEnabled;
  27202. }
  27203. scene.workerCollisions = !!parsedData.workerCollisions;
  27204. var index;
  27205. var cache;
  27206. // Lights
  27207. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  27208. var parsedLight = parsedData.lights[index];
  27209. var light = BABYLON.Light.Parse(parsedLight, scene);
  27210. log += (index === 0 ? "\n\tLights:" : "");
  27211. log += "\n\t\t" + light.toString(fullDetails);
  27212. }
  27213. // Animations
  27214. if (parsedData.animations) {
  27215. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  27216. var parsedAnimation = parsedData.animations[index];
  27217. var animation = BABYLON.Animation.Parse(parsedAnimation);
  27218. scene.animations.push(animation);
  27219. log += (index === 0 ? "\n\tAnimations:" : "");
  27220. log += "\n\t\t" + animation.toString(fullDetails);
  27221. }
  27222. }
  27223. if (parsedData.autoAnimate) {
  27224. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  27225. }
  27226. // Materials
  27227. if (parsedData.materials) {
  27228. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  27229. var parsedMaterial = parsedData.materials[index];
  27230. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  27231. log += (index === 0 ? "\n\tMaterials:" : "");
  27232. log += "\n\t\t" + mat.toString(fullDetails);
  27233. }
  27234. }
  27235. if (parsedData.multiMaterials) {
  27236. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  27237. var parsedMultiMaterial = parsedData.multiMaterials[index];
  27238. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  27239. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  27240. log += "\n\t\t" + mmat.toString(fullDetails);
  27241. }
  27242. }
  27243. // Skeletons
  27244. if (parsedData.skeletons) {
  27245. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  27246. var parsedSkeleton = parsedData.skeletons[index];
  27247. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27248. log += (index === 0 ? "\n\tSkeletons:" : "");
  27249. log += "\n\t\t" + skeleton.toString(fullDetails);
  27250. }
  27251. }
  27252. // Geometries
  27253. var geometries = parsedData.geometries;
  27254. if (geometries) {
  27255. // Boxes
  27256. var boxes = geometries.boxes;
  27257. if (boxes) {
  27258. for (index = 0, cache = boxes.length; index < cache; index++) {
  27259. var parsedBox = boxes[index];
  27260. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  27261. }
  27262. }
  27263. // Spheres
  27264. var spheres = geometries.spheres;
  27265. if (spheres) {
  27266. for (index = 0, cache = spheres.length; index < cache; index++) {
  27267. var parsedSphere = spheres[index];
  27268. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  27269. }
  27270. }
  27271. // Cylinders
  27272. var cylinders = geometries.cylinders;
  27273. if (cylinders) {
  27274. for (index = 0, cache = cylinders.length; index < cache; index++) {
  27275. var parsedCylinder = cylinders[index];
  27276. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  27277. }
  27278. }
  27279. // Toruses
  27280. var toruses = geometries.toruses;
  27281. if (toruses) {
  27282. for (index = 0, cache = toruses.length; index < cache; index++) {
  27283. var parsedTorus = toruses[index];
  27284. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  27285. }
  27286. }
  27287. // Grounds
  27288. var grounds = geometries.grounds;
  27289. if (grounds) {
  27290. for (index = 0, cache = grounds.length; index < cache; index++) {
  27291. var parsedGround = grounds[index];
  27292. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  27293. }
  27294. }
  27295. // Planes
  27296. var planes = geometries.planes;
  27297. if (planes) {
  27298. for (index = 0, cache = planes.length; index < cache; index++) {
  27299. var parsedPlane = planes[index];
  27300. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  27301. }
  27302. }
  27303. // TorusKnots
  27304. var torusKnots = geometries.torusKnots;
  27305. if (torusKnots) {
  27306. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  27307. var parsedTorusKnot = torusKnots[index];
  27308. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  27309. }
  27310. }
  27311. // VertexData
  27312. var vertexData = geometries.vertexData;
  27313. if (vertexData) {
  27314. for (index = 0, cache = vertexData.length; index < cache; index++) {
  27315. var parsedVertexData = vertexData[index];
  27316. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  27317. }
  27318. }
  27319. }
  27320. // Meshes
  27321. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  27322. var parsedMesh = parsedData.meshes[index];
  27323. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27324. log += (index === 0 ? "\n\tMeshes:" : "");
  27325. log += "\n\t\t" + mesh.toString(fullDetails);
  27326. }
  27327. // Cameras
  27328. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  27329. var parsedCamera = parsedData.cameras[index];
  27330. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  27331. log += (index === 0 ? "\n\tCameras:" : "");
  27332. log += "\n\t\t" + camera.toString(fullDetails);
  27333. }
  27334. if (parsedData.activeCameraID) {
  27335. scene.setActiveCameraByID(parsedData.activeCameraID);
  27336. }
  27337. // Browsing all the graph to connect the dots
  27338. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  27339. var camera = scene.cameras[index];
  27340. if (camera._waitingParentId) {
  27341. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  27342. camera._waitingParentId = undefined;
  27343. }
  27344. }
  27345. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  27346. var light = scene.lights[index];
  27347. if (light._waitingParentId) {
  27348. light.parent = scene.getLastEntryByID(light._waitingParentId);
  27349. light._waitingParentId = undefined;
  27350. }
  27351. }
  27352. // Sounds
  27353. var loadedSounds = [];
  27354. var loadedSound;
  27355. if (BABYLON.AudioEngine && parsedData.sounds) {
  27356. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  27357. var parsedSound = parsedData.sounds[index];
  27358. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27359. if (!parsedSound.url)
  27360. parsedSound.url = parsedSound.name;
  27361. if (!loadedSounds[parsedSound.url]) {
  27362. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  27363. loadedSounds[parsedSound.url] = loadedSound;
  27364. }
  27365. else {
  27366. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  27367. }
  27368. }
  27369. else {
  27370. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  27371. }
  27372. }
  27373. }
  27374. loadedSounds = [];
  27375. // Connect parents & children and parse actions
  27376. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27377. var mesh = scene.meshes[index];
  27378. if (mesh._waitingParentId) {
  27379. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  27380. mesh._waitingParentId = undefined;
  27381. }
  27382. if (mesh._waitingActions) {
  27383. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  27384. mesh._waitingActions = undefined;
  27385. }
  27386. }
  27387. // freeze world matrix application
  27388. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27389. var currentMesh = scene.meshes[index];
  27390. if (currentMesh._waitingFreezeWorldMatrix) {
  27391. currentMesh.freezeWorldMatrix();
  27392. currentMesh._waitingFreezeWorldMatrix = undefined;
  27393. }
  27394. else {
  27395. currentMesh.computeWorldMatrix(true);
  27396. }
  27397. }
  27398. // Particles Systems
  27399. if (parsedData.particleSystems) {
  27400. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27401. var parsedParticleSystem = parsedData.particleSystems[index];
  27402. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  27403. }
  27404. }
  27405. // Lens flares
  27406. if (parsedData.lensFlareSystems) {
  27407. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  27408. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  27409. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  27410. }
  27411. }
  27412. // Shadows
  27413. if (parsedData.shadowGenerators) {
  27414. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  27415. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  27416. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  27417. }
  27418. }
  27419. // Actions (scene)
  27420. if (parsedData.actions) {
  27421. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  27422. }
  27423. // Finish
  27424. return true;
  27425. }
  27426. catch (err) {
  27427. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  27428. log = null;
  27429. throw err;
  27430. }
  27431. finally {
  27432. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  27433. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  27434. }
  27435. }
  27436. }
  27437. });
  27438. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27439. })(BABYLON || (BABYLON = {}));
  27440. var BABYLON;
  27441. (function (BABYLON) {
  27442. var SpriteManager = (function () {
  27443. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  27444. if (epsilon === void 0) { epsilon = 0.01; }
  27445. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27446. this.name = name;
  27447. this.sprites = new Array();
  27448. this.renderingGroupId = 0;
  27449. this.layerMask = 0x0FFFFFFF;
  27450. this.fogEnabled = true;
  27451. this.isPickable = false;
  27452. /**
  27453. * An event triggered when the manager is disposed.
  27454. * @type {BABYLON.Observable}
  27455. */
  27456. this.onDisposeObservable = new BABYLON.Observable();
  27457. this._vertexBuffers = {};
  27458. this._capacity = capacity;
  27459. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  27460. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27461. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27462. if (cellSize.width && cellSize.height) {
  27463. this.cellWidth = cellSize.width;
  27464. this.cellHeight = cellSize.height;
  27465. }
  27466. else if (cellSize !== undefined) {
  27467. this.cellWidth = cellSize;
  27468. this.cellHeight = cellSize;
  27469. }
  27470. else {
  27471. return;
  27472. }
  27473. this._scene = scene;
  27474. this._scene.spriteManagers.push(this);
  27475. var indices = [];
  27476. var index = 0;
  27477. for (var count = 0; count < capacity; count++) {
  27478. indices.push(index);
  27479. indices.push(index + 1);
  27480. indices.push(index + 2);
  27481. indices.push(index);
  27482. indices.push(index + 2);
  27483. indices.push(index + 3);
  27484. index += 4;
  27485. }
  27486. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  27487. // VBO
  27488. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  27489. this._vertexData = new Float32Array(capacity * 16 * 4);
  27490. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  27491. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  27492. var options = this._buffer.createVertexBuffer("options", 4, 4);
  27493. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  27494. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  27495. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  27496. this._vertexBuffers["options"] = options;
  27497. this._vertexBuffers["cellInfo"] = cellInfo;
  27498. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  27499. // Effects
  27500. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  27501. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  27502. }
  27503. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  27504. set: function (callback) {
  27505. if (this._onDisposeObserver) {
  27506. this.onDisposeObservable.remove(this._onDisposeObserver);
  27507. }
  27508. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27509. },
  27510. enumerable: true,
  27511. configurable: true
  27512. });
  27513. Object.defineProperty(SpriteManager.prototype, "texture", {
  27514. get: function () {
  27515. return this._spriteTexture;
  27516. },
  27517. set: function (value) {
  27518. this._spriteTexture = value;
  27519. },
  27520. enumerable: true,
  27521. configurable: true
  27522. });
  27523. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  27524. var arrayOffset = index * 16;
  27525. if (offsetX === 0)
  27526. offsetX = this._epsilon;
  27527. else if (offsetX === 1)
  27528. offsetX = 1 - this._epsilon;
  27529. if (offsetY === 0)
  27530. offsetY = this._epsilon;
  27531. else if (offsetY === 1)
  27532. offsetY = 1 - this._epsilon;
  27533. this._vertexData[arrayOffset] = sprite.position.x;
  27534. this._vertexData[arrayOffset + 1] = sprite.position.y;
  27535. this._vertexData[arrayOffset + 2] = sprite.position.z;
  27536. this._vertexData[arrayOffset + 3] = sprite.angle;
  27537. this._vertexData[arrayOffset + 4] = sprite.width;
  27538. this._vertexData[arrayOffset + 5] = sprite.height;
  27539. this._vertexData[arrayOffset + 6] = offsetX;
  27540. this._vertexData[arrayOffset + 7] = offsetY;
  27541. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  27542. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  27543. var offset = (sprite.cellIndex / rowSize) >> 0;
  27544. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  27545. this._vertexData[arrayOffset + 11] = offset;
  27546. // Color
  27547. this._vertexData[arrayOffset + 12] = sprite.color.r;
  27548. this._vertexData[arrayOffset + 13] = sprite.color.g;
  27549. this._vertexData[arrayOffset + 14] = sprite.color.b;
  27550. this._vertexData[arrayOffset + 15] = sprite.color.a;
  27551. };
  27552. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  27553. var count = Math.min(this._capacity, this.sprites.length);
  27554. var min = BABYLON.Vector3.Zero();
  27555. var max = BABYLON.Vector3.Zero();
  27556. var distance = Number.MAX_VALUE;
  27557. var currentSprite;
  27558. var cameraSpacePosition = BABYLON.Vector3.Zero();
  27559. var cameraView = camera.getViewMatrix();
  27560. for (var index = 0; index < count; index++) {
  27561. var sprite = this.sprites[index];
  27562. if (!sprite) {
  27563. continue;
  27564. }
  27565. if (predicate) {
  27566. if (!predicate(sprite)) {
  27567. continue;
  27568. }
  27569. }
  27570. else if (!sprite.isPickable) {
  27571. continue;
  27572. }
  27573. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  27574. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  27575. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  27576. if (ray.intersectsBoxMinMax(min, max)) {
  27577. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  27578. if (distance > currentDistance) {
  27579. distance = currentDistance;
  27580. currentSprite = sprite;
  27581. if (fastCheck) {
  27582. break;
  27583. }
  27584. }
  27585. }
  27586. }
  27587. if (currentSprite) {
  27588. var result = new BABYLON.PickingInfo();
  27589. result.hit = true;
  27590. result.pickedSprite = currentSprite;
  27591. result.distance = distance;
  27592. return result;
  27593. }
  27594. return null;
  27595. };
  27596. SpriteManager.prototype.render = function () {
  27597. // Check
  27598. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  27599. return;
  27600. var engine = this._scene.getEngine();
  27601. var baseSize = this._spriteTexture.getBaseSize();
  27602. // Sprites
  27603. var deltaTime = engine.getDeltaTime();
  27604. var max = Math.min(this._capacity, this.sprites.length);
  27605. var rowSize = baseSize.width / this.cellWidth;
  27606. var offset = 0;
  27607. for (var index = 0; index < max; index++) {
  27608. var sprite = this.sprites[index];
  27609. if (!sprite) {
  27610. continue;
  27611. }
  27612. sprite._animate(deltaTime);
  27613. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  27614. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  27615. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  27616. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  27617. }
  27618. this._buffer.update(this._vertexData);
  27619. // Render
  27620. var effect = this._effectBase;
  27621. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27622. effect = this._effectFog;
  27623. }
  27624. engine.enableEffect(effect);
  27625. var viewMatrix = this._scene.getViewMatrix();
  27626. effect.setTexture("diffuseSampler", this._spriteTexture);
  27627. effect.setMatrix("view", viewMatrix);
  27628. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  27629. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  27630. // Fog
  27631. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27632. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  27633. effect.setColor3("vFogColor", this._scene.fogColor);
  27634. }
  27635. // VBOs
  27636. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27637. // Draw order
  27638. engine.setDepthFunctionToLessOrEqual();
  27639. effect.setBool("alphaTest", true);
  27640. engine.setColorWrite(false);
  27641. engine.draw(true, 0, max * 6);
  27642. engine.setColorWrite(true);
  27643. effect.setBool("alphaTest", false);
  27644. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27645. engine.draw(true, 0, max * 6);
  27646. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27647. };
  27648. SpriteManager.prototype.dispose = function () {
  27649. if (this._buffer) {
  27650. this._buffer.dispose();
  27651. this._buffer = null;
  27652. }
  27653. if (this._indexBuffer) {
  27654. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27655. this._indexBuffer = null;
  27656. }
  27657. if (this._spriteTexture) {
  27658. this._spriteTexture.dispose();
  27659. this._spriteTexture = null;
  27660. }
  27661. // Remove from scene
  27662. var index = this._scene.spriteManagers.indexOf(this);
  27663. this._scene.spriteManagers.splice(index, 1);
  27664. // Callback
  27665. this.onDisposeObservable.notifyObservers(this);
  27666. this.onDisposeObservable.clear();
  27667. };
  27668. return SpriteManager;
  27669. }());
  27670. BABYLON.SpriteManager = SpriteManager;
  27671. })(BABYLON || (BABYLON = {}));
  27672. var BABYLON;
  27673. (function (BABYLON) {
  27674. var Sprite = (function () {
  27675. function Sprite(name, manager) {
  27676. this.name = name;
  27677. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27678. this.width = 1.0;
  27679. this.height = 1.0;
  27680. this.angle = 0;
  27681. this.cellIndex = 0;
  27682. this.invertU = 0;
  27683. this.invertV = 0;
  27684. this.animations = new Array();
  27685. this.isPickable = false;
  27686. this._animationStarted = false;
  27687. this._loopAnimation = false;
  27688. this._fromIndex = 0;
  27689. this._toIndex = 0;
  27690. this._delay = 0;
  27691. this._direction = 1;
  27692. this._frameCount = 0;
  27693. this._time = 0;
  27694. this._manager = manager;
  27695. this._manager.sprites.push(this);
  27696. this.position = BABYLON.Vector3.Zero();
  27697. }
  27698. Object.defineProperty(Sprite.prototype, "size", {
  27699. get: function () {
  27700. return this.width;
  27701. },
  27702. set: function (value) {
  27703. this.width = value;
  27704. this.height = value;
  27705. },
  27706. enumerable: true,
  27707. configurable: true
  27708. });
  27709. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  27710. this._fromIndex = from;
  27711. this._toIndex = to;
  27712. this._loopAnimation = loop;
  27713. this._delay = delay;
  27714. this._animationStarted = true;
  27715. this._direction = from < to ? 1 : -1;
  27716. this.cellIndex = from;
  27717. this._time = 0;
  27718. this._onAnimationEnd = onAnimationEnd;
  27719. };
  27720. Sprite.prototype.stopAnimation = function () {
  27721. this._animationStarted = false;
  27722. };
  27723. Sprite.prototype._animate = function (deltaTime) {
  27724. if (!this._animationStarted)
  27725. return;
  27726. this._time += deltaTime;
  27727. if (this._time > this._delay) {
  27728. this._time = this._time % this._delay;
  27729. this.cellIndex += this._direction;
  27730. if (this.cellIndex === this._toIndex) {
  27731. if (this._loopAnimation) {
  27732. this.cellIndex = this._fromIndex;
  27733. }
  27734. else {
  27735. this._animationStarted = false;
  27736. if (this._onAnimationEnd) {
  27737. this._onAnimationEnd();
  27738. }
  27739. if (this.disposeWhenFinishedAnimating) {
  27740. this.dispose();
  27741. }
  27742. }
  27743. }
  27744. }
  27745. };
  27746. Sprite.prototype.dispose = function () {
  27747. for (var i = 0; i < this._manager.sprites.length; i++) {
  27748. if (this._manager.sprites[i] == this) {
  27749. this._manager.sprites.splice(i, 1);
  27750. }
  27751. }
  27752. };
  27753. return Sprite;
  27754. }());
  27755. BABYLON.Sprite = Sprite;
  27756. })(BABYLON || (BABYLON = {}));
  27757. var BABYLON;
  27758. (function (BABYLON) {
  27759. var Layer = (function () {
  27760. function Layer(name, imgUrl, scene, isBackground, color) {
  27761. this.name = name;
  27762. this.scale = new BABYLON.Vector2(1, 1);
  27763. this.offset = new BABYLON.Vector2(0, 0);
  27764. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  27765. this._vertexBuffers = {};
  27766. // Events
  27767. /**
  27768. * An event triggered when the layer is disposed.
  27769. * @type {BABYLON.Observable}
  27770. */
  27771. this.onDisposeObservable = new BABYLON.Observable();
  27772. /**
  27773. * An event triggered before rendering the scene
  27774. * @type {BABYLON.Observable}
  27775. */
  27776. this.onBeforeRenderObservable = new BABYLON.Observable();
  27777. /**
  27778. * An event triggered after rendering the scene
  27779. * @type {BABYLON.Observable}
  27780. */
  27781. this.onAfterRenderObservable = new BABYLON.Observable();
  27782. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  27783. this.isBackground = isBackground === undefined ? true : isBackground;
  27784. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  27785. this._scene = scene;
  27786. this._scene.layers.push(this);
  27787. var engine = scene.getEngine();
  27788. // VBO
  27789. var vertices = [];
  27790. vertices.push(1, 1);
  27791. vertices.push(-1, 1);
  27792. vertices.push(-1, -1);
  27793. vertices.push(1, -1);
  27794. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27795. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  27796. // Indices
  27797. var indices = [];
  27798. indices.push(0);
  27799. indices.push(1);
  27800. indices.push(2);
  27801. indices.push(0);
  27802. indices.push(2);
  27803. indices.push(3);
  27804. this._indexBuffer = engine.createIndexBuffer(indices);
  27805. // Effects
  27806. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  27807. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  27808. }
  27809. Object.defineProperty(Layer.prototype, "onDispose", {
  27810. set: function (callback) {
  27811. if (this._onDisposeObserver) {
  27812. this.onDisposeObservable.remove(this._onDisposeObserver);
  27813. }
  27814. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27815. },
  27816. enumerable: true,
  27817. configurable: true
  27818. });
  27819. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  27820. set: function (callback) {
  27821. if (this._onBeforeRenderObserver) {
  27822. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  27823. }
  27824. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  27825. },
  27826. enumerable: true,
  27827. configurable: true
  27828. });
  27829. Object.defineProperty(Layer.prototype, "onAfterRender", {
  27830. set: function (callback) {
  27831. if (this._onAfterRenderObserver) {
  27832. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  27833. }
  27834. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  27835. },
  27836. enumerable: true,
  27837. configurable: true
  27838. });
  27839. Layer.prototype.render = function () {
  27840. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  27841. // Check
  27842. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  27843. return;
  27844. var engine = this._scene.getEngine();
  27845. this.onBeforeRenderObservable.notifyObservers(this);
  27846. // Render
  27847. engine.enableEffect(currentEffect);
  27848. engine.setState(false);
  27849. // Texture
  27850. currentEffect.setTexture("textureSampler", this.texture);
  27851. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  27852. // Color
  27853. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  27854. // Scale / offset
  27855. currentEffect.setVector2("offset", this.offset);
  27856. currentEffect.setVector2("scale", this.scale);
  27857. // VBOs
  27858. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  27859. // Draw order
  27860. if (!this.alphaTest) {
  27861. engine.setAlphaMode(this.alphaBlendingMode);
  27862. engine.draw(true, 0, 6);
  27863. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27864. }
  27865. else {
  27866. engine.draw(true, 0, 6);
  27867. }
  27868. this.onAfterRenderObservable.notifyObservers(this);
  27869. };
  27870. Layer.prototype.dispose = function () {
  27871. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  27872. if (vertexBuffer) {
  27873. vertexBuffer.dispose();
  27874. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  27875. }
  27876. if (this._indexBuffer) {
  27877. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27878. this._indexBuffer = null;
  27879. }
  27880. if (this.texture) {
  27881. this.texture.dispose();
  27882. this.texture = null;
  27883. }
  27884. // Remove from scene
  27885. var index = this._scene.layers.indexOf(this);
  27886. this._scene.layers.splice(index, 1);
  27887. // Callback
  27888. this.onDisposeObservable.notifyObservers(this);
  27889. this.onDisposeObservable.clear();
  27890. this.onAfterRenderObservable.clear();
  27891. this.onBeforeRenderObservable.clear();
  27892. };
  27893. return Layer;
  27894. }());
  27895. BABYLON.Layer = Layer;
  27896. })(BABYLON || (BABYLON = {}));
  27897. var BABYLON;
  27898. (function (BABYLON) {
  27899. var Particle = (function () {
  27900. function Particle() {
  27901. this.position = BABYLON.Vector3.Zero();
  27902. this.direction = BABYLON.Vector3.Zero();
  27903. this.color = new BABYLON.Color4(0, 0, 0, 0);
  27904. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  27905. this.lifeTime = 1.0;
  27906. this.age = 0;
  27907. this.size = 0;
  27908. this.angle = 0;
  27909. this.angularSpeed = 0;
  27910. }
  27911. Particle.prototype.copyTo = function (other) {
  27912. other.position.copyFrom(this.position);
  27913. other.direction.copyFrom(this.direction);
  27914. other.color.copyFrom(this.color);
  27915. other.colorStep.copyFrom(this.colorStep);
  27916. other.lifeTime = this.lifeTime;
  27917. other.age = this.age;
  27918. other.size = this.size;
  27919. other.angle = this.angle;
  27920. other.angularSpeed = this.angularSpeed;
  27921. };
  27922. return Particle;
  27923. }());
  27924. BABYLON.Particle = Particle;
  27925. })(BABYLON || (BABYLON = {}));
  27926. var BABYLON;
  27927. (function (BABYLON) {
  27928. var randomNumber = function (min, max) {
  27929. if (min === max) {
  27930. return (min);
  27931. }
  27932. var random = Math.random();
  27933. return ((random * (max - min)) + min);
  27934. };
  27935. var ParticleSystem = (function () {
  27936. function ParticleSystem(name, capacity, scene, customEffect) {
  27937. var _this = this;
  27938. this.name = name;
  27939. // Members
  27940. this.animations = [];
  27941. this.renderingGroupId = 0;
  27942. this.emitter = null;
  27943. this.emitRate = 10;
  27944. this.manualEmitCount = -1;
  27945. this.updateSpeed = 0.01;
  27946. this.targetStopDuration = 0;
  27947. this.disposeOnStop = false;
  27948. this.minEmitPower = 1;
  27949. this.maxEmitPower = 1;
  27950. this.minLifeTime = 1;
  27951. this.maxLifeTime = 1;
  27952. this.minSize = 1;
  27953. this.maxSize = 1;
  27954. this.minAngularSpeed = 0;
  27955. this.maxAngularSpeed = 0;
  27956. this.layerMask = 0x0FFFFFFF;
  27957. /**
  27958. * An event triggered when the system is disposed.
  27959. * @type {BABYLON.Observable}
  27960. */
  27961. this.onDisposeObservable = new BABYLON.Observable();
  27962. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  27963. this.forceDepthWrite = false;
  27964. this.gravity = BABYLON.Vector3.Zero();
  27965. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  27966. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  27967. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  27968. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  27969. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27970. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27971. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  27972. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27973. this.particles = new Array();
  27974. this._stockParticles = new Array();
  27975. this._newPartsExcess = 0;
  27976. this._vertexBuffers = {};
  27977. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  27978. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  27979. this._scaledDirection = BABYLON.Vector3.Zero();
  27980. this._scaledGravity = BABYLON.Vector3.Zero();
  27981. this._currentRenderId = -1;
  27982. this._started = false;
  27983. this._stopped = false;
  27984. this._actualFrame = 0;
  27985. this.id = name;
  27986. this._capacity = capacity;
  27987. this._scene = scene;
  27988. this._customEffect = customEffect;
  27989. scene.particleSystems.push(this);
  27990. var indices = [];
  27991. var index = 0;
  27992. for (var count = 0; count < capacity; count++) {
  27993. indices.push(index);
  27994. indices.push(index + 1);
  27995. indices.push(index + 2);
  27996. indices.push(index);
  27997. indices.push(index + 2);
  27998. indices.push(index + 3);
  27999. index += 4;
  28000. }
  28001. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  28002. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  28003. this._vertexData = new Float32Array(capacity * 11 * 4);
  28004. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  28005. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  28006. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  28007. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  28008. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  28009. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  28010. this._vertexBuffers["options"] = options;
  28011. // Default behaviors
  28012. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  28013. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  28014. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  28015. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  28016. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  28017. };
  28018. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  28019. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  28020. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  28021. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  28022. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  28023. };
  28024. this.updateFunction = function (particles) {
  28025. for (var index = 0; index < particles.length; index++) {
  28026. var particle = particles[index];
  28027. particle.age += _this._scaledUpdateSpeed;
  28028. if (particle.age >= particle.lifeTime) {
  28029. _this.recycleParticle(particle);
  28030. index--;
  28031. continue;
  28032. }
  28033. else {
  28034. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  28035. particle.color.addInPlace(_this._scaledColorStep);
  28036. if (particle.color.a < 0)
  28037. particle.color.a = 0;
  28038. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  28039. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  28040. particle.position.addInPlace(_this._scaledDirection);
  28041. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  28042. particle.direction.addInPlace(_this._scaledGravity);
  28043. }
  28044. }
  28045. };
  28046. }
  28047. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  28048. set: function (callback) {
  28049. if (this._onDisposeObserver) {
  28050. this.onDisposeObservable.remove(this._onDisposeObserver);
  28051. }
  28052. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28053. },
  28054. enumerable: true,
  28055. configurable: true
  28056. });
  28057. ParticleSystem.prototype.recycleParticle = function (particle) {
  28058. var lastParticle = this.particles.pop();
  28059. if (lastParticle !== particle) {
  28060. lastParticle.copyTo(particle);
  28061. this._stockParticles.push(lastParticle);
  28062. }
  28063. };
  28064. ParticleSystem.prototype.getCapacity = function () {
  28065. return this._capacity;
  28066. };
  28067. ParticleSystem.prototype.isAlive = function () {
  28068. return this._alive;
  28069. };
  28070. ParticleSystem.prototype.isStarted = function () {
  28071. return this._started;
  28072. };
  28073. ParticleSystem.prototype.start = function () {
  28074. this._started = true;
  28075. this._stopped = false;
  28076. this._actualFrame = 0;
  28077. };
  28078. ParticleSystem.prototype.stop = function () {
  28079. this._stopped = true;
  28080. };
  28081. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  28082. var offset = index * 11;
  28083. this._vertexData[offset] = particle.position.x;
  28084. this._vertexData[offset + 1] = particle.position.y;
  28085. this._vertexData[offset + 2] = particle.position.z;
  28086. this._vertexData[offset + 3] = particle.color.r;
  28087. this._vertexData[offset + 4] = particle.color.g;
  28088. this._vertexData[offset + 5] = particle.color.b;
  28089. this._vertexData[offset + 6] = particle.color.a;
  28090. this._vertexData[offset + 7] = particle.angle;
  28091. this._vertexData[offset + 8] = particle.size;
  28092. this._vertexData[offset + 9] = offsetX;
  28093. this._vertexData[offset + 10] = offsetY;
  28094. };
  28095. ParticleSystem.prototype._update = function (newParticles) {
  28096. // Update current
  28097. this._alive = this.particles.length > 0;
  28098. this.updateFunction(this.particles);
  28099. // Add new ones
  28100. var worldMatrix;
  28101. if (this.emitter.position) {
  28102. worldMatrix = this.emitter.getWorldMatrix();
  28103. }
  28104. else {
  28105. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  28106. }
  28107. var particle;
  28108. for (var index = 0; index < newParticles; index++) {
  28109. if (this.particles.length === this._capacity) {
  28110. break;
  28111. }
  28112. if (this._stockParticles.length !== 0) {
  28113. particle = this._stockParticles.pop();
  28114. particle.age = 0;
  28115. }
  28116. else {
  28117. particle = new BABYLON.Particle();
  28118. }
  28119. this.particles.push(particle);
  28120. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  28121. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  28122. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  28123. particle.size = randomNumber(this.minSize, this.maxSize);
  28124. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  28125. this.startPositionFunction(worldMatrix, particle.position, particle);
  28126. var step = randomNumber(0, 1.0);
  28127. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  28128. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  28129. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  28130. }
  28131. };
  28132. ParticleSystem.prototype._getEffect = function () {
  28133. if (this._customEffect) {
  28134. return this._customEffect;
  28135. }
  28136. ;
  28137. var defines = [];
  28138. if (this._scene.clipPlane) {
  28139. defines.push("#define CLIPPLANE");
  28140. }
  28141. // Effect
  28142. var join = defines.join("\n");
  28143. if (this._cachedDefines !== join) {
  28144. this._cachedDefines = join;
  28145. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  28146. }
  28147. return this._effect;
  28148. };
  28149. ParticleSystem.prototype.animate = function () {
  28150. if (!this._started)
  28151. return;
  28152. var effect = this._getEffect();
  28153. // Check
  28154. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  28155. return;
  28156. if (this._currentRenderId === this._scene.getRenderId()) {
  28157. return;
  28158. }
  28159. this._currentRenderId = this._scene.getRenderId();
  28160. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  28161. // determine the number of particles we need to create
  28162. var newParticles;
  28163. if (this.manualEmitCount > -1) {
  28164. newParticles = this.manualEmitCount;
  28165. this._newPartsExcess = 0;
  28166. this.manualEmitCount = 0;
  28167. }
  28168. else {
  28169. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  28170. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  28171. }
  28172. if (this._newPartsExcess > 1.0) {
  28173. newParticles += this._newPartsExcess >> 0;
  28174. this._newPartsExcess -= this._newPartsExcess >> 0;
  28175. }
  28176. this._alive = false;
  28177. if (!this._stopped) {
  28178. this._actualFrame += this._scaledUpdateSpeed;
  28179. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  28180. this.stop();
  28181. }
  28182. else {
  28183. newParticles = 0;
  28184. }
  28185. this._update(newParticles);
  28186. // Stopped?
  28187. if (this._stopped) {
  28188. if (!this._alive) {
  28189. this._started = false;
  28190. if (this.disposeOnStop) {
  28191. this._scene._toBeDisposed.push(this);
  28192. }
  28193. }
  28194. }
  28195. // Update VBO
  28196. var offset = 0;
  28197. for (var index = 0; index < this.particles.length; index++) {
  28198. var particle = this.particles[index];
  28199. this._appendParticleVertex(offset++, particle, 0, 0);
  28200. this._appendParticleVertex(offset++, particle, 1, 0);
  28201. this._appendParticleVertex(offset++, particle, 1, 1);
  28202. this._appendParticleVertex(offset++, particle, 0, 1);
  28203. }
  28204. this._vertexBuffer.update(this._vertexData);
  28205. };
  28206. ParticleSystem.prototype.render = function () {
  28207. var effect = this._getEffect();
  28208. // Check
  28209. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  28210. return 0;
  28211. var engine = this._scene.getEngine();
  28212. // Render
  28213. engine.enableEffect(effect);
  28214. engine.setState(false);
  28215. var viewMatrix = this._scene.getViewMatrix();
  28216. effect.setTexture("diffuseSampler", this.particleTexture);
  28217. effect.setMatrix("view", viewMatrix);
  28218. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  28219. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  28220. if (this._scene.clipPlane) {
  28221. var clipPlane = this._scene.clipPlane;
  28222. var invView = viewMatrix.clone();
  28223. invView.invert();
  28224. effect.setMatrix("invView", invView);
  28225. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  28226. }
  28227. // VBOs
  28228. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28229. // Draw order
  28230. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  28231. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  28232. }
  28233. else {
  28234. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28235. }
  28236. if (this.forceDepthWrite) {
  28237. engine.setDepthWrite(true);
  28238. }
  28239. engine.draw(true, 0, this.particles.length * 6);
  28240. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28241. return this.particles.length;
  28242. };
  28243. ParticleSystem.prototype.dispose = function () {
  28244. if (this._vertexBuffer) {
  28245. this._vertexBuffer.dispose();
  28246. this._vertexBuffer = null;
  28247. }
  28248. if (this._indexBuffer) {
  28249. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28250. this._indexBuffer = null;
  28251. }
  28252. if (this.particleTexture) {
  28253. this.particleTexture.dispose();
  28254. this.particleTexture = null;
  28255. }
  28256. // Remove from scene
  28257. var index = this._scene.particleSystems.indexOf(this);
  28258. this._scene.particleSystems.splice(index, 1);
  28259. // Callback
  28260. this.onDisposeObservable.notifyObservers(this);
  28261. this.onDisposeObservable.clear();
  28262. };
  28263. // Clone
  28264. ParticleSystem.prototype.clone = function (name, newEmitter) {
  28265. var result = new ParticleSystem(name, this._capacity, this._scene);
  28266. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  28267. if (newEmitter === undefined) {
  28268. newEmitter = this.emitter;
  28269. }
  28270. result.emitter = newEmitter;
  28271. if (this.particleTexture) {
  28272. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  28273. }
  28274. result.start();
  28275. return result;
  28276. };
  28277. ParticleSystem.prototype.serialize = function () {
  28278. var serializationObject = {};
  28279. serializationObject.name = this.name;
  28280. serializationObject.id = this.id;
  28281. // Emitter
  28282. if (this.emitter.position) {
  28283. serializationObject.emitterId = this.emitter.id;
  28284. }
  28285. else {
  28286. serializationObject.emitter = this.emitter.asArray();
  28287. }
  28288. serializationObject.capacity = this.getCapacity();
  28289. if (this.particleTexture) {
  28290. serializationObject.textureName = this.particleTexture.name;
  28291. }
  28292. // Animations
  28293. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28294. // Particle system
  28295. serializationObject.minAngularSpeed = this.minAngularSpeed;
  28296. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  28297. serializationObject.minSize = this.minSize;
  28298. serializationObject.maxSize = this.maxSize;
  28299. serializationObject.minEmitPower = this.minEmitPower;
  28300. serializationObject.maxEmitPower = this.maxEmitPower;
  28301. serializationObject.minLifeTime = this.minLifeTime;
  28302. serializationObject.maxLifeTime = this.maxLifeTime;
  28303. serializationObject.emitRate = this.emitRate;
  28304. serializationObject.minEmitBox = this.minEmitBox.asArray();
  28305. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  28306. serializationObject.gravity = this.gravity.asArray();
  28307. serializationObject.direction1 = this.direction1.asArray();
  28308. serializationObject.direction2 = this.direction2.asArray();
  28309. serializationObject.color1 = this.color1.asArray();
  28310. serializationObject.color2 = this.color2.asArray();
  28311. serializationObject.colorDead = this.colorDead.asArray();
  28312. serializationObject.updateSpeed = this.updateSpeed;
  28313. serializationObject.targetStopDuration = this.targetStopDuration;
  28314. serializationObject.textureMask = this.textureMask.asArray();
  28315. serializationObject.blendMode = this.blendMode;
  28316. return serializationObject;
  28317. };
  28318. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  28319. var name = parsedParticleSystem.name;
  28320. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  28321. if (parsedParticleSystem.id) {
  28322. particleSystem.id = parsedParticleSystem.id;
  28323. }
  28324. // Texture
  28325. if (parsedParticleSystem.textureName) {
  28326. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  28327. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  28328. }
  28329. // Emitter
  28330. if (parsedParticleSystem.emitterId) {
  28331. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  28332. }
  28333. else {
  28334. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  28335. }
  28336. // Animations
  28337. if (parsedParticleSystem.animations) {
  28338. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  28339. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  28340. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28341. }
  28342. }
  28343. if (parsedParticleSystem.autoAnimate) {
  28344. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  28345. }
  28346. // Particle system
  28347. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  28348. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  28349. particleSystem.minSize = parsedParticleSystem.minSize;
  28350. particleSystem.maxSize = parsedParticleSystem.maxSize;
  28351. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  28352. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  28353. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  28354. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  28355. particleSystem.emitRate = parsedParticleSystem.emitRate;
  28356. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  28357. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  28358. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  28359. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  28360. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  28361. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  28362. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  28363. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  28364. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  28365. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  28366. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  28367. particleSystem.blendMode = parsedParticleSystem.blendMode;
  28368. if (!parsedParticleSystem.preventAutoStart) {
  28369. particleSystem.start();
  28370. }
  28371. return particleSystem;
  28372. };
  28373. // Statics
  28374. ParticleSystem.BLENDMODE_ONEONE = 0;
  28375. ParticleSystem.BLENDMODE_STANDARD = 1;
  28376. return ParticleSystem;
  28377. }());
  28378. BABYLON.ParticleSystem = ParticleSystem;
  28379. })(BABYLON || (BABYLON = {}));
  28380. var BABYLON;
  28381. (function (BABYLON) {
  28382. var AnimationRange = (function () {
  28383. function AnimationRange(name, from, to) {
  28384. this.name = name;
  28385. this.from = from;
  28386. this.to = to;
  28387. }
  28388. AnimationRange.prototype.clone = function () {
  28389. return new AnimationRange(this.name, this.from, this.to);
  28390. };
  28391. return AnimationRange;
  28392. }());
  28393. BABYLON.AnimationRange = AnimationRange;
  28394. /**
  28395. * Composed of a frame, and an action function
  28396. */
  28397. var AnimationEvent = (function () {
  28398. function AnimationEvent(frame, action, onlyOnce) {
  28399. this.frame = frame;
  28400. this.action = action;
  28401. this.onlyOnce = onlyOnce;
  28402. this.isDone = false;
  28403. }
  28404. return AnimationEvent;
  28405. }());
  28406. BABYLON.AnimationEvent = AnimationEvent;
  28407. var PathCursor = (function () {
  28408. function PathCursor(path) {
  28409. this.path = path;
  28410. this._onchange = new Array();
  28411. this.value = 0;
  28412. this.animations = new Array();
  28413. }
  28414. PathCursor.prototype.getPoint = function () {
  28415. var point = this.path.getPointAtLengthPosition(this.value);
  28416. return new BABYLON.Vector3(point.x, 0, point.y);
  28417. };
  28418. PathCursor.prototype.moveAhead = function (step) {
  28419. if (step === void 0) { step = 0.002; }
  28420. this.move(step);
  28421. return this;
  28422. };
  28423. PathCursor.prototype.moveBack = function (step) {
  28424. if (step === void 0) { step = 0.002; }
  28425. this.move(-step);
  28426. return this;
  28427. };
  28428. PathCursor.prototype.move = function (step) {
  28429. if (Math.abs(step) > 1) {
  28430. throw "step size should be less than 1.";
  28431. }
  28432. this.value += step;
  28433. this.ensureLimits();
  28434. this.raiseOnChange();
  28435. return this;
  28436. };
  28437. PathCursor.prototype.ensureLimits = function () {
  28438. while (this.value > 1) {
  28439. this.value -= 1;
  28440. }
  28441. while (this.value < 0) {
  28442. this.value += 1;
  28443. }
  28444. return this;
  28445. };
  28446. // used by animation engine
  28447. PathCursor.prototype.markAsDirty = function (propertyName) {
  28448. this.ensureLimits();
  28449. this.raiseOnChange();
  28450. return this;
  28451. };
  28452. PathCursor.prototype.raiseOnChange = function () {
  28453. var _this = this;
  28454. this._onchange.forEach(function (f) { return f(_this); });
  28455. return this;
  28456. };
  28457. PathCursor.prototype.onchange = function (f) {
  28458. this._onchange.push(f);
  28459. return this;
  28460. };
  28461. return PathCursor;
  28462. }());
  28463. BABYLON.PathCursor = PathCursor;
  28464. var Animation = (function () {
  28465. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  28466. this.name = name;
  28467. this.targetProperty = targetProperty;
  28468. this.framePerSecond = framePerSecond;
  28469. this.dataType = dataType;
  28470. this.loopMode = loopMode;
  28471. this.enableBlending = enableBlending;
  28472. this._offsetsCache = {};
  28473. this._highLimitsCache = {};
  28474. this._stopped = false;
  28475. this._blendingFactor = 0;
  28476. // The set of event that will be linked to this animation
  28477. this._events = new Array();
  28478. this.allowMatricesInterpolation = false;
  28479. this.blendingSpeed = 0.01;
  28480. this._ranges = {};
  28481. this.targetPropertyPath = targetProperty.split(".");
  28482. this.dataType = dataType;
  28483. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  28484. }
  28485. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  28486. var dataType = undefined;
  28487. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  28488. dataType = Animation.ANIMATIONTYPE_FLOAT;
  28489. }
  28490. else if (from instanceof BABYLON.Quaternion) {
  28491. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  28492. }
  28493. else if (from instanceof BABYLON.Vector3) {
  28494. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  28495. }
  28496. else if (from instanceof BABYLON.Vector2) {
  28497. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  28498. }
  28499. else if (from instanceof BABYLON.Color3) {
  28500. dataType = Animation.ANIMATIONTYPE_COLOR3;
  28501. }
  28502. else if (from instanceof BABYLON.Size) {
  28503. dataType = Animation.ANIMATIONTYPE_SIZE;
  28504. }
  28505. if (dataType == undefined) {
  28506. return null;
  28507. }
  28508. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  28509. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  28510. animation.setKeys(keys);
  28511. if (easingFunction !== undefined) {
  28512. animation.setEasingFunction(easingFunction);
  28513. }
  28514. return animation;
  28515. };
  28516. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28517. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28518. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28519. };
  28520. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28521. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28522. node.animations.push(animation);
  28523. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28524. };
  28525. // Methods
  28526. /**
  28527. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28528. */
  28529. Animation.prototype.toString = function (fullDetails) {
  28530. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  28531. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  28532. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  28533. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28534. if (fullDetails) {
  28535. ret += ", Ranges: {";
  28536. var first = true;
  28537. for (var name in this._ranges) {
  28538. if (first) {
  28539. ret += ", ";
  28540. first = false;
  28541. }
  28542. ret += name;
  28543. }
  28544. ret += "}";
  28545. }
  28546. return ret;
  28547. };
  28548. /**
  28549. * Add an event to this animation.
  28550. */
  28551. Animation.prototype.addEvent = function (event) {
  28552. this._events.push(event);
  28553. };
  28554. /**
  28555. * Remove all events found at the given frame
  28556. * @param frame
  28557. */
  28558. Animation.prototype.removeEvents = function (frame) {
  28559. for (var index = 0; index < this._events.length; index++) {
  28560. if (this._events[index].frame === frame) {
  28561. this._events.splice(index, 1);
  28562. index--;
  28563. }
  28564. }
  28565. };
  28566. Animation.prototype.createRange = function (name, from, to) {
  28567. // check name not already in use; could happen for bones after serialized
  28568. if (!this._ranges[name]) {
  28569. this._ranges[name] = new AnimationRange(name, from, to);
  28570. }
  28571. };
  28572. Animation.prototype.deleteRange = function (name, deleteFrames) {
  28573. if (deleteFrames === void 0) { deleteFrames = true; }
  28574. if (this._ranges[name]) {
  28575. if (deleteFrames) {
  28576. var from = this._ranges[name].from;
  28577. var to = this._ranges[name].to;
  28578. // this loop MUST go high to low for multiple splices to work
  28579. for (var key = this._keys.length - 1; key >= 0; key--) {
  28580. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  28581. this._keys.splice(key, 1);
  28582. }
  28583. }
  28584. }
  28585. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28586. }
  28587. };
  28588. Animation.prototype.getRange = function (name) {
  28589. return this._ranges[name];
  28590. };
  28591. Animation.prototype.reset = function () {
  28592. this._offsetsCache = {};
  28593. this._highLimitsCache = {};
  28594. this.currentFrame = 0;
  28595. this._blendingFactor = 0;
  28596. this._originalBlendValue = null;
  28597. };
  28598. Animation.prototype.isStopped = function () {
  28599. return this._stopped;
  28600. };
  28601. Animation.prototype.getKeys = function () {
  28602. return this._keys;
  28603. };
  28604. Animation.prototype.getHighestFrame = function () {
  28605. var ret = 0;
  28606. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  28607. if (ret < this._keys[key].frame) {
  28608. ret = this._keys[key].frame;
  28609. }
  28610. }
  28611. return ret;
  28612. };
  28613. Animation.prototype.getEasingFunction = function () {
  28614. return this._easingFunction;
  28615. };
  28616. Animation.prototype.setEasingFunction = function (easingFunction) {
  28617. this._easingFunction = easingFunction;
  28618. };
  28619. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  28620. return startValue + (endValue - startValue) * gradient;
  28621. };
  28622. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  28623. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  28624. };
  28625. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  28626. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  28627. };
  28628. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  28629. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  28630. };
  28631. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  28632. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  28633. };
  28634. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  28635. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  28636. };
  28637. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  28638. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  28639. };
  28640. Animation.prototype.clone = function () {
  28641. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  28642. if (this._keys) {
  28643. clone.setKeys(this._keys);
  28644. }
  28645. if (this._ranges) {
  28646. clone._ranges = {};
  28647. for (var name in this._ranges) {
  28648. clone._ranges[name] = this._ranges[name].clone();
  28649. }
  28650. }
  28651. return clone;
  28652. };
  28653. Animation.prototype.setKeys = function (values) {
  28654. this._keys = values.slice(0);
  28655. this._offsetsCache = {};
  28656. this._highLimitsCache = {};
  28657. };
  28658. Animation.prototype._getKeyValue = function (value) {
  28659. if (typeof value === "function") {
  28660. return value();
  28661. }
  28662. return value;
  28663. };
  28664. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  28665. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  28666. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  28667. }
  28668. this.currentFrame = currentFrame;
  28669. // Try to get a hash to find the right key
  28670. 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));
  28671. if (this._keys[startKey].frame >= currentFrame) {
  28672. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  28673. startKey--;
  28674. }
  28675. }
  28676. for (var key = startKey; key < this._keys.length; key++) {
  28677. if (this._keys[key + 1].frame >= currentFrame) {
  28678. var startValue = this._getKeyValue(this._keys[key].value);
  28679. var endValue = this._getKeyValue(this._keys[key + 1].value);
  28680. // gradient : percent of currentFrame between the frame inf and the frame sup
  28681. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  28682. // check for easingFunction and correction of gradient
  28683. if (this._easingFunction != null) {
  28684. gradient = this._easingFunction.ease(gradient);
  28685. }
  28686. switch (this.dataType) {
  28687. // Float
  28688. case Animation.ANIMATIONTYPE_FLOAT:
  28689. switch (loopMode) {
  28690. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28691. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28692. return this.floatInterpolateFunction(startValue, endValue, gradient);
  28693. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28694. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  28695. }
  28696. break;
  28697. // Quaternion
  28698. case Animation.ANIMATIONTYPE_QUATERNION:
  28699. var quaternion = null;
  28700. switch (loopMode) {
  28701. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28702. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28703. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  28704. break;
  28705. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28706. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28707. break;
  28708. }
  28709. return quaternion;
  28710. // Vector3
  28711. case Animation.ANIMATIONTYPE_VECTOR3:
  28712. switch (loopMode) {
  28713. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28714. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28715. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  28716. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28717. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28718. }
  28719. // Vector2
  28720. case Animation.ANIMATIONTYPE_VECTOR2:
  28721. switch (loopMode) {
  28722. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28723. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28724. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  28725. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28726. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28727. }
  28728. // Size
  28729. case Animation.ANIMATIONTYPE_SIZE:
  28730. switch (loopMode) {
  28731. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28732. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28733. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  28734. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28735. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28736. }
  28737. // Color3
  28738. case Animation.ANIMATIONTYPE_COLOR3:
  28739. switch (loopMode) {
  28740. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28741. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28742. return this.color3InterpolateFunction(startValue, endValue, gradient);
  28743. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28744. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28745. }
  28746. // Matrix
  28747. case Animation.ANIMATIONTYPE_MATRIX:
  28748. switch (loopMode) {
  28749. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28750. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28751. if (this.allowMatricesInterpolation) {
  28752. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  28753. }
  28754. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28755. return startValue;
  28756. }
  28757. default:
  28758. break;
  28759. }
  28760. break;
  28761. }
  28762. }
  28763. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  28764. };
  28765. Animation.prototype.setValue = function (currentValue, blend) {
  28766. if (blend === void 0) { blend = false; }
  28767. // Set value
  28768. var path;
  28769. var destination;
  28770. if (this.targetPropertyPath.length > 1) {
  28771. var property = this._target[this.targetPropertyPath[0]];
  28772. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  28773. property = property[this.targetPropertyPath[index]];
  28774. }
  28775. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  28776. destination = property;
  28777. }
  28778. else {
  28779. path = this.targetPropertyPath[0];
  28780. destination = this._target;
  28781. }
  28782. // Blending
  28783. if (this.enableBlending && this._blendingFactor <= 1.0) {
  28784. if (!this._originalBlendValue) {
  28785. if (destination[path].clone) {
  28786. this._originalBlendValue = destination[path].clone();
  28787. }
  28788. else {
  28789. this._originalBlendValue = destination[path];
  28790. }
  28791. }
  28792. if (this._originalBlendValue.prototype) {
  28793. if (this._originalBlendValue.prototype.Lerp) {
  28794. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  28795. }
  28796. else {
  28797. destination[path] = currentValue;
  28798. }
  28799. }
  28800. else if (this._originalBlendValue.m) {
  28801. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  28802. }
  28803. else {
  28804. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  28805. }
  28806. this._blendingFactor += this.blendingSpeed;
  28807. }
  28808. else {
  28809. destination[path] = currentValue;
  28810. }
  28811. if (this._target.markAsDirty) {
  28812. this._target.markAsDirty(this.targetProperty);
  28813. }
  28814. };
  28815. Animation.prototype.goToFrame = function (frame) {
  28816. if (frame < this._keys[0].frame) {
  28817. frame = this._keys[0].frame;
  28818. }
  28819. else if (frame > this._keys[this._keys.length - 1].frame) {
  28820. frame = this._keys[this._keys.length - 1].frame;
  28821. }
  28822. var currentValue = this._interpolate(frame, 0, this.loopMode);
  28823. this.setValue(currentValue);
  28824. };
  28825. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  28826. if (blend === void 0) { blend = false; }
  28827. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  28828. this._stopped = true;
  28829. return false;
  28830. }
  28831. var returnValue = true;
  28832. // Adding a start key at frame 0 if missing
  28833. if (this._keys[0].frame !== 0) {
  28834. var newKey = { frame: 0, value: this._keys[0].value };
  28835. this._keys.splice(0, 0, newKey);
  28836. }
  28837. // Check limits
  28838. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  28839. from = this._keys[0].frame;
  28840. }
  28841. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  28842. to = this._keys[this._keys.length - 1].frame;
  28843. }
  28844. // Compute ratio
  28845. var range = to - from;
  28846. var offsetValue;
  28847. // ratio represents the frame delta between from and to
  28848. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  28849. var highLimitValue = 0;
  28850. if (ratio > range && !loop) {
  28851. returnValue = false;
  28852. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  28853. }
  28854. else {
  28855. // Get max value if required
  28856. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  28857. var keyOffset = to.toString() + from.toString();
  28858. if (!this._offsetsCache[keyOffset]) {
  28859. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28860. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28861. switch (this.dataType) {
  28862. // Float
  28863. case Animation.ANIMATIONTYPE_FLOAT:
  28864. this._offsetsCache[keyOffset] = toValue - fromValue;
  28865. break;
  28866. // Quaternion
  28867. case Animation.ANIMATIONTYPE_QUATERNION:
  28868. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28869. break;
  28870. // Vector3
  28871. case Animation.ANIMATIONTYPE_VECTOR3:
  28872. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28873. // Vector2
  28874. case Animation.ANIMATIONTYPE_VECTOR2:
  28875. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28876. // Size
  28877. case Animation.ANIMATIONTYPE_SIZE:
  28878. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28879. // Color3
  28880. case Animation.ANIMATIONTYPE_COLOR3:
  28881. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28882. default:
  28883. break;
  28884. }
  28885. this._highLimitsCache[keyOffset] = toValue;
  28886. }
  28887. highLimitValue = this._highLimitsCache[keyOffset];
  28888. offsetValue = this._offsetsCache[keyOffset];
  28889. }
  28890. }
  28891. if (offsetValue === undefined) {
  28892. switch (this.dataType) {
  28893. // Float
  28894. case Animation.ANIMATIONTYPE_FLOAT:
  28895. offsetValue = 0;
  28896. break;
  28897. // Quaternion
  28898. case Animation.ANIMATIONTYPE_QUATERNION:
  28899. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  28900. break;
  28901. // Vector3
  28902. case Animation.ANIMATIONTYPE_VECTOR3:
  28903. offsetValue = BABYLON.Vector3.Zero();
  28904. break;
  28905. // Vector2
  28906. case Animation.ANIMATIONTYPE_VECTOR2:
  28907. offsetValue = BABYLON.Vector2.Zero();
  28908. break;
  28909. // Size
  28910. case Animation.ANIMATIONTYPE_SIZE:
  28911. offsetValue = BABYLON.Size.Zero();
  28912. break;
  28913. // Color3
  28914. case Animation.ANIMATIONTYPE_COLOR3:
  28915. offsetValue = BABYLON.Color3.Black();
  28916. }
  28917. }
  28918. // Compute value
  28919. var repeatCount = (ratio / range) >> 0;
  28920. var currentFrame = returnValue ? from + ratio % range : to;
  28921. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  28922. // Set value
  28923. this.setValue(currentValue);
  28924. // Check events
  28925. for (var index = 0; index < this._events.length; index++) {
  28926. if (currentFrame >= this._events[index].frame) {
  28927. var event = this._events[index];
  28928. if (!event.isDone) {
  28929. // If event should be done only once, remove it.
  28930. if (event.onlyOnce) {
  28931. this._events.splice(index, 1);
  28932. index--;
  28933. }
  28934. event.isDone = true;
  28935. event.action();
  28936. } // Don't do anything if the event has already be done.
  28937. }
  28938. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  28939. // reset event, the animation is looping
  28940. this._events[index].isDone = false;
  28941. }
  28942. }
  28943. if (!returnValue) {
  28944. this._stopped = true;
  28945. }
  28946. return returnValue;
  28947. };
  28948. Animation.prototype.serialize = function () {
  28949. var serializationObject = {};
  28950. serializationObject.name = this.name;
  28951. serializationObject.property = this.targetProperty;
  28952. serializationObject.framePerSecond = this.framePerSecond;
  28953. serializationObject.dataType = this.dataType;
  28954. serializationObject.loopBehavior = this.loopMode;
  28955. var dataType = this.dataType;
  28956. serializationObject.keys = [];
  28957. var keys = this.getKeys();
  28958. for (var index = 0; index < keys.length; index++) {
  28959. var animationKey = keys[index];
  28960. var key = {};
  28961. key.frame = animationKey.frame;
  28962. switch (dataType) {
  28963. case Animation.ANIMATIONTYPE_FLOAT:
  28964. key.values = [animationKey.value];
  28965. break;
  28966. case Animation.ANIMATIONTYPE_QUATERNION:
  28967. case Animation.ANIMATIONTYPE_MATRIX:
  28968. case Animation.ANIMATIONTYPE_VECTOR3:
  28969. case Animation.ANIMATIONTYPE_COLOR3:
  28970. key.values = animationKey.value.asArray();
  28971. break;
  28972. }
  28973. serializationObject.keys.push(key);
  28974. }
  28975. serializationObject.ranges = [];
  28976. for (var name in this._ranges) {
  28977. var range = {};
  28978. range.name = name;
  28979. range.from = this._ranges[name].from;
  28980. range.to = this._ranges[name].to;
  28981. serializationObject.ranges.push(range);
  28982. }
  28983. return serializationObject;
  28984. };
  28985. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  28986. get: function () {
  28987. return Animation._ANIMATIONTYPE_FLOAT;
  28988. },
  28989. enumerable: true,
  28990. configurable: true
  28991. });
  28992. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  28993. get: function () {
  28994. return Animation._ANIMATIONTYPE_VECTOR3;
  28995. },
  28996. enumerable: true,
  28997. configurable: true
  28998. });
  28999. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  29000. get: function () {
  29001. return Animation._ANIMATIONTYPE_VECTOR2;
  29002. },
  29003. enumerable: true,
  29004. configurable: true
  29005. });
  29006. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  29007. get: function () {
  29008. return Animation._ANIMATIONTYPE_SIZE;
  29009. },
  29010. enumerable: true,
  29011. configurable: true
  29012. });
  29013. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  29014. get: function () {
  29015. return Animation._ANIMATIONTYPE_QUATERNION;
  29016. },
  29017. enumerable: true,
  29018. configurable: true
  29019. });
  29020. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  29021. get: function () {
  29022. return Animation._ANIMATIONTYPE_MATRIX;
  29023. },
  29024. enumerable: true,
  29025. configurable: true
  29026. });
  29027. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  29028. get: function () {
  29029. return Animation._ANIMATIONTYPE_COLOR3;
  29030. },
  29031. enumerable: true,
  29032. configurable: true
  29033. });
  29034. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  29035. get: function () {
  29036. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  29037. },
  29038. enumerable: true,
  29039. configurable: true
  29040. });
  29041. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  29042. get: function () {
  29043. return Animation._ANIMATIONLOOPMODE_CYCLE;
  29044. },
  29045. enumerable: true,
  29046. configurable: true
  29047. });
  29048. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  29049. get: function () {
  29050. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  29051. },
  29052. enumerable: true,
  29053. configurable: true
  29054. });
  29055. Animation.Parse = function (parsedAnimation) {
  29056. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  29057. var dataType = parsedAnimation.dataType;
  29058. var keys = [];
  29059. var data;
  29060. var index;
  29061. for (index = 0; index < parsedAnimation.keys.length; index++) {
  29062. var key = parsedAnimation.keys[index];
  29063. switch (dataType) {
  29064. case Animation.ANIMATIONTYPE_FLOAT:
  29065. data = key.values[0];
  29066. break;
  29067. case Animation.ANIMATIONTYPE_QUATERNION:
  29068. data = BABYLON.Quaternion.FromArray(key.values);
  29069. break;
  29070. case Animation.ANIMATIONTYPE_MATRIX:
  29071. data = BABYLON.Matrix.FromArray(key.values);
  29072. break;
  29073. case Animation.ANIMATIONTYPE_COLOR3:
  29074. data = BABYLON.Color3.FromArray(key.values);
  29075. break;
  29076. case Animation.ANIMATIONTYPE_VECTOR3:
  29077. default:
  29078. data = BABYLON.Vector3.FromArray(key.values);
  29079. break;
  29080. }
  29081. keys.push({
  29082. frame: key.frame,
  29083. value: data
  29084. });
  29085. }
  29086. animation.setKeys(keys);
  29087. if (parsedAnimation.ranges) {
  29088. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  29089. data = parsedAnimation.ranges[index];
  29090. animation.createRange(data.name, data.from, data.to);
  29091. }
  29092. }
  29093. return animation;
  29094. };
  29095. Animation.AppendSerializedAnimations = function (source, destination) {
  29096. if (source.animations) {
  29097. destination.animations = [];
  29098. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29099. var animation = source.animations[animationIndex];
  29100. destination.animations.push(animation.serialize());
  29101. }
  29102. }
  29103. };
  29104. // Statics
  29105. Animation._ANIMATIONTYPE_FLOAT = 0;
  29106. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  29107. Animation._ANIMATIONTYPE_QUATERNION = 2;
  29108. Animation._ANIMATIONTYPE_MATRIX = 3;
  29109. Animation._ANIMATIONTYPE_COLOR3 = 4;
  29110. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  29111. Animation._ANIMATIONTYPE_SIZE = 6;
  29112. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  29113. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  29114. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  29115. return Animation;
  29116. }());
  29117. BABYLON.Animation = Animation;
  29118. })(BABYLON || (BABYLON = {}));
  29119. var BABYLON;
  29120. (function (BABYLON) {
  29121. var Animatable = (function () {
  29122. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  29123. if (fromFrame === void 0) { fromFrame = 0; }
  29124. if (toFrame === void 0) { toFrame = 100; }
  29125. if (loopAnimation === void 0) { loopAnimation = false; }
  29126. if (speedRatio === void 0) { speedRatio = 1.0; }
  29127. this.target = target;
  29128. this.fromFrame = fromFrame;
  29129. this.toFrame = toFrame;
  29130. this.loopAnimation = loopAnimation;
  29131. this.speedRatio = speedRatio;
  29132. this.onAnimationEnd = onAnimationEnd;
  29133. this._animations = new Array();
  29134. this._paused = false;
  29135. this.animationStarted = false;
  29136. if (animations) {
  29137. this.appendAnimations(target, animations);
  29138. }
  29139. this._scene = scene;
  29140. scene._activeAnimatables.push(this);
  29141. }
  29142. // Methods
  29143. Animatable.prototype.getAnimations = function () {
  29144. return this._animations;
  29145. };
  29146. Animatable.prototype.appendAnimations = function (target, animations) {
  29147. for (var index = 0; index < animations.length; index++) {
  29148. var animation = animations[index];
  29149. animation._target = target;
  29150. this._animations.push(animation);
  29151. }
  29152. };
  29153. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  29154. var animations = this._animations;
  29155. for (var index = 0; index < animations.length; index++) {
  29156. if (animations[index].targetProperty === property) {
  29157. return animations[index];
  29158. }
  29159. }
  29160. return null;
  29161. };
  29162. Animatable.prototype.reset = function () {
  29163. var animations = this._animations;
  29164. for (var index = 0; index < animations.length; index++) {
  29165. animations[index].reset();
  29166. }
  29167. this._localDelayOffset = null;
  29168. this._pausedDelay = null;
  29169. };
  29170. Animatable.prototype.enableBlending = function (blendingSpeed) {
  29171. var animations = this._animations;
  29172. for (var index = 0; index < animations.length; index++) {
  29173. animations[index].enableBlending = true;
  29174. animations[index].blendingSpeed = blendingSpeed;
  29175. }
  29176. };
  29177. Animatable.prototype.disableBlending = function () {
  29178. var animations = this._animations;
  29179. for (var index = 0; index < animations.length; index++) {
  29180. animations[index].enableBlending = false;
  29181. }
  29182. };
  29183. Animatable.prototype.goToFrame = function (frame) {
  29184. var animations = this._animations;
  29185. if (animations[0]) {
  29186. var fps = animations[0].framePerSecond;
  29187. var currentFrame = animations[0].currentFrame;
  29188. var adjustTime = frame - currentFrame;
  29189. var delay = adjustTime * 1000 / fps;
  29190. this._localDelayOffset -= delay;
  29191. }
  29192. for (var index = 0; index < animations.length; index++) {
  29193. animations[index].goToFrame(frame);
  29194. }
  29195. };
  29196. Animatable.prototype.pause = function () {
  29197. if (this._paused) {
  29198. return;
  29199. }
  29200. this._paused = true;
  29201. };
  29202. Animatable.prototype.restart = function () {
  29203. this._paused = false;
  29204. };
  29205. Animatable.prototype.stop = function (animationName) {
  29206. var index = this._scene._activeAnimatables.indexOf(this);
  29207. if (index > -1) {
  29208. var animations = this._animations;
  29209. var numberOfAnimationsStopped = 0;
  29210. for (var index = animations.length - 1; index >= 0; index--) {
  29211. if (typeof animationName === "string" && animations[index].name != animationName) {
  29212. continue;
  29213. }
  29214. animations[index].reset();
  29215. animations.splice(index, 1);
  29216. numberOfAnimationsStopped++;
  29217. }
  29218. if (animations.length == numberOfAnimationsStopped) {
  29219. this._scene._activeAnimatables.splice(index, 1);
  29220. if (this.onAnimationEnd) {
  29221. this.onAnimationEnd();
  29222. }
  29223. }
  29224. }
  29225. };
  29226. Animatable.prototype._animate = function (delay) {
  29227. if (this._paused) {
  29228. this.animationStarted = false;
  29229. if (!this._pausedDelay) {
  29230. this._pausedDelay = delay;
  29231. }
  29232. return true;
  29233. }
  29234. if (!this._localDelayOffset) {
  29235. this._localDelayOffset = delay;
  29236. }
  29237. else if (this._pausedDelay) {
  29238. this._localDelayOffset += delay - this._pausedDelay;
  29239. this._pausedDelay = null;
  29240. }
  29241. // Animating
  29242. var running = false;
  29243. var animations = this._animations;
  29244. var index;
  29245. for (index = 0; index < animations.length; index++) {
  29246. var animation = animations[index];
  29247. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  29248. running = running || isRunning;
  29249. }
  29250. this.animationStarted = running;
  29251. if (!running) {
  29252. // Remove from active animatables
  29253. index = this._scene._activeAnimatables.indexOf(this);
  29254. this._scene._activeAnimatables.splice(index, 1);
  29255. }
  29256. if (!running && this.onAnimationEnd) {
  29257. this.onAnimationEnd();
  29258. this.onAnimationEnd = null;
  29259. }
  29260. return running;
  29261. };
  29262. return Animatable;
  29263. }());
  29264. BABYLON.Animatable = Animatable;
  29265. })(BABYLON || (BABYLON = {}));
  29266. var BABYLON;
  29267. (function (BABYLON) {
  29268. var EasingFunction = (function () {
  29269. function EasingFunction() {
  29270. // Properties
  29271. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  29272. }
  29273. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  29274. get: function () {
  29275. return EasingFunction._EASINGMODE_EASEIN;
  29276. },
  29277. enumerable: true,
  29278. configurable: true
  29279. });
  29280. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  29281. get: function () {
  29282. return EasingFunction._EASINGMODE_EASEOUT;
  29283. },
  29284. enumerable: true,
  29285. configurable: true
  29286. });
  29287. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  29288. get: function () {
  29289. return EasingFunction._EASINGMODE_EASEINOUT;
  29290. },
  29291. enumerable: true,
  29292. configurable: true
  29293. });
  29294. EasingFunction.prototype.setEasingMode = function (easingMode) {
  29295. var n = Math.min(Math.max(easingMode, 0), 2);
  29296. this._easingMode = n;
  29297. };
  29298. EasingFunction.prototype.getEasingMode = function () {
  29299. return this._easingMode;
  29300. };
  29301. EasingFunction.prototype.easeInCore = function (gradient) {
  29302. throw new Error('You must implement this method');
  29303. };
  29304. EasingFunction.prototype.ease = function (gradient) {
  29305. switch (this._easingMode) {
  29306. case EasingFunction.EASINGMODE_EASEIN:
  29307. return this.easeInCore(gradient);
  29308. case EasingFunction.EASINGMODE_EASEOUT:
  29309. return (1 - this.easeInCore(1 - gradient));
  29310. }
  29311. if (gradient >= 0.5) {
  29312. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  29313. }
  29314. return (this.easeInCore(gradient * 2) * 0.5);
  29315. };
  29316. //Statics
  29317. EasingFunction._EASINGMODE_EASEIN = 0;
  29318. EasingFunction._EASINGMODE_EASEOUT = 1;
  29319. EasingFunction._EASINGMODE_EASEINOUT = 2;
  29320. return EasingFunction;
  29321. }());
  29322. BABYLON.EasingFunction = EasingFunction;
  29323. var CircleEase = (function (_super) {
  29324. __extends(CircleEase, _super);
  29325. function CircleEase() {
  29326. _super.apply(this, arguments);
  29327. }
  29328. CircleEase.prototype.easeInCore = function (gradient) {
  29329. gradient = Math.max(0, Math.min(1, gradient));
  29330. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  29331. };
  29332. return CircleEase;
  29333. }(EasingFunction));
  29334. BABYLON.CircleEase = CircleEase;
  29335. var BackEase = (function (_super) {
  29336. __extends(BackEase, _super);
  29337. function BackEase(amplitude) {
  29338. if (amplitude === void 0) { amplitude = 1; }
  29339. _super.call(this);
  29340. this.amplitude = amplitude;
  29341. }
  29342. BackEase.prototype.easeInCore = function (gradient) {
  29343. var num = Math.max(0, this.amplitude);
  29344. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  29345. };
  29346. return BackEase;
  29347. }(EasingFunction));
  29348. BABYLON.BackEase = BackEase;
  29349. var BounceEase = (function (_super) {
  29350. __extends(BounceEase, _super);
  29351. function BounceEase(bounces, bounciness) {
  29352. if (bounces === void 0) { bounces = 3; }
  29353. if (bounciness === void 0) { bounciness = 2; }
  29354. _super.call(this);
  29355. this.bounces = bounces;
  29356. this.bounciness = bounciness;
  29357. }
  29358. BounceEase.prototype.easeInCore = function (gradient) {
  29359. var y = Math.max(0.0, this.bounces);
  29360. var bounciness = this.bounciness;
  29361. if (bounciness <= 1.0) {
  29362. bounciness = 1.001;
  29363. }
  29364. var num9 = Math.pow(bounciness, y);
  29365. var num5 = 1.0 - bounciness;
  29366. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  29367. var num15 = gradient * num4;
  29368. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  29369. var num3 = Math.floor(num65);
  29370. var num13 = num3 + 1.0;
  29371. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  29372. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  29373. var num7 = (num8 + num12) * 0.5;
  29374. var num6 = gradient - num7;
  29375. var num2 = num7 - num8;
  29376. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  29377. };
  29378. return BounceEase;
  29379. }(EasingFunction));
  29380. BABYLON.BounceEase = BounceEase;
  29381. var CubicEase = (function (_super) {
  29382. __extends(CubicEase, _super);
  29383. function CubicEase() {
  29384. _super.apply(this, arguments);
  29385. }
  29386. CubicEase.prototype.easeInCore = function (gradient) {
  29387. return (gradient * gradient * gradient);
  29388. };
  29389. return CubicEase;
  29390. }(EasingFunction));
  29391. BABYLON.CubicEase = CubicEase;
  29392. var ElasticEase = (function (_super) {
  29393. __extends(ElasticEase, _super);
  29394. function ElasticEase(oscillations, springiness) {
  29395. if (oscillations === void 0) { oscillations = 3; }
  29396. if (springiness === void 0) { springiness = 3; }
  29397. _super.call(this);
  29398. this.oscillations = oscillations;
  29399. this.springiness = springiness;
  29400. }
  29401. ElasticEase.prototype.easeInCore = function (gradient) {
  29402. var num2;
  29403. var num3 = Math.max(0.0, this.oscillations);
  29404. var num = Math.max(0.0, this.springiness);
  29405. if (num == 0) {
  29406. num2 = gradient;
  29407. }
  29408. else {
  29409. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  29410. }
  29411. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  29412. };
  29413. return ElasticEase;
  29414. }(EasingFunction));
  29415. BABYLON.ElasticEase = ElasticEase;
  29416. var ExponentialEase = (function (_super) {
  29417. __extends(ExponentialEase, _super);
  29418. function ExponentialEase(exponent) {
  29419. if (exponent === void 0) { exponent = 2; }
  29420. _super.call(this);
  29421. this.exponent = exponent;
  29422. }
  29423. ExponentialEase.prototype.easeInCore = function (gradient) {
  29424. if (this.exponent <= 0) {
  29425. return gradient;
  29426. }
  29427. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  29428. };
  29429. return ExponentialEase;
  29430. }(EasingFunction));
  29431. BABYLON.ExponentialEase = ExponentialEase;
  29432. var PowerEase = (function (_super) {
  29433. __extends(PowerEase, _super);
  29434. function PowerEase(power) {
  29435. if (power === void 0) { power = 2; }
  29436. _super.call(this);
  29437. this.power = power;
  29438. }
  29439. PowerEase.prototype.easeInCore = function (gradient) {
  29440. var y = Math.max(0.0, this.power);
  29441. return Math.pow(gradient, y);
  29442. };
  29443. return PowerEase;
  29444. }(EasingFunction));
  29445. BABYLON.PowerEase = PowerEase;
  29446. var QuadraticEase = (function (_super) {
  29447. __extends(QuadraticEase, _super);
  29448. function QuadraticEase() {
  29449. _super.apply(this, arguments);
  29450. }
  29451. QuadraticEase.prototype.easeInCore = function (gradient) {
  29452. return (gradient * gradient);
  29453. };
  29454. return QuadraticEase;
  29455. }(EasingFunction));
  29456. BABYLON.QuadraticEase = QuadraticEase;
  29457. var QuarticEase = (function (_super) {
  29458. __extends(QuarticEase, _super);
  29459. function QuarticEase() {
  29460. _super.apply(this, arguments);
  29461. }
  29462. QuarticEase.prototype.easeInCore = function (gradient) {
  29463. return (gradient * gradient * gradient * gradient);
  29464. };
  29465. return QuarticEase;
  29466. }(EasingFunction));
  29467. BABYLON.QuarticEase = QuarticEase;
  29468. var QuinticEase = (function (_super) {
  29469. __extends(QuinticEase, _super);
  29470. function QuinticEase() {
  29471. _super.apply(this, arguments);
  29472. }
  29473. QuinticEase.prototype.easeInCore = function (gradient) {
  29474. return (gradient * gradient * gradient * gradient * gradient);
  29475. };
  29476. return QuinticEase;
  29477. }(EasingFunction));
  29478. BABYLON.QuinticEase = QuinticEase;
  29479. var SineEase = (function (_super) {
  29480. __extends(SineEase, _super);
  29481. function SineEase() {
  29482. _super.apply(this, arguments);
  29483. }
  29484. SineEase.prototype.easeInCore = function (gradient) {
  29485. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  29486. };
  29487. return SineEase;
  29488. }(EasingFunction));
  29489. BABYLON.SineEase = SineEase;
  29490. var BezierCurveEase = (function (_super) {
  29491. __extends(BezierCurveEase, _super);
  29492. function BezierCurveEase(x1, y1, x2, y2) {
  29493. if (x1 === void 0) { x1 = 0; }
  29494. if (y1 === void 0) { y1 = 0; }
  29495. if (x2 === void 0) { x2 = 1; }
  29496. if (y2 === void 0) { y2 = 1; }
  29497. _super.call(this);
  29498. this.x1 = x1;
  29499. this.y1 = y1;
  29500. this.x2 = x2;
  29501. this.y2 = y2;
  29502. }
  29503. BezierCurveEase.prototype.easeInCore = function (gradient) {
  29504. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  29505. };
  29506. return BezierCurveEase;
  29507. }(EasingFunction));
  29508. BABYLON.BezierCurveEase = BezierCurveEase;
  29509. })(BABYLON || (BABYLON = {}));
  29510. var BABYLON;
  29511. (function (BABYLON) {
  29512. var Bone = (function (_super) {
  29513. __extends(Bone, _super);
  29514. function Bone(name, skeleton, parentBone, matrix, restPose) {
  29515. _super.call(this, name, skeleton.getScene());
  29516. this.name = name;
  29517. this.children = new Array();
  29518. this.animations = new Array();
  29519. this._worldTransform = new BABYLON.Matrix();
  29520. this._absoluteTransform = new BABYLON.Matrix();
  29521. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  29522. this._scaleMatrix = BABYLON.Matrix.Identity();
  29523. this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  29524. this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  29525. this._scalingDeterminant = 1;
  29526. this._syncScaleVector = function () {
  29527. var lm = this.getLocalMatrix();
  29528. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  29529. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  29530. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  29531. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  29532. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  29533. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  29534. this._scaleVector.x = xs * Math.sqrt(xsq);
  29535. this._scaleVector.y = ys * Math.sqrt(ysq);
  29536. this._scaleVector.z = zs * Math.sqrt(zsq);
  29537. if (this._parent) {
  29538. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  29539. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  29540. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  29541. }
  29542. 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);
  29543. };
  29544. this._skeleton = skeleton;
  29545. this._matrix = matrix;
  29546. this._baseMatrix = matrix;
  29547. this._restPose = restPose ? restPose : matrix.clone();
  29548. skeleton.bones.push(this);
  29549. if (parentBone) {
  29550. this._parent = parentBone;
  29551. parentBone.children.push(this);
  29552. }
  29553. else {
  29554. this._parent = null;
  29555. }
  29556. this._updateDifferenceMatrix();
  29557. if (this.getAbsoluteTransform().determinant() < 0) {
  29558. this._scalingDeterminant *= -1;
  29559. }
  29560. }
  29561. // Members
  29562. Bone.prototype.getParent = function () {
  29563. return this._parent;
  29564. };
  29565. Bone.prototype.getLocalMatrix = function () {
  29566. return this._matrix;
  29567. };
  29568. Bone.prototype.getBaseMatrix = function () {
  29569. return this._baseMatrix;
  29570. };
  29571. Bone.prototype.getRestPose = function () {
  29572. return this._restPose;
  29573. };
  29574. Bone.prototype.returnToRest = function () {
  29575. this.updateMatrix(this._restPose.clone());
  29576. };
  29577. Bone.prototype.getWorldMatrix = function () {
  29578. return this._worldTransform;
  29579. };
  29580. Bone.prototype.getInvertedAbsoluteTransform = function () {
  29581. return this._invertedAbsoluteTransform;
  29582. };
  29583. Bone.prototype.getAbsoluteTransform = function () {
  29584. return this._absoluteTransform;
  29585. };
  29586. // Methods
  29587. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  29588. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  29589. this._baseMatrix = matrix.clone();
  29590. this._matrix = matrix.clone();
  29591. this._skeleton._markAsDirty();
  29592. if (updateDifferenceMatrix) {
  29593. this._updateDifferenceMatrix();
  29594. }
  29595. };
  29596. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  29597. if (!rootMatrix) {
  29598. rootMatrix = this._baseMatrix;
  29599. }
  29600. if (this._parent) {
  29601. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  29602. }
  29603. else {
  29604. this._absoluteTransform.copyFrom(rootMatrix);
  29605. }
  29606. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  29607. for (var index = 0; index < this.children.length; index++) {
  29608. this.children[index]._updateDifferenceMatrix();
  29609. }
  29610. };
  29611. Bone.prototype.markAsDirty = function () {
  29612. this._currentRenderId++;
  29613. this._skeleton._markAsDirty();
  29614. };
  29615. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  29616. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  29617. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  29618. // all animation may be coming from a library skeleton, so may need to create animation
  29619. if (this.animations.length === 0) {
  29620. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  29621. this.animations[0].setKeys([]);
  29622. }
  29623. // get animation info / verify there is such a range from the source bone
  29624. var sourceRange = source.animations[0].getRange(rangeName);
  29625. if (!sourceRange) {
  29626. return false;
  29627. }
  29628. var from = sourceRange.from;
  29629. var to = sourceRange.to;
  29630. var sourceKeys = source.animations[0].getKeys();
  29631. // rescaling prep
  29632. var sourceBoneLength = source.length;
  29633. var sourceParent = source.getParent();
  29634. var parent = this.getParent();
  29635. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  29636. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  29637. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  29638. var destKeys = this.animations[0].getKeys();
  29639. // loop vars declaration
  29640. var orig;
  29641. var origTranslation;
  29642. var mat;
  29643. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  29644. orig = sourceKeys[key];
  29645. if (orig.frame >= from && orig.frame <= to) {
  29646. if (rescaleAsRequired) {
  29647. mat = orig.value.clone();
  29648. // scale based on parent ratio, when bone has parent
  29649. if (parentScalingReqd) {
  29650. origTranslation = mat.getTranslation();
  29651. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  29652. }
  29653. else if (dimensionsScalingReqd) {
  29654. origTranslation = mat.getTranslation();
  29655. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  29656. }
  29657. else {
  29658. mat = orig.value;
  29659. }
  29660. }
  29661. else {
  29662. mat = orig.value;
  29663. }
  29664. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  29665. }
  29666. }
  29667. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  29668. return true;
  29669. };
  29670. Bone.prototype.translate = function (vec) {
  29671. var lm = this.getLocalMatrix();
  29672. lm.m[12] += vec.x;
  29673. lm.m[13] += vec.y;
  29674. lm.m[14] += vec.z;
  29675. this.markAsDirty();
  29676. };
  29677. Bone.prototype.setPosition = function (position) {
  29678. var lm = this.getLocalMatrix();
  29679. lm.m[12] = position.x;
  29680. lm.m[13] = position.y;
  29681. lm.m[14] = position.z;
  29682. this.markAsDirty();
  29683. };
  29684. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  29685. if (mesh === void 0) { mesh = null; }
  29686. this._skeleton.computeAbsoluteTransforms();
  29687. var tmat = BABYLON.Tmp.Matrix[0];
  29688. var vec = BABYLON.Tmp.Vector3[0];
  29689. if (mesh) {
  29690. tmat.copyFrom(this._parent.getAbsoluteTransform());
  29691. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  29692. }
  29693. else {
  29694. tmat.copyFrom(this._parent.getAbsoluteTransform());
  29695. }
  29696. tmat.invert();
  29697. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  29698. var lm = this.getLocalMatrix();
  29699. lm.m[12] = vec.x;
  29700. lm.m[13] = vec.y;
  29701. lm.m[14] = vec.z;
  29702. this.markAsDirty();
  29703. };
  29704. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  29705. if (scaleChildren === void 0) { scaleChildren = false; }
  29706. if (this.animations[0] && !this.animations[0].isStopped()) {
  29707. if (!scaleChildren) {
  29708. this._negateScaleChildren.x = 1 / x;
  29709. this._negateScaleChildren.y = 1 / y;
  29710. this._negateScaleChildren.z = 1 / z;
  29711. }
  29712. this._syncScaleVector();
  29713. }
  29714. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  29715. };
  29716. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  29717. if (scaleChildren === void 0) { scaleChildren = false; }
  29718. var locMat = this.getLocalMatrix();
  29719. var origLocMat = BABYLON.Tmp.Matrix[0];
  29720. origLocMat.copyFrom(locMat);
  29721. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  29722. origLocMatInv.copyFrom(origLocMat);
  29723. origLocMatInv.invert();
  29724. var scaleMat = BABYLON.Tmp.Matrix[2];
  29725. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  29726. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  29727. this._scaleVector.x *= x;
  29728. this._scaleVector.y *= y;
  29729. this._scaleVector.z *= z;
  29730. locMat.multiplyToRef(origLocMatInv, locMat);
  29731. locMat.multiplyToRef(scaleMat, locMat);
  29732. locMat.multiplyToRef(origLocMat, locMat);
  29733. var parent = this.getParent();
  29734. if (parent) {
  29735. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  29736. }
  29737. else {
  29738. this.getAbsoluteTransform().copyFrom(locMat);
  29739. }
  29740. var len = this.children.length;
  29741. scaleMat.invert();
  29742. for (var i = 0; i < len; i++) {
  29743. var child = this.children[i];
  29744. var cm = child.getLocalMatrix();
  29745. cm.multiplyToRef(scaleMat, cm);
  29746. var lm = child.getLocalMatrix();
  29747. lm.m[12] *= x;
  29748. lm.m[13] *= y;
  29749. lm.m[14] *= z;
  29750. }
  29751. this.computeAbsoluteTransforms();
  29752. if (scaleChildren) {
  29753. for (var i = 0; i < len; i++) {
  29754. this.children[i].scale(x, y, z, scaleChildren);
  29755. }
  29756. }
  29757. this.markAsDirty();
  29758. };
  29759. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  29760. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  29761. if (mesh === void 0) { mesh = null; }
  29762. var rotMat = BABYLON.Tmp.Matrix[0];
  29763. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  29764. var rotMatInv = BABYLON.Tmp.Matrix[1];
  29765. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  29766. rotMatInv.multiplyToRef(rotMat, rotMat);
  29767. this._rotateWithMatrix(rotMat, space, mesh);
  29768. };
  29769. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  29770. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  29771. if (mesh === void 0) { mesh = null; }
  29772. var rmat = BABYLON.Tmp.Matrix[0];
  29773. rmat.m[12] = 0;
  29774. rmat.m[13] = 0;
  29775. rmat.m[14] = 0;
  29776. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  29777. this._rotateWithMatrix(rmat, space, mesh);
  29778. };
  29779. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  29780. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  29781. if (mesh === void 0) { mesh = null; }
  29782. var rotMat = BABYLON.Tmp.Matrix[0];
  29783. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  29784. var rotMatInv = BABYLON.Tmp.Matrix[1];
  29785. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  29786. rotMatInv.multiplyToRef(rotMat, rotMat);
  29787. this._rotateWithMatrix(rotMat, space, mesh);
  29788. };
  29789. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  29790. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  29791. if (mesh === void 0) { mesh = null; }
  29792. var rotMatInv = BABYLON.Tmp.Matrix[0];
  29793. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  29794. var rotMat2 = BABYLON.Tmp.Matrix[1];
  29795. rotMat2.copyFrom(rotMat);
  29796. rotMatInv.multiplyToRef(rotMat, rotMat2);
  29797. this._rotateWithMatrix(rotMat2, space, mesh);
  29798. };
  29799. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  29800. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  29801. if (mesh === void 0) { mesh = null; }
  29802. var lmat = this.getLocalMatrix();
  29803. var lx = lmat.m[12];
  29804. var ly = lmat.m[13];
  29805. var lz = lmat.m[14];
  29806. var parent = this.getParent();
  29807. var parentScale = BABYLON.Tmp.Matrix[3];
  29808. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  29809. if (parent) {
  29810. if (space == BABYLON.Space.WORLD) {
  29811. if (mesh) {
  29812. parentScale.copyFrom(mesh.getWorldMatrix());
  29813. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  29814. }
  29815. else {
  29816. parentScale.copyFrom(parent.getAbsoluteTransform());
  29817. }
  29818. }
  29819. else {
  29820. parentScale = parent._scaleMatrix;
  29821. }
  29822. parentScaleInv.copyFrom(parentScale);
  29823. parentScaleInv.invert();
  29824. lmat.multiplyToRef(parentScale, lmat);
  29825. lmat.multiplyToRef(rmat, lmat);
  29826. lmat.multiplyToRef(parentScaleInv, lmat);
  29827. }
  29828. else {
  29829. if (space == BABYLON.Space.WORLD && mesh) {
  29830. parentScale.copyFrom(mesh.getWorldMatrix());
  29831. parentScaleInv.copyFrom(parentScale);
  29832. parentScaleInv.invert();
  29833. lmat.multiplyToRef(parentScale, lmat);
  29834. lmat.multiplyToRef(rmat, lmat);
  29835. lmat.multiplyToRef(parentScaleInv, lmat);
  29836. }
  29837. else {
  29838. lmat.multiplyToRef(rmat, lmat);
  29839. }
  29840. }
  29841. lmat.m[12] = lx;
  29842. lmat.m[13] = ly;
  29843. lmat.m[14] = lz;
  29844. this.computeAbsoluteTransforms();
  29845. this.markAsDirty();
  29846. };
  29847. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  29848. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  29849. if (mesh === void 0) { mesh = null; }
  29850. if (space == BABYLON.Space.WORLD) {
  29851. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  29852. scaleMatrix.copyFrom(this._scaleMatrix);
  29853. rotMatInv.copyFrom(this.getAbsoluteTransform());
  29854. if (mesh) {
  29855. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  29856. var meshScale = BABYLON.Tmp.Matrix[3];
  29857. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  29858. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  29859. }
  29860. rotMatInv.invert();
  29861. scaleMatrix.m[0] *= this._scalingDeterminant;
  29862. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  29863. }
  29864. else {
  29865. rotMatInv.copyFrom(this.getLocalMatrix());
  29866. rotMatInv.invert();
  29867. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  29868. scaleMatrix.copyFrom(this._scaleMatrix);
  29869. if (this._parent) {
  29870. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  29871. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  29872. pscaleMatrix.invert();
  29873. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  29874. }
  29875. else {
  29876. scaleMatrix.m[0] *= this._scalingDeterminant;
  29877. }
  29878. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  29879. }
  29880. };
  29881. Bone.prototype.getScale = function () {
  29882. return this._scaleVector.clone();
  29883. };
  29884. Bone.prototype.getScaleToRef = function (result) {
  29885. result.copyFrom(this._scaleVector);
  29886. };
  29887. Bone.prototype.getAbsolutePosition = function (mesh) {
  29888. if (mesh === void 0) { mesh = null; }
  29889. var pos = BABYLON.Vector3.Zero();
  29890. this.getAbsolutePositionToRef(mesh, pos);
  29891. return pos;
  29892. };
  29893. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  29894. if (mesh === void 0) { mesh = null; }
  29895. this._skeleton.computeAbsoluteTransforms();
  29896. var tmat = BABYLON.Tmp.Matrix[0];
  29897. if (mesh) {
  29898. tmat.copyFrom(this.getAbsoluteTransform());
  29899. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  29900. }
  29901. else {
  29902. tmat = this.getAbsoluteTransform();
  29903. }
  29904. result.x = tmat.m[12];
  29905. result.y = tmat.m[13];
  29906. result.z = tmat.m[14];
  29907. };
  29908. Bone.prototype.computeAbsoluteTransforms = function () {
  29909. if (this._parent) {
  29910. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  29911. }
  29912. else {
  29913. this._absoluteTransform.copyFrom(this._matrix);
  29914. var poseMatrix = this._skeleton.getPoseMatrix();
  29915. if (poseMatrix) {
  29916. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  29917. }
  29918. }
  29919. var children = this.children;
  29920. var len = children.length;
  29921. for (var i = 0; i < len; i++) {
  29922. children[i].computeAbsoluteTransforms();
  29923. }
  29924. };
  29925. Bone.prototype.getDirection = function (localAxis, mesh) {
  29926. var result = BABYLON.Vector3.Zero();
  29927. this.getDirectionToRef(localAxis, result, mesh);
  29928. return result;
  29929. };
  29930. Bone.prototype.getDirectionToRef = function (localAxis, result, mesh) {
  29931. this._skeleton.computeAbsoluteTransforms();
  29932. var mat = BABYLON.Tmp.Matrix[0];
  29933. mat.copyFrom(this.getAbsoluteTransform());
  29934. if (mesh) {
  29935. mat.multiplyToRef(mesh.getWorldMatrix(), mat);
  29936. }
  29937. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  29938. result.normalize();
  29939. };
  29940. Bone.prototype.getRotation = function (mesh) {
  29941. var result = BABYLON.Quaternion.Identity();
  29942. this.getRotationToRef(mesh, result);
  29943. return result;
  29944. };
  29945. Bone.prototype.getRotationToRef = function (mesh, result) {
  29946. var mat = BABYLON.Tmp.Matrix[0];
  29947. var amat = this.getAbsoluteTransform();
  29948. var wmat = mesh.getWorldMatrix();
  29949. amat.multiplyToRef(wmat, mat);
  29950. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  29951. };
  29952. return Bone;
  29953. }(BABYLON.Node));
  29954. BABYLON.Bone = Bone;
  29955. })(BABYLON || (BABYLON = {}));
  29956. var BABYLON;
  29957. (function (BABYLON) {
  29958. var BoneIKController = (function () {
  29959. function BoneIKController(mesh, bone, target, poleTarget, poleAngle) {
  29960. if (poleAngle === void 0) { poleAngle = 0; }
  29961. this.poleAngle = 0;
  29962. this._maxAngle = Math.PI;
  29963. this._tmpVec1 = BABYLON.Vector3.Zero();
  29964. this._tmpVec2 = BABYLON.Vector3.Zero();
  29965. this._tmpVec3 = BABYLON.Vector3.Zero();
  29966. this._tmpVec4 = BABYLON.Vector3.Zero();
  29967. this._tmpVec5 = BABYLON.Vector3.Zero();
  29968. this._tmpMat1 = BABYLON.Matrix.Identity();
  29969. this._tmpMat2 = BABYLON.Matrix.Identity();
  29970. this._rightHandedSystem = false;
  29971. target.computeWorldMatrix(true);
  29972. poleTarget.computeWorldMatrix(true);
  29973. this._bone2 = bone;
  29974. this._bone1 = bone.getParent();
  29975. this.target = target;
  29976. this.poleTarget = poleTarget;
  29977. this.poleAngle = poleAngle;
  29978. this.mesh = mesh;
  29979. if (bone.getAbsoluteTransform().determinant() > 0) {
  29980. this._rightHandedSystem = true;
  29981. }
  29982. if (this._bone1.length) {
  29983. var boneScale1 = this._bone1.getScale();
  29984. var boneScale2 = this._bone2.getScale();
  29985. this._bone1Length = this._bone1.length * boneScale1.y;
  29986. this._bone2Length = this._bone2.length * boneScale2.y;
  29987. }
  29988. else if (this._bone1.children[0]) {
  29989. mesh.computeWorldMatrix(true);
  29990. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  29991. var pos2 = this._bone2.getAbsolutePosition(mesh);
  29992. var pos3 = this._bone1.getAbsolutePosition(mesh);
  29993. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  29994. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  29995. }
  29996. this.maxAngle = Math.PI;
  29997. }
  29998. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  29999. get: function () {
  30000. return this._maxAngle;
  30001. },
  30002. set: function (value) {
  30003. this._setMaxAngle(value);
  30004. },
  30005. enumerable: true,
  30006. configurable: true
  30007. });
  30008. BoneIKController.prototype._setMaxAngle = function (ang) {
  30009. if (ang < 0) {
  30010. ang = 0;
  30011. }
  30012. if (ang > Math.PI || ang == undefined) {
  30013. ang = Math.PI;
  30014. }
  30015. this._maxAngle = ang;
  30016. var a = this._bone1Length;
  30017. var b = this._bone2Length;
  30018. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  30019. };
  30020. BoneIKController.prototype.update = function () {
  30021. var bone1 = this._bone1;
  30022. var target = this.target.getAbsolutePosition();
  30023. var poleTarget = this.poleTarget.getAbsolutePosition();
  30024. var bonePos = this._tmpVec1;
  30025. var zaxis = this._tmpVec2;
  30026. var xaxis = this._tmpVec3;
  30027. var yaxis = this._tmpVec4;
  30028. var upAxis = this._tmpVec5;
  30029. var mat1 = this._tmpMat1;
  30030. var mat2 = this._tmpMat2;
  30031. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  30032. poleTarget.subtractToRef(bonePos, upAxis);
  30033. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  30034. upAxis.y = 1;
  30035. }
  30036. else {
  30037. upAxis.normalize();
  30038. }
  30039. target.subtractToRef(bonePos, yaxis);
  30040. yaxis.normalize();
  30041. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  30042. zaxis.normalize();
  30043. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  30044. xaxis.normalize();
  30045. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  30046. var a = this._bone1Length;
  30047. var b = this._bone2Length;
  30048. var c = BABYLON.Vector3.Distance(bonePos, target);
  30049. if (this._maxReach > 0) {
  30050. c = Math.min(this._maxReach, c);
  30051. }
  30052. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  30053. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  30054. if (acosa > 1) {
  30055. acosa = 1;
  30056. }
  30057. if (acosb > 1) {
  30058. acosb = 1;
  30059. }
  30060. if (acosa < -1) {
  30061. acosa = -1;
  30062. }
  30063. if (acosb < -1) {
  30064. acosb = -1;
  30065. }
  30066. var angA = Math.acos(acosa);
  30067. var angB = Math.acos(acosb);
  30068. var angC = -angA - angB;
  30069. var bendAxis = this._tmpVec1;
  30070. bendAxis.x = 0;
  30071. bendAxis.y = 0;
  30072. bendAxis.z = 0;
  30073. if (this._rightHandedSystem) {
  30074. bendAxis.z = 1;
  30075. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, angB + Math.PI * .5, mat2);
  30076. mat2.multiplyToRef(mat1, mat1);
  30077. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle + Math.PI, mat2);
  30078. mat1.multiplyToRef(mat2, mat1);
  30079. }
  30080. else {
  30081. bendAxis.x = 1;
  30082. BABYLON.Matrix.RotationYawPitchRollToRef(0, angB, 0, mat2);
  30083. mat2.multiplyToRef(mat1, mat1);
  30084. if (this.poleAngle) {
  30085. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  30086. mat1.multiplyToRef(mat2, mat1);
  30087. }
  30088. }
  30089. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  30090. this._bone2.setAxisAngle(bendAxis, angC, BABYLON.Space.LOCAL);
  30091. };
  30092. return BoneIKController;
  30093. }());
  30094. BABYLON.BoneIKController = BoneIKController;
  30095. })(BABYLON || (BABYLON = {}));
  30096. var BABYLON;
  30097. (function (BABYLON) {
  30098. var BoneLookController = (function () {
  30099. function BoneLookController(mesh, bone, target, adjustYaw, adjustPitch, adjustRoll) {
  30100. if (adjustYaw === void 0) { adjustYaw = 0; }
  30101. if (adjustPitch === void 0) { adjustPitch = 0; }
  30102. if (adjustRoll === void 0) { adjustRoll = 0; }
  30103. this.upAxis = BABYLON.Vector3.Up();
  30104. this.adjustYaw = 0;
  30105. this.adjustPitch = 0;
  30106. this.adjustRoll = 0;
  30107. this._tmpVec1 = BABYLON.Vector3.Zero();
  30108. this._tmpVec2 = BABYLON.Vector3.Zero();
  30109. this._tmpVec3 = BABYLON.Vector3.Zero();
  30110. this._tmpVec4 = BABYLON.Vector3.Zero();
  30111. this._tmpMat1 = BABYLON.Matrix.Identity();
  30112. this._tmpMat2 = BABYLON.Matrix.Identity();
  30113. this.mesh = mesh;
  30114. this.bone = bone;
  30115. this.target = target;
  30116. this.adjustYaw = adjustYaw;
  30117. this.adjustPitch = adjustPitch;
  30118. this.adjustRoll = adjustRoll;
  30119. }
  30120. BoneLookController.prototype.update = function () {
  30121. var bone = this.bone;
  30122. var target = this.target;
  30123. var bonePos = this._tmpVec1;
  30124. var zaxis = this._tmpVec2;
  30125. var xaxis = this._tmpVec3;
  30126. var yaxis = this._tmpVec4;
  30127. var mat1 = this._tmpMat1;
  30128. var mat2 = this._tmpMat2;
  30129. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  30130. target.subtractToRef(bonePos, zaxis);
  30131. zaxis.normalize();
  30132. BABYLON.Vector3.CrossToRef(this.upAxis, zaxis, xaxis);
  30133. xaxis.normalize();
  30134. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  30135. yaxis.normalize();
  30136. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  30137. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  30138. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, mat2);
  30139. mat2.multiplyToRef(mat1, mat1);
  30140. }
  30141. this.bone.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  30142. };
  30143. return BoneLookController;
  30144. }());
  30145. BABYLON.BoneLookController = BoneLookController;
  30146. })(BABYLON || (BABYLON = {}));
  30147. var BABYLON;
  30148. (function (BABYLON) {
  30149. var Skeleton = (function () {
  30150. function Skeleton(name, id, scene) {
  30151. this.name = name;
  30152. this.id = id;
  30153. this.bones = new Array();
  30154. this.needInitialSkinMatrix = false;
  30155. this._isDirty = true;
  30156. this._meshesWithPoseMatrix = new Array();
  30157. this._identity = BABYLON.Matrix.Identity();
  30158. this._ranges = {};
  30159. this._lastAbsoluteTransformsUpdateId = -1;
  30160. this.bones = [];
  30161. this._scene = scene;
  30162. scene.skeletons.push(this);
  30163. //make sure it will recalculate the matrix next time prepare is called.
  30164. this._isDirty = true;
  30165. }
  30166. // Members
  30167. Skeleton.prototype.getTransformMatrices = function (mesh) {
  30168. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  30169. return mesh._bonesTransformMatrices;
  30170. }
  30171. return this._transformMatrices;
  30172. };
  30173. Skeleton.prototype.getScene = function () {
  30174. return this._scene;
  30175. };
  30176. // Methods
  30177. /**
  30178. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30179. */
  30180. Skeleton.prototype.toString = function (fullDetails) {
  30181. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  30182. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  30183. if (fullDetails) {
  30184. ret += ", Ranges: {";
  30185. var first = true;
  30186. for (var name_1 in this._ranges) {
  30187. if (first) {
  30188. ret += ", ";
  30189. first = false;
  30190. }
  30191. ret += name_1;
  30192. }
  30193. ret += "}";
  30194. }
  30195. return ret;
  30196. };
  30197. /**
  30198. * Get bone's index searching by name
  30199. * @param {string} name is bone's name to search for
  30200. * @return {number} Indice of the bone. Returns -1 if not found
  30201. */
  30202. Skeleton.prototype.getBoneIndexByName = function (name) {
  30203. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  30204. if (this.bones[boneIndex].name === name) {
  30205. return boneIndex;
  30206. }
  30207. }
  30208. return -1;
  30209. };
  30210. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  30211. // check name not already in use
  30212. if (!this._ranges[name]) {
  30213. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  30214. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  30215. if (this.bones[i].animations[0]) {
  30216. this.bones[i].animations[0].createRange(name, from, to);
  30217. }
  30218. }
  30219. }
  30220. };
  30221. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  30222. if (deleteFrames === void 0) { deleteFrames = true; }
  30223. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  30224. if (this.bones[i].animations[0]) {
  30225. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  30226. }
  30227. }
  30228. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  30229. };
  30230. Skeleton.prototype.getAnimationRange = function (name) {
  30231. return this._ranges[name];
  30232. };
  30233. /**
  30234. * Returns as an Array, all AnimationRanges defined on this skeleton
  30235. */
  30236. Skeleton.prototype.getAnimationRanges = function () {
  30237. var animationRanges = [];
  30238. var name;
  30239. var i = 0;
  30240. for (name in this._ranges) {
  30241. animationRanges[i] = this._ranges[name];
  30242. i++;
  30243. }
  30244. return animationRanges;
  30245. };
  30246. /**
  30247. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  30248. */
  30249. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  30250. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  30251. if (this._ranges[name] || !source.getAnimationRange(name)) {
  30252. return false;
  30253. }
  30254. var ret = true;
  30255. var frameOffset = this._getHighestAnimationFrame() + 1;
  30256. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  30257. var boneDict = {};
  30258. var sourceBones = source.bones;
  30259. var nBones;
  30260. var i;
  30261. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  30262. boneDict[sourceBones[i].name] = sourceBones[i];
  30263. }
  30264. if (this.bones.length !== sourceBones.length) {
  30265. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  30266. ret = false;
  30267. }
  30268. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  30269. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  30270. var boneName = this.bones[i].name;
  30271. var sourceBone = boneDict[boneName];
  30272. if (sourceBone) {
  30273. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  30274. }
  30275. else {
  30276. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  30277. ret = false;
  30278. }
  30279. }
  30280. // do not call createAnimationRange(), since it also is done to bones, which was already done
  30281. var range = source.getAnimationRange(name);
  30282. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  30283. return ret;
  30284. };
  30285. Skeleton.prototype.returnToRest = function () {
  30286. for (var index = 0; index < this.bones.length; index++) {
  30287. this.bones[index].returnToRest();
  30288. }
  30289. };
  30290. Skeleton.prototype._getHighestAnimationFrame = function () {
  30291. var ret = 0;
  30292. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  30293. if (this.bones[i].animations[0]) {
  30294. var highest = this.bones[i].animations[0].getHighestFrame();
  30295. if (ret < highest) {
  30296. ret = highest;
  30297. }
  30298. }
  30299. }
  30300. return ret;
  30301. };
  30302. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  30303. var range = this.getAnimationRange(name);
  30304. if (!range) {
  30305. return null;
  30306. }
  30307. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  30308. };
  30309. Skeleton.prototype._markAsDirty = function () {
  30310. this._isDirty = true;
  30311. };
  30312. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  30313. this._meshesWithPoseMatrix.push(mesh);
  30314. };
  30315. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  30316. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  30317. if (index > -1) {
  30318. this._meshesWithPoseMatrix.splice(index, 1);
  30319. }
  30320. };
  30321. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  30322. for (var index = 0; index < this.bones.length; index++) {
  30323. var bone = this.bones[index];
  30324. var parentBone = bone.getParent();
  30325. if (parentBone) {
  30326. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  30327. }
  30328. else {
  30329. if (initialSkinMatrix) {
  30330. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  30331. }
  30332. else {
  30333. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  30334. }
  30335. }
  30336. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  30337. }
  30338. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  30339. };
  30340. Skeleton.prototype.prepare = function () {
  30341. if (!this._isDirty) {
  30342. return;
  30343. }
  30344. if (this.needInitialSkinMatrix) {
  30345. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  30346. var mesh = this._meshesWithPoseMatrix[index];
  30347. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  30348. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  30349. }
  30350. var poseMatrix = mesh.getPoseMatrix();
  30351. // Prepare bones
  30352. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  30353. var bone = this.bones[boneIndex];
  30354. if (!bone.getParent()) {
  30355. var matrix = bone.getBaseMatrix();
  30356. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  30357. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  30358. }
  30359. }
  30360. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  30361. }
  30362. }
  30363. else {
  30364. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  30365. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  30366. }
  30367. this._computeTransformMatrices(this._transformMatrices, null);
  30368. }
  30369. this._isDirty = false;
  30370. this._scene._activeBones.addCount(this.bones.length, false);
  30371. };
  30372. Skeleton.prototype.getAnimatables = function () {
  30373. if (!this._animatables || this._animatables.length !== this.bones.length) {
  30374. this._animatables = [];
  30375. for (var index = 0; index < this.bones.length; index++) {
  30376. this._animatables.push(this.bones[index]);
  30377. }
  30378. }
  30379. return this._animatables;
  30380. };
  30381. Skeleton.prototype.clone = function (name, id) {
  30382. var result = new Skeleton(name, id || name, this._scene);
  30383. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  30384. for (var index = 0; index < this.bones.length; index++) {
  30385. var source = this.bones[index];
  30386. var parentBone = null;
  30387. if (source.getParent()) {
  30388. var parentIndex = this.bones.indexOf(source.getParent());
  30389. parentBone = result.bones[parentIndex];
  30390. }
  30391. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  30392. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  30393. }
  30394. if (this._ranges) {
  30395. result._ranges = {};
  30396. for (var rangeName in this._ranges) {
  30397. result._ranges[rangeName] = this._ranges[rangeName].clone();
  30398. }
  30399. }
  30400. this._isDirty = true;
  30401. return result;
  30402. };
  30403. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  30404. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  30405. this.bones.forEach(function (bone) {
  30406. bone.animations.forEach(function (animation) {
  30407. animation.enableBlending = true;
  30408. animation.blendingSpeed = blendingSpeed;
  30409. });
  30410. });
  30411. };
  30412. Skeleton.prototype.dispose = function () {
  30413. this._meshesWithPoseMatrix = [];
  30414. // Animations
  30415. this.getScene().stopAnimation(this);
  30416. // Remove from scene
  30417. this.getScene().removeSkeleton(this);
  30418. };
  30419. Skeleton.prototype.serialize = function () {
  30420. var serializationObject = {};
  30421. serializationObject.name = this.name;
  30422. serializationObject.id = this.id;
  30423. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  30424. serializationObject.bones = [];
  30425. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  30426. for (var index = 0; index < this.bones.length; index++) {
  30427. var bone = this.bones[index];
  30428. var serializedBone = {
  30429. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  30430. name: bone.name,
  30431. matrix: bone.getLocalMatrix().toArray(),
  30432. rest: bone.getRestPose().toArray()
  30433. };
  30434. serializationObject.bones.push(serializedBone);
  30435. if (bone.length) {
  30436. serializedBone.length = bone.length;
  30437. }
  30438. if (bone.animations && bone.animations.length > 0) {
  30439. serializedBone.animation = bone.animations[0].serialize();
  30440. }
  30441. serializationObject.ranges = [];
  30442. for (var name in this._ranges) {
  30443. var range = {};
  30444. range.name = name;
  30445. range.from = this._ranges[name].from;
  30446. range.to = this._ranges[name].to;
  30447. serializationObject.ranges.push(range);
  30448. }
  30449. }
  30450. return serializationObject;
  30451. };
  30452. Skeleton.Parse = function (parsedSkeleton, scene) {
  30453. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  30454. if (parsedSkeleton.dimensionsAtRest) {
  30455. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  30456. }
  30457. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  30458. var index;
  30459. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  30460. var parsedBone = parsedSkeleton.bones[index];
  30461. var parentBone = null;
  30462. if (parsedBone.parentBoneIndex > -1) {
  30463. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  30464. }
  30465. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  30466. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  30467. if (parsedBone.length) {
  30468. bone.length = parsedBone.length;
  30469. }
  30470. if (parsedBone.animation) {
  30471. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  30472. }
  30473. }
  30474. // placed after bones, so createAnimationRange can cascade down
  30475. if (parsedSkeleton.ranges) {
  30476. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  30477. var data = parsedSkeleton.ranges[index];
  30478. skeleton.createAnimationRange(data.name, data.from, data.to);
  30479. }
  30480. }
  30481. return skeleton;
  30482. };
  30483. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  30484. if (forceUpdate === void 0) { forceUpdate = false; }
  30485. var renderId = this._scene.getRenderId();
  30486. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  30487. this.bones[0].computeAbsoluteTransforms();
  30488. this._lastAbsoluteTransformsUpdateId = renderId;
  30489. }
  30490. };
  30491. Skeleton.prototype.getPoseMatrix = function () {
  30492. var poseMatrix;
  30493. if (this._meshesWithPoseMatrix.length > 0) {
  30494. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  30495. }
  30496. return poseMatrix;
  30497. };
  30498. return Skeleton;
  30499. }());
  30500. BABYLON.Skeleton = Skeleton;
  30501. })(BABYLON || (BABYLON = {}));
  30502. var BABYLON;
  30503. (function (BABYLON) {
  30504. var PostProcess = (function () {
  30505. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  30506. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  30507. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  30508. this.name = name;
  30509. this.width = -1;
  30510. this.height = -1;
  30511. /*
  30512. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  30513. Can only be used on a single postprocess or on the last one of a chain.
  30514. */
  30515. this.enablePixelPerfectMode = false;
  30516. this._reusable = false;
  30517. this._textures = new BABYLON.SmartArray(2);
  30518. this._currentRenderTextureInd = 0;
  30519. this._scaleRatio = new BABYLON.Vector2(1, 1);
  30520. // Events
  30521. /**
  30522. * An event triggered when the postprocess is activated.
  30523. * @type {BABYLON.Observable}
  30524. */
  30525. this.onActivateObservable = new BABYLON.Observable();
  30526. /**
  30527. * An event triggered when the postprocess changes its size.
  30528. * @type {BABYLON.Observable}
  30529. */
  30530. this.onSizeChangedObservable = new BABYLON.Observable();
  30531. /**
  30532. * An event triggered when the postprocess applies its effect.
  30533. * @type {BABYLON.Observable}
  30534. */
  30535. this.onApplyObservable = new BABYLON.Observable();
  30536. /**
  30537. * An event triggered before rendering the postprocess
  30538. * @type {BABYLON.Observable}
  30539. */
  30540. this.onBeforeRenderObservable = new BABYLON.Observable();
  30541. /**
  30542. * An event triggered after rendering the postprocess
  30543. * @type {BABYLON.Observable}
  30544. */
  30545. this.onAfterRenderObservable = new BABYLON.Observable();
  30546. if (camera != null) {
  30547. this._camera = camera;
  30548. this._scene = camera.getScene();
  30549. camera.attachPostProcess(this);
  30550. this._engine = this._scene.getEngine();
  30551. }
  30552. else {
  30553. this._engine = engine;
  30554. }
  30555. this._options = options;
  30556. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  30557. this._reusable = reusable || false;
  30558. this._textureType = textureType;
  30559. this._samplers = samplers || [];
  30560. this._samplers.push("textureSampler");
  30561. this._fragmentUrl = fragmentUrl;
  30562. this._parameters = parameters || [];
  30563. this._parameters.push("scale");
  30564. this.updateEffect(defines);
  30565. }
  30566. Object.defineProperty(PostProcess.prototype, "onActivate", {
  30567. set: function (callback) {
  30568. if (this._onActivateObserver) {
  30569. this.onActivateObservable.remove(this._onActivateObserver);
  30570. }
  30571. this._onActivateObserver = this.onActivateObservable.add(callback);
  30572. },
  30573. enumerable: true,
  30574. configurable: true
  30575. });
  30576. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  30577. set: function (callback) {
  30578. if (this._onSizeChangedObserver) {
  30579. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  30580. }
  30581. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  30582. },
  30583. enumerable: true,
  30584. configurable: true
  30585. });
  30586. Object.defineProperty(PostProcess.prototype, "onApply", {
  30587. set: function (callback) {
  30588. if (this._onApplyObserver) {
  30589. this.onApplyObservable.remove(this._onApplyObserver);
  30590. }
  30591. this._onApplyObserver = this.onApplyObservable.add(callback);
  30592. },
  30593. enumerable: true,
  30594. configurable: true
  30595. });
  30596. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  30597. set: function (callback) {
  30598. if (this._onBeforeRenderObserver) {
  30599. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  30600. }
  30601. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  30602. },
  30603. enumerable: true,
  30604. configurable: true
  30605. });
  30606. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  30607. set: function (callback) {
  30608. if (this._onAfterRenderObserver) {
  30609. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  30610. }
  30611. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  30612. },
  30613. enumerable: true,
  30614. configurable: true
  30615. });
  30616. PostProcess.prototype.updateEffect = function (defines) {
  30617. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  30618. };
  30619. PostProcess.prototype.isReusable = function () {
  30620. return this._reusable;
  30621. };
  30622. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  30623. PostProcess.prototype.markTextureDirty = function () {
  30624. this.width = -1;
  30625. };
  30626. PostProcess.prototype.activate = function (camera, sourceTexture) {
  30627. camera = camera || this._camera;
  30628. var scene = camera.getScene();
  30629. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  30630. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  30631. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  30632. var desiredWidth = this._options.width || requiredWidth;
  30633. var desiredHeight = this._options.height || requiredHeight;
  30634. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  30635. if (!this._options.width) {
  30636. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  30637. }
  30638. if (!this._options.height) {
  30639. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  30640. }
  30641. }
  30642. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  30643. if (this._textures.length > 0) {
  30644. for (var i = 0; i < this._textures.length; i++) {
  30645. this._engine._releaseTexture(this._textures.data[i]);
  30646. }
  30647. this._textures.reset();
  30648. }
  30649. this.width = desiredWidth;
  30650. this.height = desiredHeight;
  30651. var textureSize = { width: this.width, height: this.height };
  30652. var textureOptions = {
  30653. generateMipMaps: false,
  30654. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  30655. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  30656. samplingMode: this.renderTargetSamplingMode,
  30657. type: this._textureType
  30658. };
  30659. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  30660. if (this._reusable) {
  30661. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  30662. }
  30663. this.onSizeChangedObservable.notifyObservers(this);
  30664. }
  30665. if (this.enablePixelPerfectMode) {
  30666. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  30667. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  30668. }
  30669. else {
  30670. this._scaleRatio.copyFromFloats(1, 1);
  30671. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  30672. }
  30673. this.onActivateObservable.notifyObservers(camera);
  30674. // Clear
  30675. if (this.clearColor) {
  30676. this._engine.clear(this.clearColor, true, true, true);
  30677. }
  30678. else {
  30679. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  30680. }
  30681. if (this._reusable) {
  30682. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  30683. }
  30684. };
  30685. Object.defineProperty(PostProcess.prototype, "isSupported", {
  30686. get: function () {
  30687. return this._effect.isSupported;
  30688. },
  30689. enumerable: true,
  30690. configurable: true
  30691. });
  30692. PostProcess.prototype.apply = function () {
  30693. // Check
  30694. if (!this._effect.isReady())
  30695. return null;
  30696. // States
  30697. this._engine.enableEffect(this._effect);
  30698. this._engine.setState(false);
  30699. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  30700. this._engine.setDepthBuffer(false);
  30701. this._engine.setDepthWrite(false);
  30702. // Texture
  30703. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  30704. // Parameters
  30705. this._effect.setVector2("scale", this._scaleRatio);
  30706. this.onApplyObservable.notifyObservers(this._effect);
  30707. return this._effect;
  30708. };
  30709. PostProcess.prototype.dispose = function (camera) {
  30710. camera = camera || this._camera;
  30711. if (this._textures.length > 0) {
  30712. for (var i = 0; i < this._textures.length; i++) {
  30713. this._engine._releaseTexture(this._textures.data[i]);
  30714. }
  30715. this._textures.reset();
  30716. }
  30717. if (!camera) {
  30718. return;
  30719. }
  30720. camera.detachPostProcess(this);
  30721. var index = camera._postProcesses.indexOf(this);
  30722. if (index === 0 && camera._postProcesses.length > 0) {
  30723. this._camera._postProcesses[0].markTextureDirty();
  30724. }
  30725. this.onActivateObservable.clear();
  30726. this.onAfterRenderObservable.clear();
  30727. this.onApplyObservable.clear();
  30728. this.onBeforeRenderObservable.clear();
  30729. this.onSizeChangedObservable.clear();
  30730. };
  30731. return PostProcess;
  30732. }());
  30733. BABYLON.PostProcess = PostProcess;
  30734. })(BABYLON || (BABYLON = {}));
  30735. var BABYLON;
  30736. (function (BABYLON) {
  30737. var PostProcessManager = (function () {
  30738. function PostProcessManager(scene) {
  30739. this._vertexBuffers = {};
  30740. this._scene = scene;
  30741. }
  30742. PostProcessManager.prototype._prepareBuffers = function () {
  30743. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  30744. return;
  30745. }
  30746. // VBO
  30747. var vertices = [];
  30748. vertices.push(1, 1);
  30749. vertices.push(-1, 1);
  30750. vertices.push(-1, -1);
  30751. vertices.push(1, -1);
  30752. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  30753. // Indices
  30754. var indices = [];
  30755. indices.push(0);
  30756. indices.push(1);
  30757. indices.push(2);
  30758. indices.push(0);
  30759. indices.push(2);
  30760. indices.push(3);
  30761. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  30762. };
  30763. // Methods
  30764. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  30765. var postProcesses = this._scene.activeCamera._postProcesses;
  30766. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30767. return false;
  30768. }
  30769. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  30770. return true;
  30771. };
  30772. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  30773. var engine = this._scene.getEngine();
  30774. for (var index = 0; index < postProcesses.length; index++) {
  30775. if (index < postProcesses.length - 1) {
  30776. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30777. }
  30778. else {
  30779. if (targetTexture) {
  30780. engine.bindFramebuffer(targetTexture);
  30781. }
  30782. else {
  30783. engine.restoreDefaultFramebuffer();
  30784. }
  30785. }
  30786. var pp = postProcesses[index];
  30787. var effect = pp.apply();
  30788. if (effect) {
  30789. pp.onBeforeRenderObservable.notifyObservers(effect);
  30790. // VBOs
  30791. this._prepareBuffers();
  30792. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30793. // Draw order
  30794. engine.draw(true, 0, 6);
  30795. pp.onAfterRenderObservable.notifyObservers(effect);
  30796. }
  30797. }
  30798. // Restore depth buffer
  30799. engine.setDepthBuffer(true);
  30800. engine.setDepthWrite(true);
  30801. };
  30802. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  30803. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  30804. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30805. return;
  30806. }
  30807. var engine = this._scene.getEngine();
  30808. for (var index = 0, len = postProcesses.length; index < len; index++) {
  30809. if (index < len - 1) {
  30810. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30811. }
  30812. else {
  30813. if (targetTexture) {
  30814. engine.bindFramebuffer(targetTexture, faceIndex);
  30815. }
  30816. else {
  30817. engine.restoreDefaultFramebuffer();
  30818. }
  30819. }
  30820. if (doNotPresent) {
  30821. break;
  30822. }
  30823. var pp = postProcesses[index];
  30824. var effect = pp.apply();
  30825. if (effect) {
  30826. pp.onBeforeRenderObservable.notifyObservers(effect);
  30827. // VBOs
  30828. this._prepareBuffers();
  30829. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30830. // Draw order
  30831. engine.draw(true, 0, 6);
  30832. pp.onAfterRenderObservable.notifyObservers(effect);
  30833. }
  30834. }
  30835. // Restore depth buffer
  30836. engine.setDepthBuffer(true);
  30837. engine.setDepthWrite(true);
  30838. };
  30839. PostProcessManager.prototype.dispose = function () {
  30840. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  30841. if (buffer) {
  30842. buffer.dispose();
  30843. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  30844. }
  30845. if (this._indexBuffer) {
  30846. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  30847. this._indexBuffer = null;
  30848. }
  30849. };
  30850. return PostProcessManager;
  30851. }());
  30852. BABYLON.PostProcessManager = PostProcessManager;
  30853. })(BABYLON || (BABYLON = {}));
  30854. var BABYLON;
  30855. (function (BABYLON) {
  30856. var PassPostProcess = (function (_super) {
  30857. __extends(PassPostProcess, _super);
  30858. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  30859. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  30860. }
  30861. return PassPostProcess;
  30862. }(BABYLON.PostProcess));
  30863. BABYLON.PassPostProcess = PassPostProcess;
  30864. })(BABYLON || (BABYLON = {}));
  30865. var BABYLON;
  30866. (function (BABYLON) {
  30867. /**
  30868. * This is a holder class for the physics joint created by the physics plugin.
  30869. * It holds a set of functions to control the underlying joint.
  30870. */
  30871. var PhysicsJoint = (function () {
  30872. function PhysicsJoint(type, jointData) {
  30873. this.type = type;
  30874. this.jointData = jointData;
  30875. jointData.nativeParams = jointData.nativeParams || {};
  30876. }
  30877. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  30878. get: function () {
  30879. return this._physicsJoint;
  30880. },
  30881. set: function (newJoint) {
  30882. if (this._physicsJoint) {
  30883. }
  30884. this._physicsJoint = newJoint;
  30885. },
  30886. enumerable: true,
  30887. configurable: true
  30888. });
  30889. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  30890. set: function (physicsPlugin) {
  30891. this._physicsPlugin = physicsPlugin;
  30892. },
  30893. enumerable: true,
  30894. configurable: true
  30895. });
  30896. /**
  30897. * Execute a function that is physics-plugin specific.
  30898. * @param {Function} func the function that will be executed.
  30899. * It accepts two parameters: the physics world and the physics joint.
  30900. */
  30901. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  30902. func(this._physicsPlugin.world, this._physicsJoint);
  30903. };
  30904. //TODO check if the native joints are the same
  30905. //Joint Types
  30906. PhysicsJoint.DistanceJoint = 0;
  30907. PhysicsJoint.HingeJoint = 1;
  30908. PhysicsJoint.BallAndSocketJoint = 2;
  30909. PhysicsJoint.WheelJoint = 3;
  30910. PhysicsJoint.SliderJoint = 4;
  30911. //OIMO
  30912. PhysicsJoint.PrismaticJoint = 5;
  30913. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  30914. PhysicsJoint.UniversalJoint = 6;
  30915. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  30916. //Cannon
  30917. //Similar to a Ball-Joint. Different in params
  30918. PhysicsJoint.PointToPointJoint = 8;
  30919. //Cannon only at the moment
  30920. PhysicsJoint.SpringJoint = 9;
  30921. PhysicsJoint.LockJoint = 10;
  30922. return PhysicsJoint;
  30923. }());
  30924. BABYLON.PhysicsJoint = PhysicsJoint;
  30925. /**
  30926. * A class representing a physics distance joint.
  30927. */
  30928. var DistanceJoint = (function (_super) {
  30929. __extends(DistanceJoint, _super);
  30930. function DistanceJoint(jointData) {
  30931. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  30932. }
  30933. /**
  30934. * Update the predefined distance.
  30935. */
  30936. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  30937. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  30938. };
  30939. return DistanceJoint;
  30940. }(PhysicsJoint));
  30941. BABYLON.DistanceJoint = DistanceJoint;
  30942. var MotorEnabledJoint = (function (_super) {
  30943. __extends(MotorEnabledJoint, _super);
  30944. function MotorEnabledJoint(type, jointData) {
  30945. _super.call(this, type, jointData);
  30946. }
  30947. /**
  30948. * Set the motor values.
  30949. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30950. * @param {number} force the force to apply
  30951. * @param {number} maxForce max force for this motor.
  30952. */
  30953. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  30954. this._physicsPlugin.setMotor(this, force, maxForce);
  30955. };
  30956. /**
  30957. * Set the motor's limits.
  30958. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30959. */
  30960. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  30961. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  30962. };
  30963. return MotorEnabledJoint;
  30964. }(PhysicsJoint));
  30965. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  30966. /**
  30967. * This class represents a single hinge physics joint
  30968. */
  30969. var HingeJoint = (function (_super) {
  30970. __extends(HingeJoint, _super);
  30971. function HingeJoint(jointData) {
  30972. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  30973. }
  30974. /**
  30975. * Set the motor values.
  30976. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30977. * @param {number} force the force to apply
  30978. * @param {number} maxForce max force for this motor.
  30979. */
  30980. HingeJoint.prototype.setMotor = function (force, maxForce) {
  30981. this._physicsPlugin.setMotor(this, force, maxForce);
  30982. };
  30983. /**
  30984. * Set the motor's limits.
  30985. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30986. */
  30987. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  30988. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  30989. };
  30990. return HingeJoint;
  30991. }(MotorEnabledJoint));
  30992. BABYLON.HingeJoint = HingeJoint;
  30993. /**
  30994. * This class represents a dual hinge physics joint (same as wheel joint)
  30995. */
  30996. var Hinge2Joint = (function (_super) {
  30997. __extends(Hinge2Joint, _super);
  30998. function Hinge2Joint(jointData) {
  30999. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  31000. }
  31001. /**
  31002. * Set the motor values.
  31003. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31004. * @param {number} force the force to apply
  31005. * @param {number} maxForce max force for this motor.
  31006. * @param {motorIndex} the motor's index, 0 or 1.
  31007. */
  31008. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  31009. if (motorIndex === void 0) { motorIndex = 0; }
  31010. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  31011. };
  31012. /**
  31013. * Set the motor limits.
  31014. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31015. * @param {number} upperLimit the upper limit
  31016. * @param {number} lowerLimit lower limit
  31017. * @param {motorIndex} the motor's index, 0 or 1.
  31018. */
  31019. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  31020. if (motorIndex === void 0) { motorIndex = 0; }
  31021. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  31022. };
  31023. return Hinge2Joint;
  31024. }(MotorEnabledJoint));
  31025. BABYLON.Hinge2Joint = Hinge2Joint;
  31026. })(BABYLON || (BABYLON = {}));
  31027. var BABYLON;
  31028. (function (BABYLON) {
  31029. var PhysicsImpostor = (function () {
  31030. function PhysicsImpostor(object, type, _options, _scene) {
  31031. var _this = this;
  31032. if (_options === void 0) { _options = { mass: 0 }; }
  31033. this.object = object;
  31034. this.type = type;
  31035. this._options = _options;
  31036. this._scene = _scene;
  31037. this._bodyUpdateRequired = false;
  31038. this._onBeforePhysicsStepCallbacks = new Array();
  31039. this._onAfterPhysicsStepCallbacks = new Array();
  31040. this._onPhysicsCollideCallbacks = [];
  31041. this._deltaPosition = BABYLON.Vector3.Zero();
  31042. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  31043. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  31044. /**
  31045. * this function is executed by the physics engine.
  31046. */
  31047. this.beforeStep = function () {
  31048. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  31049. //conjugate deltaRotation
  31050. if (_this._deltaRotationConjugated) {
  31051. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  31052. }
  31053. else {
  31054. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  31055. }
  31056. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  31057. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  31058. func(_this);
  31059. });
  31060. };
  31061. /**
  31062. * this function is executed by the physics engine.
  31063. */
  31064. this.afterStep = function () {
  31065. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  31066. func(_this);
  31067. });
  31068. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  31069. _this.object.position.addInPlace(_this._deltaPosition);
  31070. if (_this._deltaRotation) {
  31071. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  31072. }
  31073. };
  31074. //event and body object due to cannon's event-based architecture.
  31075. this.onCollide = function (e) {
  31076. if (!_this._onPhysicsCollideCallbacks.length)
  31077. return;
  31078. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  31079. if (otherImpostor) {
  31080. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  31081. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  31082. }).forEach(function (obj) {
  31083. obj.callback(_this, otherImpostor);
  31084. });
  31085. }
  31086. };
  31087. //sanity check!
  31088. if (!this.object) {
  31089. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  31090. return;
  31091. }
  31092. //legacy support for old syntax.
  31093. if (!this._scene && object.getScene) {
  31094. this._scene = object.getScene();
  31095. }
  31096. this._physicsEngine = this._scene.getPhysicsEngine();
  31097. if (!this._physicsEngine) {
  31098. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  31099. }
  31100. else {
  31101. //set the object's quaternion, if not set
  31102. if (!this.object.rotationQuaternion) {
  31103. if (this.object.rotation) {
  31104. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  31105. }
  31106. else {
  31107. this.object.rotationQuaternion = new BABYLON.Quaternion();
  31108. }
  31109. }
  31110. //default options params
  31111. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  31112. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  31113. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  31114. this._joints = [];
  31115. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  31116. if (!this.object.parent) {
  31117. this._init();
  31118. }
  31119. }
  31120. }
  31121. /**
  31122. * This function will completly initialize this impostor.
  31123. * It will create a new body - but only if this mesh has no parent.
  31124. * If it has, this impostor will not be used other than to define the impostor
  31125. * of the child mesh.
  31126. */
  31127. PhysicsImpostor.prototype._init = function () {
  31128. this._physicsEngine.removeImpostor(this);
  31129. this.physicsBody = null;
  31130. this._parent = this._parent || this._getPhysicsParent();
  31131. if (!this.parent) {
  31132. this._physicsEngine.addImpostor(this);
  31133. }
  31134. };
  31135. PhysicsImpostor.prototype._getPhysicsParent = function () {
  31136. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  31137. var parentMesh = this.object.parent;
  31138. return parentMesh.physicsImpostor;
  31139. }
  31140. return;
  31141. };
  31142. /**
  31143. * Should a new body be generated.
  31144. */
  31145. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  31146. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  31147. };
  31148. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  31149. this.forceUpdate();
  31150. };
  31151. /**
  31152. * Force a regeneration of this or the parent's impostor's body.
  31153. * Use under cautious - This will remove all joints already implemented.
  31154. */
  31155. PhysicsImpostor.prototype.forceUpdate = function () {
  31156. this._init();
  31157. if (this.parent) {
  31158. this.parent.forceUpdate();
  31159. }
  31160. };
  31161. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  31162. /*public get mesh(): AbstractMesh {
  31163. return this._mesh;
  31164. }*/
  31165. /**
  31166. * Gets the body that holds this impostor. Either its own, or its parent.
  31167. */
  31168. get: function () {
  31169. return this._parent ? this._parent.physicsBody : this._physicsBody;
  31170. },
  31171. /**
  31172. * Set the physics body. Used mainly by the physics engine/plugin
  31173. */
  31174. set: function (physicsBody) {
  31175. if (this._physicsBody) {
  31176. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  31177. }
  31178. this._physicsBody = physicsBody;
  31179. this.resetUpdateFlags();
  31180. },
  31181. enumerable: true,
  31182. configurable: true
  31183. });
  31184. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  31185. get: function () {
  31186. return this._parent;
  31187. },
  31188. set: function (value) {
  31189. this._parent = value;
  31190. },
  31191. enumerable: true,
  31192. configurable: true
  31193. });
  31194. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  31195. this._bodyUpdateRequired = false;
  31196. };
  31197. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  31198. if (this.object.getBoundingInfo) {
  31199. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  31200. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  31201. }
  31202. else {
  31203. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  31204. }
  31205. };
  31206. PhysicsImpostor.prototype.getObjectCenter = function () {
  31207. if (this.object.getBoundingInfo) {
  31208. return this.object.getBoundingInfo().boundingBox.center;
  31209. }
  31210. else {
  31211. return this.object.position;
  31212. }
  31213. };
  31214. /**
  31215. * Get a specific parametes from the options parameter.
  31216. */
  31217. PhysicsImpostor.prototype.getParam = function (paramName) {
  31218. return this._options[paramName];
  31219. };
  31220. /**
  31221. * Sets a specific parameter in the options given to the physics plugin
  31222. */
  31223. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  31224. this._options[paramName] = value;
  31225. this._bodyUpdateRequired = true;
  31226. };
  31227. /**
  31228. * Specifically change the body's mass option. Won't recreate the physics body object
  31229. */
  31230. PhysicsImpostor.prototype.setMass = function (mass) {
  31231. if (this.getParam("mass") !== mass) {
  31232. this.setParam("mass", mass);
  31233. }
  31234. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  31235. };
  31236. PhysicsImpostor.prototype.getLinearVelocity = function () {
  31237. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  31238. };
  31239. /**
  31240. * Set the body's linear velocity.
  31241. */
  31242. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  31243. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  31244. };
  31245. PhysicsImpostor.prototype.getAngularVelocity = function () {
  31246. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  31247. };
  31248. /**
  31249. * Set the body's linear velocity.
  31250. */
  31251. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  31252. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  31253. };
  31254. /**
  31255. * Execute a function with the physics plugin native code.
  31256. * Provide a function the will have two variables - the world object and the physics body object.
  31257. */
  31258. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  31259. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  31260. };
  31261. /**
  31262. * Register a function that will be executed before the physics world is stepping forward.
  31263. */
  31264. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  31265. this._onBeforePhysicsStepCallbacks.push(func);
  31266. };
  31267. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  31268. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  31269. if (index > -1) {
  31270. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  31271. }
  31272. else {
  31273. BABYLON.Tools.Warn("Function to remove was not found");
  31274. }
  31275. };
  31276. /**
  31277. * Register a function that will be executed after the physics step
  31278. */
  31279. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  31280. this._onAfterPhysicsStepCallbacks.push(func);
  31281. };
  31282. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  31283. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  31284. if (index > -1) {
  31285. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  31286. }
  31287. else {
  31288. BABYLON.Tools.Warn("Function to remove was not found");
  31289. }
  31290. };
  31291. /**
  31292. * register a function that will be executed when this impostor collides against a different body.
  31293. */
  31294. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  31295. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  31296. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  31297. };
  31298. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  31299. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  31300. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  31301. if (index > -1) {
  31302. this._onPhysicsCollideCallbacks.splice(index, 1);
  31303. }
  31304. else {
  31305. BABYLON.Tools.Warn("Function to remove was not found");
  31306. }
  31307. };
  31308. /**
  31309. * Apply a force
  31310. */
  31311. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  31312. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  31313. };
  31314. /**
  31315. * Apply an impulse
  31316. */
  31317. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  31318. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  31319. };
  31320. /**
  31321. * A help function to create a joint.
  31322. */
  31323. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  31324. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  31325. this.addJoint(otherImpostor, joint);
  31326. };
  31327. /**
  31328. * Add a joint to this impostor with a different impostor.
  31329. */
  31330. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  31331. this._joints.push({
  31332. otherImpostor: otherImpostor,
  31333. joint: joint
  31334. });
  31335. this._physicsEngine.addJoint(this, otherImpostor, joint);
  31336. };
  31337. /**
  31338. * Will keep this body still, in a sleep mode.
  31339. */
  31340. PhysicsImpostor.prototype.sleep = function () {
  31341. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  31342. };
  31343. /**
  31344. * Wake the body up.
  31345. */
  31346. PhysicsImpostor.prototype.wakeUp = function () {
  31347. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  31348. };
  31349. PhysicsImpostor.prototype.clone = function (newObject) {
  31350. if (!newObject)
  31351. return null;
  31352. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  31353. };
  31354. PhysicsImpostor.prototype.dispose = function () {
  31355. var _this = this;
  31356. //no dispose if no physics engine is available.
  31357. if (!this._physicsEngine) {
  31358. return;
  31359. }
  31360. this._joints.forEach(function (j) {
  31361. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  31362. });
  31363. //dispose the physics body
  31364. this._physicsEngine.removeImpostor(this);
  31365. if (this.parent) {
  31366. this.parent.forceUpdate();
  31367. }
  31368. else {
  31369. }
  31370. };
  31371. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  31372. this._deltaPosition.copyFrom(position);
  31373. };
  31374. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  31375. if (!this._deltaRotation) {
  31376. this._deltaRotation = new BABYLON.Quaternion();
  31377. }
  31378. this._deltaRotation.copyFrom(rotation);
  31379. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  31380. };
  31381. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  31382. //Impostor types
  31383. PhysicsImpostor.NoImpostor = 0;
  31384. PhysicsImpostor.SphereImpostor = 1;
  31385. PhysicsImpostor.BoxImpostor = 2;
  31386. PhysicsImpostor.PlaneImpostor = 3;
  31387. PhysicsImpostor.MeshImpostor = 4;
  31388. PhysicsImpostor.CylinderImpostor = 7;
  31389. PhysicsImpostor.ParticleImpostor = 8;
  31390. PhysicsImpostor.HeightmapImpostor = 9;
  31391. return PhysicsImpostor;
  31392. }());
  31393. BABYLON.PhysicsImpostor = PhysicsImpostor;
  31394. })(BABYLON || (BABYLON = {}));
  31395. var BABYLON;
  31396. (function (BABYLON) {
  31397. var PhysicsEngine = (function () {
  31398. function PhysicsEngine(gravity, _physicsPlugin) {
  31399. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  31400. this._physicsPlugin = _physicsPlugin;
  31401. //new methods and parameters
  31402. this._impostors = [];
  31403. this._joints = [];
  31404. if (!this._physicsPlugin.isSupported()) {
  31405. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  31406. + "Please make sure it is included.");
  31407. }
  31408. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  31409. this.setGravity(gravity);
  31410. this.setTimeStep();
  31411. }
  31412. PhysicsEngine.prototype.setGravity = function (gravity) {
  31413. this.gravity = gravity;
  31414. this._physicsPlugin.setGravity(this.gravity);
  31415. };
  31416. /**
  31417. * Set the time step of the physics engine.
  31418. * default is 1/60.
  31419. * To slow it down, enter 1/600 for example.
  31420. * To speed it up, 1/30
  31421. * @param {number} newTimeStep the new timestep to apply to this world.
  31422. */
  31423. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  31424. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  31425. this._physicsPlugin.setTimeStep(newTimeStep);
  31426. };
  31427. PhysicsEngine.prototype.dispose = function () {
  31428. this._impostors.forEach(function (impostor) {
  31429. impostor.dispose();
  31430. });
  31431. this._physicsPlugin.dispose();
  31432. };
  31433. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  31434. return this._physicsPlugin.name;
  31435. };
  31436. /**
  31437. * Adding a new impostor for the impostor tracking.
  31438. * This will be done by the impostor itself.
  31439. * @param {PhysicsImpostor} impostor the impostor to add
  31440. */
  31441. PhysicsEngine.prototype.addImpostor = function (impostor) {
  31442. impostor.uniqueId = this._impostors.push(impostor);
  31443. //if no parent, generate the body
  31444. if (!impostor.parent) {
  31445. this._physicsPlugin.generatePhysicsBody(impostor);
  31446. }
  31447. };
  31448. /**
  31449. * Remove an impostor from the engine.
  31450. * This impostor and its mesh will not longer be updated by the physics engine.
  31451. * @param {PhysicsImpostor} impostor the impostor to remove
  31452. */
  31453. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  31454. var index = this._impostors.indexOf(impostor);
  31455. if (index > -1) {
  31456. var removed = this._impostors.splice(index, 1);
  31457. //Is it needed?
  31458. if (removed.length) {
  31459. //this will also remove it from the world.
  31460. removed[0].physicsBody = null;
  31461. }
  31462. }
  31463. };
  31464. /**
  31465. * Add a joint to the physics engine
  31466. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  31467. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  31468. * @param {PhysicsJoint} the joint that will connect both impostors.
  31469. */
  31470. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  31471. var impostorJoint = {
  31472. mainImpostor: mainImpostor,
  31473. connectedImpostor: connectedImpostor,
  31474. joint: joint
  31475. };
  31476. joint.physicsPlugin = this._physicsPlugin;
  31477. this._joints.push(impostorJoint);
  31478. this._physicsPlugin.generateJoint(impostorJoint);
  31479. };
  31480. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  31481. var matchingJoints = this._joints.filter(function (impostorJoint) {
  31482. return (impostorJoint.connectedImpostor === connectedImpostor
  31483. && impostorJoint.joint === joint
  31484. && impostorJoint.mainImpostor === mainImpostor);
  31485. });
  31486. if (matchingJoints.length) {
  31487. this._physicsPlugin.removeJoint(matchingJoints[0]);
  31488. }
  31489. };
  31490. /**
  31491. * Called by the scene. no need to call it.
  31492. */
  31493. PhysicsEngine.prototype._step = function (delta) {
  31494. var _this = this;
  31495. //check if any mesh has no body / requires an update
  31496. this._impostors.forEach(function (impostor) {
  31497. if (impostor.isBodyInitRequired()) {
  31498. _this._physicsPlugin.generatePhysicsBody(impostor);
  31499. }
  31500. });
  31501. if (delta > 0.1) {
  31502. delta = 0.1;
  31503. }
  31504. else if (delta <= 0) {
  31505. delta = 1.0 / 60.0;
  31506. }
  31507. this._physicsPlugin.executeStep(delta, this._impostors);
  31508. };
  31509. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  31510. return this._physicsPlugin;
  31511. };
  31512. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  31513. for (var i = 0; i < this._impostors.length; ++i) {
  31514. if (this._impostors[i].object === object) {
  31515. return this._impostors[i];
  31516. }
  31517. }
  31518. };
  31519. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  31520. for (var i = 0; i < this._impostors.length; ++i) {
  31521. if (this._impostors[i].physicsBody === body) {
  31522. return this._impostors[i];
  31523. }
  31524. }
  31525. };
  31526. // Statics, Legacy support.
  31527. /**
  31528. * @Deprecated
  31529. *
  31530. */
  31531. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  31532. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  31533. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  31534. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  31535. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  31536. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  31537. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  31538. PhysicsEngine.CapsuleImpostor = -1;
  31539. PhysicsEngine.ConeImpostor = -1;
  31540. PhysicsEngine.ConvexHullImpostor = -1;
  31541. PhysicsEngine.Epsilon = 0.001;
  31542. return PhysicsEngine;
  31543. }());
  31544. BABYLON.PhysicsEngine = PhysicsEngine;
  31545. })(BABYLON || (BABYLON = {}));
  31546. var BABYLON;
  31547. (function (BABYLON) {
  31548. var VertexData = (function () {
  31549. function VertexData() {
  31550. }
  31551. VertexData.prototype.set = function (data, kind) {
  31552. switch (kind) {
  31553. case BABYLON.VertexBuffer.PositionKind:
  31554. this.positions = data;
  31555. break;
  31556. case BABYLON.VertexBuffer.NormalKind:
  31557. this.normals = data;
  31558. break;
  31559. case BABYLON.VertexBuffer.UVKind:
  31560. this.uvs = data;
  31561. break;
  31562. case BABYLON.VertexBuffer.UV2Kind:
  31563. this.uvs2 = data;
  31564. break;
  31565. case BABYLON.VertexBuffer.UV3Kind:
  31566. this.uvs3 = data;
  31567. break;
  31568. case BABYLON.VertexBuffer.UV4Kind:
  31569. this.uvs4 = data;
  31570. break;
  31571. case BABYLON.VertexBuffer.UV5Kind:
  31572. this.uvs5 = data;
  31573. break;
  31574. case BABYLON.VertexBuffer.UV6Kind:
  31575. this.uvs6 = data;
  31576. break;
  31577. case BABYLON.VertexBuffer.ColorKind:
  31578. this.colors = data;
  31579. break;
  31580. case BABYLON.VertexBuffer.MatricesIndicesKind:
  31581. this.matricesIndices = data;
  31582. break;
  31583. case BABYLON.VertexBuffer.MatricesWeightsKind:
  31584. this.matricesWeights = data;
  31585. break;
  31586. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  31587. this.matricesIndicesExtra = data;
  31588. break;
  31589. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  31590. this.matricesWeightsExtra = data;
  31591. break;
  31592. }
  31593. };
  31594. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  31595. this._applyTo(mesh, updatable);
  31596. };
  31597. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  31598. this._applyTo(geometry, updatable);
  31599. };
  31600. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  31601. this._update(mesh);
  31602. };
  31603. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  31604. this._update(geometry);
  31605. };
  31606. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  31607. if (this.positions) {
  31608. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  31609. }
  31610. if (this.normals) {
  31611. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  31612. }
  31613. if (this.uvs) {
  31614. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  31615. }
  31616. if (this.uvs2) {
  31617. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  31618. }
  31619. if (this.uvs3) {
  31620. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  31621. }
  31622. if (this.uvs4) {
  31623. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  31624. }
  31625. if (this.uvs5) {
  31626. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  31627. }
  31628. if (this.uvs6) {
  31629. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  31630. }
  31631. if (this.colors) {
  31632. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  31633. }
  31634. if (this.matricesIndices) {
  31635. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  31636. }
  31637. if (this.matricesWeights) {
  31638. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  31639. }
  31640. if (this.matricesIndicesExtra) {
  31641. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  31642. }
  31643. if (this.matricesWeightsExtra) {
  31644. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  31645. }
  31646. if (this.indices) {
  31647. meshOrGeometry.setIndices(this.indices);
  31648. }
  31649. };
  31650. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  31651. if (this.positions) {
  31652. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  31653. }
  31654. if (this.normals) {
  31655. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  31656. }
  31657. if (this.uvs) {
  31658. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  31659. }
  31660. if (this.uvs2) {
  31661. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  31662. }
  31663. if (this.uvs3) {
  31664. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  31665. }
  31666. if (this.uvs4) {
  31667. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  31668. }
  31669. if (this.uvs5) {
  31670. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  31671. }
  31672. if (this.uvs6) {
  31673. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  31674. }
  31675. if (this.colors) {
  31676. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  31677. }
  31678. if (this.matricesIndices) {
  31679. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  31680. }
  31681. if (this.matricesWeights) {
  31682. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  31683. }
  31684. if (this.matricesIndicesExtra) {
  31685. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  31686. }
  31687. if (this.matricesWeightsExtra) {
  31688. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  31689. }
  31690. if (this.indices) {
  31691. meshOrGeometry.setIndices(this.indices);
  31692. }
  31693. };
  31694. VertexData.prototype.transform = function (matrix) {
  31695. var transformed = BABYLON.Vector3.Zero();
  31696. var index;
  31697. if (this.positions) {
  31698. var position = BABYLON.Vector3.Zero();
  31699. for (index = 0; index < this.positions.length; index += 3) {
  31700. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  31701. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  31702. this.positions[index] = transformed.x;
  31703. this.positions[index + 1] = transformed.y;
  31704. this.positions[index + 2] = transformed.z;
  31705. }
  31706. }
  31707. if (this.normals) {
  31708. var normal = BABYLON.Vector3.Zero();
  31709. for (index = 0; index < this.normals.length; index += 3) {
  31710. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  31711. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  31712. this.normals[index] = transformed.x;
  31713. this.normals[index + 1] = transformed.y;
  31714. this.normals[index + 2] = transformed.z;
  31715. }
  31716. }
  31717. };
  31718. VertexData.prototype.merge = function (other) {
  31719. if (other.indices) {
  31720. if (!this.indices) {
  31721. this.indices = [];
  31722. }
  31723. var offset = this.positions ? this.positions.length / 3 : 0;
  31724. for (var index = 0; index < other.indices.length; index++) {
  31725. //TODO check type - if Int32Array!
  31726. this.indices.push(other.indices[index] + offset);
  31727. }
  31728. }
  31729. this.positions = this._mergeElement(this.positions, other.positions);
  31730. this.normals = this._mergeElement(this.normals, other.normals);
  31731. this.uvs = this._mergeElement(this.uvs, other.uvs);
  31732. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  31733. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  31734. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  31735. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  31736. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  31737. this.colors = this._mergeElement(this.colors, other.colors);
  31738. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  31739. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  31740. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  31741. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  31742. };
  31743. VertexData.prototype._mergeElement = function (source, other) {
  31744. if (!other)
  31745. return source;
  31746. if (!source)
  31747. return other;
  31748. var len = other.length + source.length;
  31749. var isSrcTypedArray = source instanceof Float32Array;
  31750. var isOthTypedArray = other instanceof Float32Array;
  31751. // use non-loop method when the source is Float32Array
  31752. if (isSrcTypedArray) {
  31753. var ret32 = new Float32Array(len);
  31754. ret32.set(source);
  31755. ret32.set(other, source.length);
  31756. return ret32;
  31757. }
  31758. else if (!isOthTypedArray) {
  31759. return source.concat(other);
  31760. }
  31761. else {
  31762. var ret = source.slice(0); // copy source to a separate array
  31763. for (var i = 0, len = other.length; i < len; i++) {
  31764. ret.push(other[i]);
  31765. }
  31766. return ret;
  31767. }
  31768. };
  31769. VertexData.prototype.serialize = function () {
  31770. var serializationObject = this.serialize();
  31771. if (this.positions) {
  31772. serializationObject.positions = this.positions;
  31773. }
  31774. if (this.normals) {
  31775. serializationObject.normals = this.normals;
  31776. }
  31777. if (this.uvs) {
  31778. serializationObject.uvs = this.uvs;
  31779. }
  31780. if (this.uvs2) {
  31781. serializationObject.uvs2 = this.uvs2;
  31782. }
  31783. if (this.uvs3) {
  31784. serializationObject.uvs3 = this.uvs3;
  31785. }
  31786. if (this.uvs4) {
  31787. serializationObject.uvs4 = this.uvs4;
  31788. }
  31789. if (this.uvs5) {
  31790. serializationObject.uvs5 = this.uvs5;
  31791. }
  31792. if (this.uvs6) {
  31793. serializationObject.uvs6 = this.uvs6;
  31794. }
  31795. if (this.colors) {
  31796. serializationObject.colors = this.colors;
  31797. }
  31798. if (this.matricesIndices) {
  31799. serializationObject.matricesIndices = this.matricesIndices;
  31800. serializationObject.matricesIndices._isExpanded = true;
  31801. }
  31802. if (this.matricesWeights) {
  31803. serializationObject.matricesWeights = this.matricesWeights;
  31804. }
  31805. if (this.matricesIndicesExtra) {
  31806. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  31807. serializationObject.matricesIndicesExtra._isExpanded = true;
  31808. }
  31809. if (this.matricesWeightsExtra) {
  31810. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  31811. }
  31812. serializationObject.indices = this.indices;
  31813. return serializationObject;
  31814. };
  31815. // Statics
  31816. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  31817. return VertexData._ExtractFrom(mesh, copyWhenShared);
  31818. };
  31819. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  31820. return VertexData._ExtractFrom(geometry, copyWhenShared);
  31821. };
  31822. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  31823. var result = new VertexData();
  31824. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31825. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  31826. }
  31827. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31828. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  31829. }
  31830. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31831. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  31832. }
  31833. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31834. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  31835. }
  31836. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31837. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  31838. }
  31839. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31840. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  31841. }
  31842. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31843. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  31844. }
  31845. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31846. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  31847. }
  31848. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31849. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  31850. }
  31851. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31852. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  31853. }
  31854. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31855. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  31856. }
  31857. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  31858. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  31859. }
  31860. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  31861. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  31862. }
  31863. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  31864. return result;
  31865. };
  31866. VertexData.CreateRibbon = function (options) {
  31867. var pathArray = options.pathArray;
  31868. var closeArray = options.closeArray || false;
  31869. var closePath = options.closePath || false;
  31870. var invertUV = options.invertUV || false;
  31871. var defaultOffset = Math.floor(pathArray[0].length / 2);
  31872. var offset = options.offset || defaultOffset;
  31873. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  31874. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31875. var positions = [];
  31876. var indices = [];
  31877. var normals = [];
  31878. var uvs = [];
  31879. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  31880. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  31881. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  31882. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  31883. var minlg; // minimal length among all paths from pathArray
  31884. var lg = []; // array of path lengths : nb of vertex per path
  31885. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  31886. var p; // path iterator
  31887. var i; // point iterator
  31888. var j; // point iterator
  31889. // if single path in pathArray
  31890. if (pathArray.length < 2) {
  31891. var ar1 = [];
  31892. var ar2 = [];
  31893. for (i = 0; i < pathArray[0].length - offset; i++) {
  31894. ar1.push(pathArray[0][i]);
  31895. ar2.push(pathArray[0][i + offset]);
  31896. }
  31897. pathArray = [ar1, ar2];
  31898. }
  31899. // positions and horizontal distances (u)
  31900. var idc = 0;
  31901. var closePathCorr = (closePath) ? 1 : 0;
  31902. var path;
  31903. var l;
  31904. minlg = pathArray[0].length;
  31905. var vectlg;
  31906. var dist;
  31907. for (p = 0; p < pathArray.length; p++) {
  31908. uTotalDistance[p] = 0;
  31909. us[p] = [0];
  31910. path = pathArray[p];
  31911. l = path.length;
  31912. minlg = (minlg < l) ? minlg : l;
  31913. j = 0;
  31914. while (j < l) {
  31915. positions.push(path[j].x, path[j].y, path[j].z);
  31916. if (j > 0) {
  31917. vectlg = path[j].subtract(path[j - 1]).length();
  31918. dist = vectlg + uTotalDistance[p];
  31919. us[p].push(dist);
  31920. uTotalDistance[p] = dist;
  31921. }
  31922. j++;
  31923. }
  31924. if (closePath) {
  31925. j--;
  31926. positions.push(path[0].x, path[0].y, path[0].z);
  31927. vectlg = path[j].subtract(path[0]).length();
  31928. dist = vectlg + uTotalDistance[p];
  31929. us[p].push(dist);
  31930. uTotalDistance[p] = dist;
  31931. }
  31932. lg[p] = l + closePathCorr;
  31933. idx[p] = idc;
  31934. idc += (l + closePathCorr);
  31935. }
  31936. // vertical distances (v)
  31937. var path1;
  31938. var path2;
  31939. var vertex1;
  31940. var vertex2;
  31941. for (i = 0; i < minlg + closePathCorr; i++) {
  31942. vTotalDistance[i] = 0;
  31943. vs[i] = [0];
  31944. for (p = 0; p < pathArray.length - 1; p++) {
  31945. path1 = pathArray[p];
  31946. path2 = pathArray[p + 1];
  31947. if (i === minlg) {
  31948. vertex1 = path1[0];
  31949. vertex2 = path2[0];
  31950. }
  31951. else {
  31952. vertex1 = path1[i];
  31953. vertex2 = path2[i];
  31954. }
  31955. vectlg = vertex2.subtract(vertex1).length();
  31956. dist = vectlg + vTotalDistance[i];
  31957. vs[i].push(dist);
  31958. vTotalDistance[i] = dist;
  31959. }
  31960. if (closeArray) {
  31961. path1 = pathArray[p];
  31962. path2 = pathArray[0];
  31963. if (i === minlg) {
  31964. vertex2 = path2[0];
  31965. }
  31966. vectlg = vertex2.subtract(vertex1).length();
  31967. dist = vectlg + vTotalDistance[i];
  31968. vTotalDistance[i] = dist;
  31969. }
  31970. }
  31971. // uvs
  31972. var u;
  31973. var v;
  31974. for (p = 0; p < pathArray.length; p++) {
  31975. for (i = 0; i < minlg + closePathCorr; i++) {
  31976. u = us[p][i] / uTotalDistance[p];
  31977. v = vs[i][p] / vTotalDistance[i];
  31978. if (invertUV) {
  31979. uvs.push(v, u);
  31980. }
  31981. else {
  31982. uvs.push(u, v);
  31983. }
  31984. }
  31985. }
  31986. // indices
  31987. p = 0; // path index
  31988. var pi = 0; // positions array index
  31989. var l1 = lg[p] - 1; // path1 length
  31990. var l2 = lg[p + 1] - 1; // path2 length
  31991. var min = (l1 < l2) ? l1 : l2; // current path stop index
  31992. var shft = idx[1] - idx[0]; // shift
  31993. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  31994. while (pi <= min && p < path1nb) {
  31995. // 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
  31996. indices.push(pi, pi + shft, pi + 1);
  31997. indices.push(pi + shft + 1, pi + 1, pi + shft);
  31998. pi += 1;
  31999. if (pi === min) {
  32000. p++;
  32001. if (p === lg.length - 1) {
  32002. shft = idx[0] - idx[p];
  32003. l1 = lg[p] - 1;
  32004. l2 = lg[0] - 1;
  32005. }
  32006. else {
  32007. shft = idx[p + 1] - idx[p];
  32008. l1 = lg[p] - 1;
  32009. l2 = lg[p + 1] - 1;
  32010. }
  32011. pi = idx[p];
  32012. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32013. }
  32014. }
  32015. // normals
  32016. VertexData.ComputeNormals(positions, indices, normals);
  32017. if (closePath) {
  32018. var indexFirst = 0;
  32019. var indexLast = 0;
  32020. for (p = 0; p < pathArray.length; p++) {
  32021. indexFirst = idx[p] * 3;
  32022. if (p + 1 < pathArray.length) {
  32023. indexLast = (idx[p + 1] - 1) * 3;
  32024. }
  32025. else {
  32026. indexLast = normals.length - 3;
  32027. }
  32028. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32029. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32030. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32031. normals[indexLast] = normals[indexFirst];
  32032. normals[indexLast + 1] = normals[indexFirst + 1];
  32033. normals[indexLast + 2] = normals[indexFirst + 2];
  32034. }
  32035. }
  32036. // sides
  32037. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32038. // Result
  32039. var vertexData = new VertexData();
  32040. vertexData.indices = indices;
  32041. vertexData.positions = positions;
  32042. vertexData.normals = normals;
  32043. vertexData.uvs = uvs;
  32044. if (closePath) {
  32045. vertexData._idx = idx;
  32046. }
  32047. return vertexData;
  32048. };
  32049. VertexData.CreateBox = function (options) {
  32050. var normalsSource = [
  32051. new BABYLON.Vector3(0, 0, 1),
  32052. new BABYLON.Vector3(0, 0, -1),
  32053. new BABYLON.Vector3(1, 0, 0),
  32054. new BABYLON.Vector3(-1, 0, 0),
  32055. new BABYLON.Vector3(0, 1, 0),
  32056. new BABYLON.Vector3(0, -1, 0)
  32057. ];
  32058. var indices = [];
  32059. var positions = [];
  32060. var normals = [];
  32061. var uvs = [];
  32062. var width = options.width || options.size || 1;
  32063. var height = options.height || options.size || 1;
  32064. var depth = options.depth || options.size || 1;
  32065. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32066. var faceUV = options.faceUV || new Array(6);
  32067. var faceColors = options.faceColors;
  32068. var colors = [];
  32069. // default face colors and UV if undefined
  32070. for (var f = 0; f < 6; f++) {
  32071. if (faceUV[f] === undefined) {
  32072. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32073. }
  32074. if (faceColors && faceColors[f] === undefined) {
  32075. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32076. }
  32077. }
  32078. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32079. // Create each face in turn.
  32080. for (var index = 0; index < normalsSource.length; index++) {
  32081. var normal = normalsSource[index];
  32082. // Get two vectors perpendicular to the face normal and to each other.
  32083. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32084. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32085. // Six indices (two triangles) per face.
  32086. var verticesLength = positions.length / 3;
  32087. indices.push(verticesLength);
  32088. indices.push(verticesLength + 1);
  32089. indices.push(verticesLength + 2);
  32090. indices.push(verticesLength);
  32091. indices.push(verticesLength + 2);
  32092. indices.push(verticesLength + 3);
  32093. // Four vertices per face.
  32094. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32095. positions.push(vertex.x, vertex.y, vertex.z);
  32096. normals.push(normal.x, normal.y, normal.z);
  32097. uvs.push(faceUV[index].z, faceUV[index].w);
  32098. if (faceColors) {
  32099. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32100. }
  32101. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32102. positions.push(vertex.x, vertex.y, vertex.z);
  32103. normals.push(normal.x, normal.y, normal.z);
  32104. uvs.push(faceUV[index].x, faceUV[index].w);
  32105. if (faceColors) {
  32106. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32107. }
  32108. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32109. positions.push(vertex.x, vertex.y, vertex.z);
  32110. normals.push(normal.x, normal.y, normal.z);
  32111. uvs.push(faceUV[index].x, faceUV[index].y);
  32112. if (faceColors) {
  32113. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32114. }
  32115. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32116. positions.push(vertex.x, vertex.y, vertex.z);
  32117. normals.push(normal.x, normal.y, normal.z);
  32118. uvs.push(faceUV[index].z, faceUV[index].y);
  32119. if (faceColors) {
  32120. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32121. }
  32122. }
  32123. // sides
  32124. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32125. // Result
  32126. var vertexData = new VertexData();
  32127. vertexData.indices = indices;
  32128. vertexData.positions = positions;
  32129. vertexData.normals = normals;
  32130. vertexData.uvs = uvs;
  32131. if (faceColors) {
  32132. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32133. vertexData.colors = totalColors;
  32134. }
  32135. return vertexData;
  32136. };
  32137. VertexData.CreateSphere = function (options) {
  32138. var segments = options.segments || 32;
  32139. var diameterX = options.diameterX || options.diameter || 1;
  32140. var diameterY = options.diameterY || options.diameter || 1;
  32141. var diameterZ = options.diameterZ || options.diameter || 1;
  32142. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32143. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  32144. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32145. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  32146. var totalZRotationSteps = 2 + segments;
  32147. var totalYRotationSteps = 2 * totalZRotationSteps;
  32148. var indices = [];
  32149. var positions = [];
  32150. var normals = [];
  32151. var uvs = [];
  32152. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  32153. var normalizedZ = zRotationStep / totalZRotationSteps;
  32154. var angleZ = normalizedZ * Math.PI * slice;
  32155. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  32156. var normalizedY = yRotationStep / totalYRotationSteps;
  32157. var angleY = normalizedY * Math.PI * 2 * arc;
  32158. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  32159. var rotationY = BABYLON.Matrix.RotationY(angleY);
  32160. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  32161. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  32162. var vertex = complete.multiply(radius);
  32163. var normal = complete.divide(radius).normalize();
  32164. positions.push(vertex.x, vertex.y, vertex.z);
  32165. normals.push(normal.x, normal.y, normal.z);
  32166. uvs.push(normalizedY, normalizedZ);
  32167. }
  32168. if (zRotationStep > 0) {
  32169. var verticesCount = positions.length / 3;
  32170. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  32171. indices.push((firstIndex));
  32172. indices.push((firstIndex + 1));
  32173. indices.push(firstIndex + totalYRotationSteps + 1);
  32174. indices.push((firstIndex + totalYRotationSteps + 1));
  32175. indices.push((firstIndex + 1));
  32176. indices.push((firstIndex + totalYRotationSteps + 2));
  32177. }
  32178. }
  32179. }
  32180. // Sides
  32181. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32182. // Result
  32183. var vertexData = new VertexData();
  32184. vertexData.indices = indices;
  32185. vertexData.positions = positions;
  32186. vertexData.normals = normals;
  32187. vertexData.uvs = uvs;
  32188. return vertexData;
  32189. };
  32190. // Cylinder and cone
  32191. VertexData.CreateCylinder = function (options) {
  32192. var height = options.height || 2;
  32193. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  32194. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  32195. var tessellation = options.tessellation || 24;
  32196. var subdivisions = options.subdivisions || 1;
  32197. var hasRings = options.hasRings;
  32198. var enclose = options.enclose;
  32199. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32200. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32201. var faceUV = options.faceUV || new Array(3);
  32202. var faceColors = options.faceColors;
  32203. // default face colors and UV if undefined
  32204. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  32205. var ringNb = (hasRings) ? subdivisions : 1;
  32206. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  32207. var f;
  32208. for (f = 0; f < surfaceNb; f++) {
  32209. if (faceColors && faceColors[f] === undefined) {
  32210. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32211. }
  32212. }
  32213. for (f = 0; f < surfaceNb; f++) {
  32214. if (faceUV && faceUV[f] === undefined) {
  32215. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32216. }
  32217. }
  32218. var indices = [];
  32219. var positions = [];
  32220. var normals = [];
  32221. var uvs = [];
  32222. var colors = [];
  32223. var angle_step = Math.PI * 2 * arc / tessellation;
  32224. var angle;
  32225. var h;
  32226. var radius;
  32227. var tan = (diameterBottom - diameterTop) / 2 / height;
  32228. var ringVertex = BABYLON.Vector3.Zero();
  32229. var ringNormal = BABYLON.Vector3.Zero();
  32230. var ringFirstVertex = BABYLON.Vector3.Zero();
  32231. var ringFirstNormal = BABYLON.Vector3.Zero();
  32232. var quadNormal = BABYLON.Vector3.Zero();
  32233. var Y = BABYLON.Axis.Y;
  32234. // positions, normals, uvs
  32235. var i;
  32236. var j;
  32237. var r;
  32238. var ringIdx = 1;
  32239. var s = 1; // surface index
  32240. var cs = 0;
  32241. var v = 0;
  32242. for (i = 0; i <= subdivisions; i++) {
  32243. h = i / subdivisions;
  32244. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  32245. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  32246. for (r = 0; r < ringIdx; r++) {
  32247. if (hasRings) {
  32248. s += r;
  32249. }
  32250. if (enclose) {
  32251. s += 2 * r;
  32252. }
  32253. for (j = 0; j <= tessellation; j++) {
  32254. angle = j * angle_step;
  32255. // position
  32256. ringVertex.x = Math.cos(-angle) * radius;
  32257. ringVertex.y = -height / 2 + h * height;
  32258. ringVertex.z = Math.sin(-angle) * radius;
  32259. // normal
  32260. if (diameterTop === 0 && i === subdivisions) {
  32261. // if no top cap, reuse former normals
  32262. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  32263. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  32264. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  32265. }
  32266. else {
  32267. ringNormal.x = ringVertex.x;
  32268. ringNormal.z = ringVertex.z;
  32269. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  32270. ringNormal.normalize();
  32271. }
  32272. // keep first ring vertex values for enclose
  32273. if (j === 0) {
  32274. ringFirstVertex.copyFrom(ringVertex);
  32275. ringFirstNormal.copyFrom(ringNormal);
  32276. }
  32277. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32278. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  32279. if (hasRings) {
  32280. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  32281. }
  32282. else {
  32283. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  32284. }
  32285. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  32286. if (faceColors) {
  32287. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  32288. }
  32289. }
  32290. // if enclose, add four vertices and their dedicated normals
  32291. if (arc !== 1 && enclose) {
  32292. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32293. positions.push(0, ringVertex.y, 0);
  32294. positions.push(0, ringVertex.y, 0);
  32295. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  32296. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  32297. quadNormal.normalize();
  32298. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32299. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  32300. quadNormal.normalize();
  32301. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32302. if (hasRings) {
  32303. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  32304. }
  32305. else {
  32306. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  32307. }
  32308. uvs.push(faceUV[s + 1].x, v);
  32309. uvs.push(faceUV[s + 1].z, v);
  32310. if (hasRings) {
  32311. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  32312. }
  32313. else {
  32314. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  32315. }
  32316. uvs.push(faceUV[s + 2].x, v);
  32317. uvs.push(faceUV[s + 2].z, v);
  32318. if (faceColors) {
  32319. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32320. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32321. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32322. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32323. }
  32324. }
  32325. if (cs !== s) {
  32326. cs = s;
  32327. }
  32328. }
  32329. }
  32330. // indices
  32331. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  32332. var s;
  32333. i = 0;
  32334. for (s = 0; s < subdivisions; s++) {
  32335. for (j = 0; j < tessellation; j++) {
  32336. var i0 = i * (e + 1) + j;
  32337. var i1 = (i + 1) * (e + 1) + j;
  32338. var i2 = i * (e + 1) + (j + 1);
  32339. var i3 = (i + 1) * (e + 1) + (j + 1);
  32340. indices.push(i0, i1, i2);
  32341. indices.push(i3, i2, i1);
  32342. }
  32343. if (arc !== 1 && enclose) {
  32344. indices.push(i0 + 2, i1 + 2, i2 + 2);
  32345. indices.push(i3 + 2, i2 + 2, i1 + 2);
  32346. indices.push(i0 + 4, i1 + 4, i2 + 4);
  32347. indices.push(i3 + 4, i2 + 4, i1 + 4);
  32348. }
  32349. i = (hasRings) ? (i + 2) : (i + 1);
  32350. }
  32351. // Caps
  32352. var createCylinderCap = function (isTop) {
  32353. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  32354. if (radius === 0) {
  32355. return;
  32356. }
  32357. // Cap positions, normals & uvs
  32358. var angle;
  32359. var circleVector;
  32360. var i;
  32361. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  32362. var c;
  32363. if (faceColors) {
  32364. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  32365. }
  32366. // cap center
  32367. var vbase = positions.length / 3;
  32368. var offset = isTop ? height / 2 : -height / 2;
  32369. var center = new BABYLON.Vector3(0, offset, 0);
  32370. positions.push(center.x, center.y, center.z);
  32371. normals.push(0, isTop ? 1 : -1, 0);
  32372. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  32373. if (faceColors) {
  32374. colors.push(c.r, c.g, c.b, c.a);
  32375. }
  32376. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  32377. for (i = 0; i <= tessellation; i++) {
  32378. angle = Math.PI * 2 * i * arc / tessellation;
  32379. var cos = Math.cos(-angle);
  32380. var sin = Math.sin(-angle);
  32381. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  32382. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  32383. positions.push(circleVector.x, circleVector.y, circleVector.z);
  32384. normals.push(0, isTop ? 1 : -1, 0);
  32385. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  32386. if (faceColors) {
  32387. colors.push(c.r, c.g, c.b, c.a);
  32388. }
  32389. }
  32390. // Cap indices
  32391. for (i = 0; i < tessellation; i++) {
  32392. if (!isTop) {
  32393. indices.push(vbase);
  32394. indices.push(vbase + (i + 1));
  32395. indices.push(vbase + (i + 2));
  32396. }
  32397. else {
  32398. indices.push(vbase);
  32399. indices.push(vbase + (i + 2));
  32400. indices.push(vbase + (i + 1));
  32401. }
  32402. }
  32403. };
  32404. // add caps to geometry
  32405. createCylinderCap(false);
  32406. createCylinderCap(true);
  32407. // Sides
  32408. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32409. var vertexData = new VertexData();
  32410. vertexData.indices = indices;
  32411. vertexData.positions = positions;
  32412. vertexData.normals = normals;
  32413. vertexData.uvs = uvs;
  32414. if (faceColors) {
  32415. vertexData.colors = colors;
  32416. }
  32417. return vertexData;
  32418. };
  32419. VertexData.CreateTorus = function (options) {
  32420. var indices = [];
  32421. var positions = [];
  32422. var normals = [];
  32423. var uvs = [];
  32424. var diameter = options.diameter || 1;
  32425. var thickness = options.thickness || 0.5;
  32426. var tessellation = options.tessellation || 16;
  32427. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32428. var stride = tessellation + 1;
  32429. for (var i = 0; i <= tessellation; i++) {
  32430. var u = i / tessellation;
  32431. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  32432. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  32433. for (var j = 0; j <= tessellation; j++) {
  32434. var v = 1 - j / tessellation;
  32435. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  32436. var dx = Math.cos(innerAngle);
  32437. var dy = Math.sin(innerAngle);
  32438. // Create a vertex.
  32439. var normal = new BABYLON.Vector3(dx, dy, 0);
  32440. var position = normal.scale(thickness / 2);
  32441. var textureCoordinate = new BABYLON.Vector2(u, v);
  32442. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  32443. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  32444. positions.push(position.x, position.y, position.z);
  32445. normals.push(normal.x, normal.y, normal.z);
  32446. uvs.push(textureCoordinate.x, textureCoordinate.y);
  32447. // And create indices for two triangles.
  32448. var nextI = (i + 1) % stride;
  32449. var nextJ = (j + 1) % stride;
  32450. indices.push(i * stride + j);
  32451. indices.push(i * stride + nextJ);
  32452. indices.push(nextI * stride + j);
  32453. indices.push(i * stride + nextJ);
  32454. indices.push(nextI * stride + nextJ);
  32455. indices.push(nextI * stride + j);
  32456. }
  32457. }
  32458. // Sides
  32459. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32460. // Result
  32461. var vertexData = new VertexData();
  32462. vertexData.indices = indices;
  32463. vertexData.positions = positions;
  32464. vertexData.normals = normals;
  32465. vertexData.uvs = uvs;
  32466. return vertexData;
  32467. };
  32468. VertexData.CreateLineSystem = function (options) {
  32469. var indices = [];
  32470. var positions = [];
  32471. var lines = options.lines;
  32472. var idx = 0;
  32473. for (var l = 0; l < lines.length; l++) {
  32474. var points = lines[l];
  32475. for (var index = 0; index < points.length; index++) {
  32476. positions.push(points[index].x, points[index].y, points[index].z);
  32477. if (index > 0) {
  32478. indices.push(idx - 1);
  32479. indices.push(idx);
  32480. }
  32481. idx++;
  32482. }
  32483. }
  32484. var vertexData = new VertexData();
  32485. vertexData.indices = indices;
  32486. vertexData.positions = positions;
  32487. return vertexData;
  32488. };
  32489. VertexData.CreateDashedLines = function (options) {
  32490. var dashSize = options.dashSize || 3;
  32491. var gapSize = options.gapSize || 1;
  32492. var dashNb = options.dashNb || 200;
  32493. var points = options.points;
  32494. var positions = new Array();
  32495. var indices = new Array();
  32496. var curvect = BABYLON.Vector3.Zero();
  32497. var lg = 0;
  32498. var nb = 0;
  32499. var shft = 0;
  32500. var dashshft = 0;
  32501. var curshft = 0;
  32502. var idx = 0;
  32503. var i = 0;
  32504. for (i = 0; i < points.length - 1; i++) {
  32505. points[i + 1].subtractToRef(points[i], curvect);
  32506. lg += curvect.length();
  32507. }
  32508. shft = lg / dashNb;
  32509. dashshft = dashSize * shft / (dashSize + gapSize);
  32510. for (i = 0; i < points.length - 1; i++) {
  32511. points[i + 1].subtractToRef(points[i], curvect);
  32512. nb = Math.floor(curvect.length() / shft);
  32513. curvect.normalize();
  32514. for (var j = 0; j < nb; j++) {
  32515. curshft = shft * j;
  32516. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  32517. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  32518. indices.push(idx, idx + 1);
  32519. idx += 2;
  32520. }
  32521. }
  32522. // Result
  32523. var vertexData = new VertexData();
  32524. vertexData.positions = positions;
  32525. vertexData.indices = indices;
  32526. return vertexData;
  32527. };
  32528. VertexData.CreateGround = function (options) {
  32529. var indices = [];
  32530. var positions = [];
  32531. var normals = [];
  32532. var uvs = [];
  32533. var row, col;
  32534. var width = options.width || 1;
  32535. var height = options.height || 1;
  32536. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  32537. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  32538. for (row = 0; row <= subdivisionsY; row++) {
  32539. for (col = 0; col <= subdivisionsX; col++) {
  32540. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  32541. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32542. positions.push(position.x, position.y, position.z);
  32543. normals.push(normal.x, normal.y, normal.z);
  32544. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsX);
  32545. }
  32546. }
  32547. for (row = 0; row < subdivisionsY; row++) {
  32548. for (col = 0; col < subdivisionsX; col++) {
  32549. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32550. indices.push(col + 1 + row * (subdivisionsX + 1));
  32551. indices.push(col + row * (subdivisionsX + 1));
  32552. indices.push(col + (row + 1) * (subdivisionsX + 1));
  32553. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32554. indices.push(col + row * (subdivisionsX + 1));
  32555. }
  32556. }
  32557. // Result
  32558. var vertexData = new VertexData();
  32559. vertexData.indices = indices;
  32560. vertexData.positions = positions;
  32561. vertexData.normals = normals;
  32562. vertexData.uvs = uvs;
  32563. return vertexData;
  32564. };
  32565. VertexData.CreateTiledGround = function (options) {
  32566. var xmin = options.xmin || -1.0;
  32567. var zmin = options.zmin || -1.0;
  32568. var xmax = options.xmax || 1.0;
  32569. var zmax = options.zmax || 1.0;
  32570. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  32571. var precision = options.precision || { w: 1, h: 1 };
  32572. var indices = [];
  32573. var positions = [];
  32574. var normals = [];
  32575. var uvs = [];
  32576. var row, col, tileRow, tileCol;
  32577. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  32578. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  32579. precision.w = (precision.w < 1) ? 1 : precision.w;
  32580. precision.h = (precision.h < 1) ? 1 : precision.h;
  32581. var tileSize = {
  32582. 'w': (xmax - xmin) / subdivisions.w,
  32583. 'h': (zmax - zmin) / subdivisions.h
  32584. };
  32585. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  32586. // Indices
  32587. var base = positions.length / 3;
  32588. var rowLength = precision.w + 1;
  32589. for (row = 0; row < precision.h; row++) {
  32590. for (col = 0; col < precision.w; col++) {
  32591. var square = [
  32592. base + col + row * rowLength,
  32593. base + (col + 1) + row * rowLength,
  32594. base + (col + 1) + (row + 1) * rowLength,
  32595. base + col + (row + 1) * rowLength
  32596. ];
  32597. indices.push(square[1]);
  32598. indices.push(square[2]);
  32599. indices.push(square[3]);
  32600. indices.push(square[0]);
  32601. indices.push(square[1]);
  32602. indices.push(square[3]);
  32603. }
  32604. }
  32605. // Position, normals and uvs
  32606. var position = BABYLON.Vector3.Zero();
  32607. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32608. for (row = 0; row <= precision.h; row++) {
  32609. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  32610. for (col = 0; col <= precision.w; col++) {
  32611. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  32612. position.y = 0;
  32613. positions.push(position.x, position.y, position.z);
  32614. normals.push(normal.x, normal.y, normal.z);
  32615. uvs.push(col / precision.w, row / precision.h);
  32616. }
  32617. }
  32618. }
  32619. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  32620. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  32621. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  32622. }
  32623. }
  32624. // Result
  32625. var vertexData = new VertexData();
  32626. vertexData.indices = indices;
  32627. vertexData.positions = positions;
  32628. vertexData.normals = normals;
  32629. vertexData.uvs = uvs;
  32630. return vertexData;
  32631. };
  32632. VertexData.CreateGroundFromHeightMap = function (options) {
  32633. var indices = [];
  32634. var positions = [];
  32635. var normals = [];
  32636. var uvs = [];
  32637. var row, col;
  32638. // Vertices
  32639. for (row = 0; row <= options.subdivisions; row++) {
  32640. for (col = 0; col <= options.subdivisions; col++) {
  32641. 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));
  32642. // Compute height
  32643. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  32644. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  32645. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  32646. var r = options.buffer[pos] / 255.0;
  32647. var g = options.buffer[pos + 1] / 255.0;
  32648. var b = options.buffer[pos + 2] / 255.0;
  32649. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32650. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  32651. // Add vertex
  32652. positions.push(position.x, position.y, position.z);
  32653. normals.push(0, 0, 0);
  32654. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  32655. }
  32656. }
  32657. // Indices
  32658. for (row = 0; row < options.subdivisions; row++) {
  32659. for (col = 0; col < options.subdivisions; col++) {
  32660. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  32661. indices.push(col + 1 + row * (options.subdivisions + 1));
  32662. indices.push(col + row * (options.subdivisions + 1));
  32663. indices.push(col + (row + 1) * (options.subdivisions + 1));
  32664. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  32665. indices.push(col + row * (options.subdivisions + 1));
  32666. }
  32667. }
  32668. // Normals
  32669. VertexData.ComputeNormals(positions, indices, normals);
  32670. // Result
  32671. var vertexData = new VertexData();
  32672. vertexData.indices = indices;
  32673. vertexData.positions = positions;
  32674. vertexData.normals = normals;
  32675. vertexData.uvs = uvs;
  32676. return vertexData;
  32677. };
  32678. VertexData.CreatePlane = function (options) {
  32679. var indices = [];
  32680. var positions = [];
  32681. var normals = [];
  32682. var uvs = [];
  32683. var width = options.width || options.size || 1;
  32684. var height = options.height || options.size || 1;
  32685. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32686. // Vertices
  32687. var halfWidth = width / 2.0;
  32688. var halfHeight = height / 2.0;
  32689. positions.push(-halfWidth, -halfHeight, 0);
  32690. normals.push(0, 0, -1.0);
  32691. uvs.push(0.0, 0.0);
  32692. positions.push(halfWidth, -halfHeight, 0);
  32693. normals.push(0, 0, -1.0);
  32694. uvs.push(1.0, 0.0);
  32695. positions.push(halfWidth, halfHeight, 0);
  32696. normals.push(0, 0, -1.0);
  32697. uvs.push(1.0, 1.0);
  32698. positions.push(-halfWidth, halfHeight, 0);
  32699. normals.push(0, 0, -1.0);
  32700. uvs.push(0.0, 1.0);
  32701. // Indices
  32702. indices.push(0);
  32703. indices.push(1);
  32704. indices.push(2);
  32705. indices.push(0);
  32706. indices.push(2);
  32707. indices.push(3);
  32708. // Sides
  32709. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32710. // Result
  32711. var vertexData = new VertexData();
  32712. vertexData.indices = indices;
  32713. vertexData.positions = positions;
  32714. vertexData.normals = normals;
  32715. vertexData.uvs = uvs;
  32716. return vertexData;
  32717. };
  32718. VertexData.CreateDisc = function (options) {
  32719. var positions = [];
  32720. var indices = [];
  32721. var normals = [];
  32722. var uvs = [];
  32723. var radius = options.radius || 0.5;
  32724. var tessellation = options.tessellation || 64;
  32725. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32726. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32727. // positions and uvs
  32728. positions.push(0, 0, 0); // disc center first
  32729. uvs.push(0.5, 0.5);
  32730. var theta = Math.PI * 2 * arc;
  32731. var step = theta / tessellation;
  32732. for (var a = 0; a < theta; a += step) {
  32733. var x = Math.cos(a);
  32734. var y = Math.sin(a);
  32735. var u = (x + 1) / 2;
  32736. var v = (1 - y) / 2;
  32737. positions.push(radius * x, radius * y, 0);
  32738. uvs.push(u, v);
  32739. }
  32740. if (arc === 1) {
  32741. positions.push(positions[3], positions[4], positions[5]); // close the circle
  32742. uvs.push(uvs[2], uvs[3]);
  32743. }
  32744. //indices
  32745. var vertexNb = positions.length / 3;
  32746. for (var i = 1; i < vertexNb - 1; i++) {
  32747. indices.push(i + 1, 0, i);
  32748. }
  32749. // result
  32750. VertexData.ComputeNormals(positions, indices, normals);
  32751. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32752. var vertexData = new VertexData();
  32753. vertexData.indices = indices;
  32754. vertexData.positions = positions;
  32755. vertexData.normals = normals;
  32756. vertexData.uvs = uvs;
  32757. return vertexData;
  32758. };
  32759. VertexData.CreateIcoSphere = function (options) {
  32760. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32761. var radius = options.radius || 1;
  32762. var flat = (options.flat === undefined) ? true : options.flat;
  32763. var subdivisions = options.subdivisions || 4;
  32764. var radiusX = options.radiusX || radius;
  32765. var radiusY = options.radiusY || radius;
  32766. var radiusZ = options.radiusZ || radius;
  32767. var t = (1 + Math.sqrt(5)) / 2;
  32768. // 12 vertex x,y,z
  32769. var ico_vertices = [
  32770. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  32771. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  32772. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  32773. ];
  32774. // index of 3 vertex makes a face of icopshere
  32775. var ico_indices = [
  32776. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  32777. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  32778. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  32779. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  32780. ];
  32781. // vertex for uv have aliased position, not for UV
  32782. var vertices_unalias_id = [
  32783. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  32784. // vertex alias
  32785. 0,
  32786. 2,
  32787. 3,
  32788. 3,
  32789. 3,
  32790. 4,
  32791. 7,
  32792. 8,
  32793. 9,
  32794. 9,
  32795. 10,
  32796. 11 // 23: B + 12
  32797. ];
  32798. // uv as integer step (not pixels !)
  32799. var ico_vertexuv = [
  32800. 5, 1, 3, 1, 6, 4, 0, 0,
  32801. 5, 3, 4, 2, 2, 2, 4, 0,
  32802. 2, 0, 1, 1, 6, 0, 6, 2,
  32803. // vertex alias (for same vertex on different faces)
  32804. 0, 4,
  32805. 3, 3,
  32806. 4, 4,
  32807. 3, 1,
  32808. 4, 2,
  32809. 4, 4,
  32810. 0, 2,
  32811. 1, 1,
  32812. 2, 2,
  32813. 3, 3,
  32814. 1, 3,
  32815. 2, 4 // 23: B + 12
  32816. ];
  32817. // Vertices[0, 1, ...9, A, B] : position on UV plane
  32818. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  32819. // First island of uv mapping
  32820. // v = 4h 3+ 2
  32821. // v = 3h 9+ 4
  32822. // v = 2h 9+ 5 B
  32823. // v = 1h 9 1 0
  32824. // v = 0h 3 8 7 A
  32825. // u = 0 1 2 3 4 5 6 *a
  32826. // Second island of uv mapping
  32827. // v = 4h 0+ B+ 4+
  32828. // v = 3h A+ 2+
  32829. // v = 2h 7+ 6 3+
  32830. // v = 1h 8+ 3+
  32831. // v = 0h
  32832. // u = 0 1 2 3 4 5 6 *a
  32833. // Face layout on texture UV mapping
  32834. // ============
  32835. // \ 4 /\ 16 / ======
  32836. // \ / \ / /\ 11 /
  32837. // \/ 7 \/ / \ /
  32838. // ======= / 10 \/
  32839. // /\ 17 /\ =======
  32840. // / \ / \ \ 15 /\
  32841. // / 8 \/ 12 \ \ / \
  32842. // ============ \/ 6 \
  32843. // \ 18 /\ ============
  32844. // \ / \ \ 5 /\ 0 /
  32845. // \/ 13 \ \ / \ /
  32846. // ======= \/ 1 \/
  32847. // =============
  32848. // /\ 19 /\ 2 /\
  32849. // / \ / \ / \
  32850. // / 14 \/ 9 \/ 3 \
  32851. // ===================
  32852. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  32853. var ustep = 138 / 1024;
  32854. var vstep = 239 / 1024;
  32855. var uoffset = 60 / 1024;
  32856. var voffset = 26 / 1024;
  32857. // Second island should have margin, not to touch the first island
  32858. // avoid any borderline artefact in pixel rounding
  32859. var island_u_offset = -40 / 1024;
  32860. var island_v_offset = +20 / 1024;
  32861. // face is either island 0 or 1 :
  32862. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  32863. var island = [
  32864. 0, 0, 0, 0, 1,
  32865. 0, 0, 1, 1, 0,
  32866. 0, 0, 1, 1, 0,
  32867. 0, 1, 1, 1, 0 // 15 - 19
  32868. ];
  32869. var indices = [];
  32870. var positions = [];
  32871. var normals = [];
  32872. var uvs = [];
  32873. var current_indice = 0;
  32874. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  32875. var face_vertex_pos = new Array(3);
  32876. var face_vertex_uv = new Array(3);
  32877. var v012;
  32878. for (v012 = 0; v012 < 3; v012++) {
  32879. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  32880. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  32881. }
  32882. // create all with normals
  32883. for (var face = 0; face < 20; face++) {
  32884. // 3 vertex per face
  32885. for (v012 = 0; v012 < 3; v012++) {
  32886. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  32887. var v_id = ico_indices[3 * face + v012];
  32888. // vertex have 3D position (x,y,z)
  32889. 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]);
  32890. // Normalize to get normal, then scale to radius
  32891. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  32892. // uv Coordinates from vertex ID
  32893. 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);
  32894. }
  32895. // Subdivide the face (interpolate pos, norm, uv)
  32896. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  32897. // - norm is linear interpolation of vertex corner normal
  32898. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  32899. // - uv is linear interpolation
  32900. //
  32901. // Topology is as below for sub-divide by 2
  32902. // vertex shown as v0,v1,v2
  32903. // interp index is i1 to progress in range [v0,v1[
  32904. // interp index is i2 to progress in range [v0,v2[
  32905. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  32906. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32907. //
  32908. //
  32909. // i2 v2
  32910. // ^ ^
  32911. // / / \
  32912. // / / \
  32913. // / / \
  32914. // / / (0,1) \
  32915. // / #---------\
  32916. // / / \ (0,0)'/ \
  32917. // / / \ / \
  32918. // / / \ / \
  32919. // / / (0,0) \ / (1,0) \
  32920. // / #---------#---------\
  32921. // v0 v1
  32922. //
  32923. // --------------------> i1
  32924. //
  32925. // interp of (i1,i2):
  32926. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  32927. // along i1 : lerp(x0,x1, i1/(S-i2))
  32928. //
  32929. // centroid of triangle is needed to get help normal computation
  32930. // (c1,c2) are used for centroid location
  32931. var interp_vertex = function (i1, i2, c1, c2) {
  32932. // vertex is interpolated from
  32933. // - face_vertex_pos[0..2]
  32934. // - face_vertex_uv[0..2]
  32935. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  32936. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  32937. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  32938. pos_interp.normalize();
  32939. var vertex_normal;
  32940. if (flat) {
  32941. // in flat mode, recalculate normal as face centroid normal
  32942. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  32943. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  32944. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  32945. }
  32946. else {
  32947. // in smooth mode, recalculate normal from each single vertex position
  32948. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  32949. }
  32950. // Vertex normal need correction due to X,Y,Z radius scaling
  32951. vertex_normal.x /= radiusX;
  32952. vertex_normal.y /= radiusY;
  32953. vertex_normal.z /= radiusZ;
  32954. vertex_normal.normalize();
  32955. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  32956. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  32957. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  32958. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  32959. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  32960. uvs.push(uv_interp.x, uv_interp.y);
  32961. // push each vertex has member of a face
  32962. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  32963. indices.push(current_indice);
  32964. current_indice++;
  32965. };
  32966. for (var i2 = 0; i2 < subdivisions; i2++) {
  32967. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  32968. // face : (i1,i2) for /\ :
  32969. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  32970. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32971. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32972. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32973. if (i1 + i2 + 1 < subdivisions) {
  32974. // face : (i1,i2)' for \/ :
  32975. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32976. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32977. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32978. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32979. }
  32980. }
  32981. }
  32982. }
  32983. // Sides
  32984. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32985. // Result
  32986. var vertexData = new VertexData();
  32987. vertexData.indices = indices;
  32988. vertexData.positions = positions;
  32989. vertexData.normals = normals;
  32990. vertexData.uvs = uvs;
  32991. return vertexData;
  32992. };
  32993. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  32994. VertexData.CreatePolyhedron = function (options) {
  32995. // provided polyhedron types :
  32996. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  32997. // 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)
  32998. var polyhedra = [];
  32999. 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]] };
  33000. 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]] };
  33001. polyhedra[2] = {
  33002. 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]],
  33003. 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]]
  33004. };
  33005. polyhedra[3] = {
  33006. 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]],
  33007. 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]]
  33008. };
  33009. polyhedra[4] = {
  33010. 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]],
  33011. 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]]
  33012. };
  33013. 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]] };
  33014. 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]] };
  33015. 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]] };
  33016. 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]] };
  33017. 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]] };
  33018. 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]] };
  33019. 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]] };
  33020. 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]] };
  33021. 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]] };
  33022. polyhedra[14] = {
  33023. 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]],
  33024. 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]]
  33025. };
  33026. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33027. var size = options.size;
  33028. var sizeX = options.sizeX || size || 1;
  33029. var sizeY = options.sizeY || size || 1;
  33030. var sizeZ = options.sizeZ || size || 1;
  33031. var data = options.custom || polyhedra[type];
  33032. var nbfaces = data.face.length;
  33033. var faceUV = options.faceUV || new Array(nbfaces);
  33034. var faceColors = options.faceColors;
  33035. var flat = (options.flat === undefined) ? true : options.flat;
  33036. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33037. var positions = [];
  33038. var indices = [];
  33039. var normals = [];
  33040. var uvs = [];
  33041. var colors = [];
  33042. var index = 0;
  33043. var faceIdx = 0; // face cursor in the array "indexes"
  33044. var indexes = [];
  33045. var i = 0;
  33046. var f = 0;
  33047. var u, v, ang, x, y, tmp;
  33048. // default face colors and UV if undefined
  33049. if (flat) {
  33050. for (f = 0; f < nbfaces; f++) {
  33051. if (faceColors && faceColors[f] === undefined) {
  33052. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33053. }
  33054. if (faceUV && faceUV[f] === undefined) {
  33055. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33056. }
  33057. }
  33058. }
  33059. if (!flat) {
  33060. for (i = 0; i < data.vertex.length; i++) {
  33061. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33062. uvs.push(0, 0);
  33063. }
  33064. for (f = 0; f < nbfaces; f++) {
  33065. for (i = 0; i < data.face[f].length - 2; i++) {
  33066. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33067. }
  33068. }
  33069. }
  33070. else {
  33071. for (f = 0; f < nbfaces; f++) {
  33072. var fl = data.face[f].length; // number of vertices of the current face
  33073. ang = 2 * Math.PI / fl;
  33074. x = 0.5 * Math.tan(ang / 2);
  33075. y = 0.5;
  33076. // positions, uvs, colors
  33077. for (i = 0; i < fl; i++) {
  33078. // positions
  33079. 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);
  33080. indexes.push(index);
  33081. index++;
  33082. // uvs
  33083. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33084. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33085. uvs.push(u, v);
  33086. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33087. y = x * Math.sin(ang) + y * Math.cos(ang);
  33088. x = tmp;
  33089. // colors
  33090. if (faceColors) {
  33091. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33092. }
  33093. }
  33094. // indices from indexes
  33095. for (i = 0; i < fl - 2; i++) {
  33096. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33097. }
  33098. faceIdx += fl;
  33099. }
  33100. }
  33101. VertexData.ComputeNormals(positions, indices, normals);
  33102. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33103. var vertexData = new VertexData();
  33104. vertexData.positions = positions;
  33105. vertexData.indices = indices;
  33106. vertexData.normals = normals;
  33107. vertexData.uvs = uvs;
  33108. if (faceColors && flat) {
  33109. vertexData.colors = colors;
  33110. }
  33111. return vertexData;
  33112. };
  33113. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  33114. VertexData.CreateTorusKnot = function (options) {
  33115. var indices = [];
  33116. var positions = [];
  33117. var normals = [];
  33118. var uvs = [];
  33119. var radius = options.radius || 2;
  33120. var tube = options.tube || 0.5;
  33121. var radialSegments = options.radialSegments || 32;
  33122. var tubularSegments = options.tubularSegments || 32;
  33123. var p = options.p || 2;
  33124. var q = options.q || 3;
  33125. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33126. // Helper
  33127. var getPos = function (angle) {
  33128. var cu = Math.cos(angle);
  33129. var su = Math.sin(angle);
  33130. var quOverP = q / p * angle;
  33131. var cs = Math.cos(quOverP);
  33132. var tx = radius * (2 + cs) * 0.5 * cu;
  33133. var ty = radius * (2 + cs) * su * 0.5;
  33134. var tz = radius * Math.sin(quOverP) * 0.5;
  33135. return new BABYLON.Vector3(tx, ty, tz);
  33136. };
  33137. // Vertices
  33138. var i;
  33139. var j;
  33140. for (i = 0; i <= radialSegments; i++) {
  33141. var modI = i % radialSegments;
  33142. var u = modI / radialSegments * 2 * p * Math.PI;
  33143. var p1 = getPos(u);
  33144. var p2 = getPos(u + 0.01);
  33145. var tang = p2.subtract(p1);
  33146. var n = p2.add(p1);
  33147. var bitan = BABYLON.Vector3.Cross(tang, n);
  33148. n = BABYLON.Vector3.Cross(bitan, tang);
  33149. bitan.normalize();
  33150. n.normalize();
  33151. for (j = 0; j < tubularSegments; j++) {
  33152. var modJ = j % tubularSegments;
  33153. var v = modJ / tubularSegments * 2 * Math.PI;
  33154. var cx = -tube * Math.cos(v);
  33155. var cy = tube * Math.sin(v);
  33156. positions.push(p1.x + cx * n.x + cy * bitan.x);
  33157. positions.push(p1.y + cx * n.y + cy * bitan.y);
  33158. positions.push(p1.z + cx * n.z + cy * bitan.z);
  33159. uvs.push(i / radialSegments);
  33160. uvs.push(j / tubularSegments);
  33161. }
  33162. }
  33163. for (i = 0; i < radialSegments; i++) {
  33164. for (j = 0; j < tubularSegments; j++) {
  33165. var jNext = (j + 1) % tubularSegments;
  33166. var a = i * tubularSegments + j;
  33167. var b = (i + 1) * tubularSegments + j;
  33168. var c = (i + 1) * tubularSegments + jNext;
  33169. var d = i * tubularSegments + jNext;
  33170. indices.push(d);
  33171. indices.push(b);
  33172. indices.push(a);
  33173. indices.push(d);
  33174. indices.push(c);
  33175. indices.push(b);
  33176. }
  33177. }
  33178. // Normals
  33179. VertexData.ComputeNormals(positions, indices, normals);
  33180. // Sides
  33181. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33182. // Result
  33183. var vertexData = new VertexData();
  33184. vertexData.indices = indices;
  33185. vertexData.positions = positions;
  33186. vertexData.normals = normals;
  33187. vertexData.uvs = uvs;
  33188. return vertexData;
  33189. };
  33190. // Tools
  33191. /**
  33192. * @param {any} - positions (number[] or Float32Array)
  33193. * @param {any} - indices (number[] or Uint16Array)
  33194. * @param {any} - normals (number[] or Float32Array)
  33195. */
  33196. VertexData.ComputeNormals = function (positions, indices, normals) {
  33197. var index = 0;
  33198. var p1p2x = 0.0;
  33199. var p1p2y = 0.0;
  33200. var p1p2z = 0.0;
  33201. var p3p2x = 0.0;
  33202. var p3p2y = 0.0;
  33203. var p3p2z = 0.0;
  33204. var faceNormalx = 0.0;
  33205. var faceNormaly = 0.0;
  33206. var faceNormalz = 0.0;
  33207. var length = 0.0;
  33208. var i1 = 0;
  33209. var i2 = 0;
  33210. var i3 = 0;
  33211. for (index = 0; index < positions.length; index++) {
  33212. normals[index] = 0.0;
  33213. }
  33214. // indice triplet = 1 face
  33215. var nbFaces = indices.length / 3;
  33216. for (index = 0; index < nbFaces; index++) {
  33217. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  33218. i2 = indices[index * 3 + 1];
  33219. i3 = indices[index * 3 + 2];
  33220. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  33221. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  33222. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  33223. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  33224. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  33225. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  33226. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  33227. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  33228. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  33229. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33230. length = (length === 0) ? 1.0 : length;
  33231. faceNormalx /= length; // normalize this normal
  33232. faceNormaly /= length;
  33233. faceNormalz /= length;
  33234. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  33235. normals[i1 * 3 + 1] += faceNormaly;
  33236. normals[i1 * 3 + 2] += faceNormalz;
  33237. normals[i2 * 3] += faceNormalx;
  33238. normals[i2 * 3 + 1] += faceNormaly;
  33239. normals[i2 * 3 + 2] += faceNormalz;
  33240. normals[i3 * 3] += faceNormalx;
  33241. normals[i3 * 3 + 1] += faceNormaly;
  33242. normals[i3 * 3 + 2] += faceNormalz;
  33243. }
  33244. // last normalization of each normal
  33245. for (index = 0; index < normals.length / 3; index++) {
  33246. faceNormalx = normals[index * 3];
  33247. faceNormaly = normals[index * 3 + 1];
  33248. faceNormalz = normals[index * 3 + 2];
  33249. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33250. length = (length === 0) ? 1.0 : length;
  33251. faceNormalx /= length;
  33252. faceNormaly /= length;
  33253. faceNormalz /= length;
  33254. normals[index * 3] = faceNormalx;
  33255. normals[index * 3 + 1] = faceNormaly;
  33256. normals[index * 3 + 2] = faceNormalz;
  33257. }
  33258. };
  33259. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  33260. var li = indices.length;
  33261. var ln = normals.length;
  33262. var i;
  33263. var n;
  33264. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33265. switch (sideOrientation) {
  33266. case BABYLON.Mesh.FRONTSIDE:
  33267. // nothing changed
  33268. break;
  33269. case BABYLON.Mesh.BACKSIDE:
  33270. var tmp;
  33271. // indices
  33272. for (i = 0; i < li; i += 3) {
  33273. tmp = indices[i];
  33274. indices[i] = indices[i + 2];
  33275. indices[i + 2] = tmp;
  33276. }
  33277. // normals
  33278. for (n = 0; n < ln; n++) {
  33279. normals[n] = -normals[n];
  33280. }
  33281. break;
  33282. case BABYLON.Mesh.DOUBLESIDE:
  33283. // positions
  33284. var lp = positions.length;
  33285. var l = lp / 3;
  33286. for (var p = 0; p < lp; p++) {
  33287. positions[lp + p] = positions[p];
  33288. }
  33289. // indices
  33290. for (i = 0; i < li; i += 3) {
  33291. indices[i + li] = indices[i + 2] + l;
  33292. indices[i + 1 + li] = indices[i + 1] + l;
  33293. indices[i + 2 + li] = indices[i] + l;
  33294. }
  33295. // normals
  33296. for (n = 0; n < ln; n++) {
  33297. normals[ln + n] = -normals[n];
  33298. }
  33299. // uvs
  33300. var lu = uvs.length;
  33301. for (var u = 0; u < lu; u++) {
  33302. uvs[u + lu] = uvs[u];
  33303. }
  33304. break;
  33305. }
  33306. };
  33307. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  33308. var vertexData = new VertexData();
  33309. // positions
  33310. var positions = parsedVertexData.positions;
  33311. if (positions) {
  33312. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  33313. }
  33314. // normals
  33315. var normals = parsedVertexData.normals;
  33316. if (normals) {
  33317. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  33318. }
  33319. // uvs
  33320. var uvs = parsedVertexData.uvs;
  33321. if (uvs) {
  33322. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  33323. }
  33324. // uv2s
  33325. var uv2s = parsedVertexData.uv2s;
  33326. if (uv2s) {
  33327. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  33328. }
  33329. // uv3s
  33330. var uv3s = parsedVertexData.uv3s;
  33331. if (uv3s) {
  33332. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  33333. }
  33334. // uv4s
  33335. var uv4s = parsedVertexData.uv4s;
  33336. if (uv4s) {
  33337. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  33338. }
  33339. // uv5s
  33340. var uv5s = parsedVertexData.uv5s;
  33341. if (uv5s) {
  33342. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  33343. }
  33344. // uv6s
  33345. var uv6s = parsedVertexData.uv6s;
  33346. if (uv6s) {
  33347. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  33348. }
  33349. // colors
  33350. var colors = parsedVertexData.colors;
  33351. if (colors) {
  33352. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  33353. }
  33354. // matricesIndices
  33355. var matricesIndices = parsedVertexData.matricesIndices;
  33356. if (matricesIndices) {
  33357. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  33358. }
  33359. // matricesWeights
  33360. var matricesWeights = parsedVertexData.matricesWeights;
  33361. if (matricesWeights) {
  33362. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  33363. }
  33364. // indices
  33365. var indices = parsedVertexData.indices;
  33366. if (indices) {
  33367. vertexData.indices = indices;
  33368. }
  33369. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  33370. };
  33371. return VertexData;
  33372. }());
  33373. BABYLON.VertexData = VertexData;
  33374. })(BABYLON || (BABYLON = {}));
  33375. var BABYLON;
  33376. (function (BABYLON) {
  33377. var Tags = (function () {
  33378. function Tags() {
  33379. }
  33380. Tags.EnableFor = function (obj) {
  33381. obj._tags = obj._tags || {};
  33382. obj.hasTags = function () {
  33383. return Tags.HasTags(obj);
  33384. };
  33385. obj.addTags = function (tagsString) {
  33386. return Tags.AddTagsTo(obj, tagsString);
  33387. };
  33388. obj.removeTags = function (tagsString) {
  33389. return Tags.RemoveTagsFrom(obj, tagsString);
  33390. };
  33391. obj.matchesTagsQuery = function (tagsQuery) {
  33392. return Tags.MatchesQuery(obj, tagsQuery);
  33393. };
  33394. };
  33395. Tags.DisableFor = function (obj) {
  33396. delete obj._tags;
  33397. delete obj.hasTags;
  33398. delete obj.addTags;
  33399. delete obj.removeTags;
  33400. delete obj.matchesTagsQuery;
  33401. };
  33402. Tags.HasTags = function (obj) {
  33403. if (!obj._tags) {
  33404. return false;
  33405. }
  33406. return !BABYLON.Tools.IsEmpty(obj._tags);
  33407. };
  33408. Tags.GetTags = function (obj, asString) {
  33409. if (asString === void 0) { asString = true; }
  33410. if (!obj._tags) {
  33411. return null;
  33412. }
  33413. if (asString) {
  33414. var tagsArray = [];
  33415. for (var tag in obj._tags) {
  33416. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  33417. tagsArray.push(tag);
  33418. }
  33419. }
  33420. return tagsArray.join(" ");
  33421. }
  33422. else {
  33423. return obj._tags;
  33424. }
  33425. };
  33426. // the tags 'true' and 'false' are reserved and cannot be used as tags
  33427. // a tag cannot start with '||', '&&', and '!'
  33428. // it cannot contain whitespaces
  33429. Tags.AddTagsTo = function (obj, tagsString) {
  33430. if (!tagsString) {
  33431. return;
  33432. }
  33433. if (typeof tagsString !== "string") {
  33434. return;
  33435. }
  33436. var tags = tagsString.split(" ");
  33437. tags.forEach(function (tag, index, array) {
  33438. Tags._AddTagTo(obj, tag);
  33439. });
  33440. };
  33441. Tags._AddTagTo = function (obj, tag) {
  33442. tag = tag.trim();
  33443. if (tag === "" || tag === "true" || tag === "false") {
  33444. return;
  33445. }
  33446. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  33447. return;
  33448. }
  33449. Tags.EnableFor(obj);
  33450. obj._tags[tag] = true;
  33451. };
  33452. Tags.RemoveTagsFrom = function (obj, tagsString) {
  33453. if (!Tags.HasTags(obj)) {
  33454. return;
  33455. }
  33456. var tags = tagsString.split(" ");
  33457. for (var t in tags) {
  33458. Tags._RemoveTagFrom(obj, tags[t]);
  33459. }
  33460. };
  33461. Tags._RemoveTagFrom = function (obj, tag) {
  33462. delete obj._tags[tag];
  33463. };
  33464. Tags.MatchesQuery = function (obj, tagsQuery) {
  33465. if (tagsQuery === undefined) {
  33466. return true;
  33467. }
  33468. if (tagsQuery === "") {
  33469. return Tags.HasTags(obj);
  33470. }
  33471. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  33472. };
  33473. return Tags;
  33474. }());
  33475. BABYLON.Tags = Tags;
  33476. })(BABYLON || (BABYLON = {}));
  33477. var BABYLON;
  33478. (function (BABYLON) {
  33479. var Internals;
  33480. (function (Internals) {
  33481. var AndOrNotEvaluator = (function () {
  33482. function AndOrNotEvaluator() {
  33483. }
  33484. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  33485. if (!query.match(/\([^\(\)]*\)/g)) {
  33486. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  33487. }
  33488. else {
  33489. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  33490. // remove parenthesis
  33491. r = r.slice(1, r.length - 1);
  33492. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  33493. });
  33494. }
  33495. if (query === "true") {
  33496. return true;
  33497. }
  33498. if (query === "false") {
  33499. return false;
  33500. }
  33501. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  33502. };
  33503. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  33504. evaluateCallback = evaluateCallback || (function (r) {
  33505. return r === "true" ? true : false;
  33506. });
  33507. var result;
  33508. var or = parenthesisContent.split("||");
  33509. for (var i in or) {
  33510. if (or.hasOwnProperty(i)) {
  33511. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  33512. var and = ori.split("&&");
  33513. if (and.length > 1) {
  33514. for (var j = 0; j < and.length; ++j) {
  33515. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  33516. if (andj !== "true" && andj !== "false") {
  33517. if (andj[0] === "!") {
  33518. result = !evaluateCallback(andj.substring(1));
  33519. }
  33520. else {
  33521. result = evaluateCallback(andj);
  33522. }
  33523. }
  33524. else {
  33525. result = andj === "true" ? true : false;
  33526. }
  33527. if (!result) {
  33528. ori = "false";
  33529. break;
  33530. }
  33531. }
  33532. }
  33533. if (result || ori === "true") {
  33534. result = true;
  33535. break;
  33536. }
  33537. // result equals false (or undefined)
  33538. if (ori !== "true" && ori !== "false") {
  33539. if (ori[0] === "!") {
  33540. result = !evaluateCallback(ori.substring(1));
  33541. }
  33542. else {
  33543. result = evaluateCallback(ori);
  33544. }
  33545. }
  33546. else {
  33547. result = ori === "true" ? true : false;
  33548. }
  33549. }
  33550. }
  33551. // the whole parenthesis scope is replaced by 'true' or 'false'
  33552. return result ? "true" : "false";
  33553. };
  33554. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  33555. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  33556. // remove whitespaces
  33557. r = r.replace(/[\s]/g, function () { return ""; });
  33558. return r.length % 2 ? "!" : "";
  33559. });
  33560. booleanString = booleanString.trim();
  33561. if (booleanString === "!true") {
  33562. booleanString = "false";
  33563. }
  33564. else if (booleanString === "!false") {
  33565. booleanString = "true";
  33566. }
  33567. return booleanString;
  33568. };
  33569. return AndOrNotEvaluator;
  33570. }());
  33571. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  33572. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33573. })(BABYLON || (BABYLON = {}));
  33574. var BABYLON;
  33575. (function (BABYLON) {
  33576. var PostProcessRenderPass = (function () {
  33577. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  33578. this._enabled = true;
  33579. this._refCount = 0;
  33580. this._name = name;
  33581. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  33582. this.setRenderList(renderList);
  33583. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  33584. this._renderTexture.onAfterRenderObservable.add(afterRender);
  33585. this._scene = scene;
  33586. this._renderList = renderList;
  33587. }
  33588. // private
  33589. PostProcessRenderPass.prototype._incRefCount = function () {
  33590. if (this._refCount === 0) {
  33591. this._scene.customRenderTargets.push(this._renderTexture);
  33592. }
  33593. return ++this._refCount;
  33594. };
  33595. PostProcessRenderPass.prototype._decRefCount = function () {
  33596. this._refCount--;
  33597. if (this._refCount <= 0) {
  33598. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  33599. }
  33600. return this._refCount;
  33601. };
  33602. PostProcessRenderPass.prototype._update = function () {
  33603. this.setRenderList(this._renderList);
  33604. };
  33605. // public
  33606. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  33607. this._renderTexture.renderList = renderList;
  33608. };
  33609. PostProcessRenderPass.prototype.getRenderTexture = function () {
  33610. return this._renderTexture;
  33611. };
  33612. return PostProcessRenderPass;
  33613. }());
  33614. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  33615. })(BABYLON || (BABYLON = {}));
  33616. var BABYLON;
  33617. (function (BABYLON) {
  33618. var PostProcessRenderEffect = (function () {
  33619. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  33620. this._engine = engine;
  33621. this._name = name;
  33622. this._singleInstance = singleInstance || true;
  33623. this._getPostProcess = getPostProcess;
  33624. this._cameras = [];
  33625. this._indicesForCamera = [];
  33626. this._postProcesses = {};
  33627. this._renderPasses = {};
  33628. this._renderEffectAsPasses = {};
  33629. }
  33630. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  33631. get: function () {
  33632. for (var index in this._postProcesses) {
  33633. if (!this._postProcesses[index].isSupported) {
  33634. return false;
  33635. }
  33636. }
  33637. return true;
  33638. },
  33639. enumerable: true,
  33640. configurable: true
  33641. });
  33642. PostProcessRenderEffect.prototype._update = function () {
  33643. for (var renderPassName in this._renderPasses) {
  33644. this._renderPasses[renderPassName]._update();
  33645. }
  33646. };
  33647. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  33648. this._renderPasses[renderPass._name] = renderPass;
  33649. this._linkParameters();
  33650. };
  33651. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  33652. delete this._renderPasses[renderPass._name];
  33653. this._linkParameters();
  33654. };
  33655. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  33656. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  33657. this._linkParameters();
  33658. };
  33659. PostProcessRenderEffect.prototype.getPass = function (passName) {
  33660. for (var renderPassName in this._renderPasses) {
  33661. if (renderPassName === passName) {
  33662. return this._renderPasses[passName];
  33663. }
  33664. }
  33665. };
  33666. PostProcessRenderEffect.prototype.emptyPasses = function () {
  33667. this._renderPasses = {};
  33668. this._linkParameters();
  33669. };
  33670. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  33671. var cameraKey;
  33672. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33673. for (var i = 0; i < _cam.length; i++) {
  33674. var camera = _cam[i];
  33675. var cameraName = camera.name;
  33676. if (this._singleInstance) {
  33677. cameraKey = 0;
  33678. }
  33679. else {
  33680. cameraKey = cameraName;
  33681. }
  33682. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  33683. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  33684. if (!this._indicesForCamera[cameraName]) {
  33685. this._indicesForCamera[cameraName] = [];
  33686. }
  33687. this._indicesForCamera[cameraName].push(index);
  33688. if (this._cameras.indexOf(camera) === -1) {
  33689. this._cameras[cameraName] = camera;
  33690. }
  33691. for (var passName in this._renderPasses) {
  33692. this._renderPasses[passName]._incRefCount();
  33693. }
  33694. }
  33695. this._linkParameters();
  33696. };
  33697. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  33698. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33699. for (var i = 0; i < _cam.length; i++) {
  33700. var camera = _cam[i];
  33701. var cameraName = camera.name;
  33702. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  33703. var index = this._cameras.indexOf(cameraName);
  33704. this._indicesForCamera.splice(index, 1);
  33705. this._cameras.splice(index, 1);
  33706. for (var passName in this._renderPasses) {
  33707. this._renderPasses[passName]._decRefCount();
  33708. }
  33709. }
  33710. };
  33711. PostProcessRenderEffect.prototype._enable = function (cameras) {
  33712. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33713. for (var i = 0; i < _cam.length; i++) {
  33714. var camera = _cam[i];
  33715. var cameraName = camera.name;
  33716. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  33717. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  33718. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  33719. }
  33720. }
  33721. for (var passName in this._renderPasses) {
  33722. this._renderPasses[passName]._incRefCount();
  33723. }
  33724. }
  33725. };
  33726. PostProcessRenderEffect.prototype._disable = function (cameras) {
  33727. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33728. for (var i = 0; i < _cam.length; i++) {
  33729. var camera = _cam[i];
  33730. var cameraName = camera.Name;
  33731. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  33732. for (var passName in this._renderPasses) {
  33733. this._renderPasses[passName]._decRefCount();
  33734. }
  33735. }
  33736. };
  33737. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  33738. if (this._singleInstance) {
  33739. return this._postProcesses[0];
  33740. }
  33741. else {
  33742. return this._postProcesses[camera.name];
  33743. }
  33744. };
  33745. PostProcessRenderEffect.prototype._linkParameters = function () {
  33746. var _this = this;
  33747. for (var index in this._postProcesses) {
  33748. if (this.applyParameters) {
  33749. this.applyParameters(this._postProcesses[index]);
  33750. }
  33751. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  33752. _this._linkTextures(effect);
  33753. });
  33754. }
  33755. };
  33756. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  33757. for (var renderPassName in this._renderPasses) {
  33758. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  33759. }
  33760. for (var renderEffectName in this._renderEffectAsPasses) {
  33761. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  33762. }
  33763. };
  33764. return PostProcessRenderEffect;
  33765. }());
  33766. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  33767. })(BABYLON || (BABYLON = {}));
  33768. var BABYLON;
  33769. (function (BABYLON) {
  33770. var PostProcessRenderPipeline = (function () {
  33771. function PostProcessRenderPipeline(engine, name) {
  33772. this._engine = engine;
  33773. this._name = name;
  33774. this._renderEffects = {};
  33775. this._renderEffectsForIsolatedPass = {};
  33776. this._cameras = [];
  33777. }
  33778. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  33779. get: function () {
  33780. for (var renderEffectName in this._renderEffects) {
  33781. if (!this._renderEffects[renderEffectName].isSupported) {
  33782. return false;
  33783. }
  33784. }
  33785. return true;
  33786. },
  33787. enumerable: true,
  33788. configurable: true
  33789. });
  33790. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  33791. this._renderEffects[renderEffect._name] = renderEffect;
  33792. };
  33793. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  33794. var renderEffects = this._renderEffects[renderEffectName];
  33795. if (!renderEffects) {
  33796. return;
  33797. }
  33798. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  33799. };
  33800. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  33801. var renderEffects = this._renderEffects[renderEffectName];
  33802. if (!renderEffects) {
  33803. return;
  33804. }
  33805. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  33806. };
  33807. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  33808. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33809. var indicesToDelete = [];
  33810. var i;
  33811. for (i = 0; i < _cam.length; i++) {
  33812. var camera = _cam[i];
  33813. var cameraName = camera.name;
  33814. if (this._cameras.indexOf(camera) === -1) {
  33815. this._cameras[cameraName] = camera;
  33816. }
  33817. else if (unique) {
  33818. indicesToDelete.push(i);
  33819. }
  33820. }
  33821. for (i = 0; i < indicesToDelete.length; i++) {
  33822. cameras.splice(indicesToDelete[i], 1);
  33823. }
  33824. for (var renderEffectName in this._renderEffects) {
  33825. this._renderEffects[renderEffectName]._attachCameras(_cam);
  33826. }
  33827. };
  33828. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  33829. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33830. for (var renderEffectName in this._renderEffects) {
  33831. this._renderEffects[renderEffectName]._detachCameras(_cam);
  33832. }
  33833. for (var i = 0; i < _cam.length; i++) {
  33834. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  33835. }
  33836. };
  33837. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  33838. var _this = this;
  33839. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33840. var pass = null;
  33841. var renderEffectName;
  33842. for (renderEffectName in this._renderEffects) {
  33843. pass = this._renderEffects[renderEffectName].getPass(passName);
  33844. if (pass != null) {
  33845. break;
  33846. }
  33847. }
  33848. if (pass === null) {
  33849. return;
  33850. }
  33851. for (renderEffectName in this._renderEffects) {
  33852. this._renderEffects[renderEffectName]._disable(_cam);
  33853. }
  33854. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  33855. for (var i = 0; i < _cam.length; i++) {
  33856. var camera = _cam[i];
  33857. var cameraName = camera.name;
  33858. 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); });
  33859. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  33860. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  33861. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  33862. }
  33863. };
  33864. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  33865. var _this = this;
  33866. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33867. for (var i = 0; i < _cam.length; i++) {
  33868. var camera = _cam[i];
  33869. var cameraName = camera.name;
  33870. 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); });
  33871. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  33872. }
  33873. for (var renderEffectName in this._renderEffects) {
  33874. this._renderEffects[renderEffectName]._enable(_cam);
  33875. }
  33876. };
  33877. PostProcessRenderPipeline.prototype._update = function () {
  33878. for (var renderEffectName in this._renderEffects) {
  33879. this._renderEffects[renderEffectName]._update();
  33880. }
  33881. for (var i = 0; i < this._cameras.length; i++) {
  33882. var cameraName = this._cameras[i].name;
  33883. if (this._renderEffectsForIsolatedPass[cameraName]) {
  33884. this._renderEffectsForIsolatedPass[cameraName]._update();
  33885. }
  33886. }
  33887. };
  33888. PostProcessRenderPipeline.prototype.dispose = function () {
  33889. // Must be implemented by children
  33890. };
  33891. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  33892. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  33893. return PostProcessRenderPipeline;
  33894. }());
  33895. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  33896. })(BABYLON || (BABYLON = {}));
  33897. var BABYLON;
  33898. (function (BABYLON) {
  33899. var PostProcessRenderPipelineManager = (function () {
  33900. function PostProcessRenderPipelineManager() {
  33901. this._renderPipelines = {};
  33902. }
  33903. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  33904. this._renderPipelines[renderPipeline._name] = renderPipeline;
  33905. };
  33906. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  33907. var renderPipeline = this._renderPipelines[renderPipelineName];
  33908. if (!renderPipeline) {
  33909. return;
  33910. }
  33911. renderPipeline._attachCameras(cameras, unique);
  33912. };
  33913. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  33914. var renderPipeline = this._renderPipelines[renderPipelineName];
  33915. if (!renderPipeline) {
  33916. return;
  33917. }
  33918. renderPipeline._detachCameras(cameras);
  33919. };
  33920. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  33921. var renderPipeline = this._renderPipelines[renderPipelineName];
  33922. if (!renderPipeline) {
  33923. return;
  33924. }
  33925. renderPipeline._enableEffect(renderEffectName, cameras);
  33926. };
  33927. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  33928. var renderPipeline = this._renderPipelines[renderPipelineName];
  33929. if (!renderPipeline) {
  33930. return;
  33931. }
  33932. renderPipeline._disableEffect(renderEffectName, cameras);
  33933. };
  33934. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  33935. var renderPipeline = this._renderPipelines[renderPipelineName];
  33936. if (!renderPipeline) {
  33937. return;
  33938. }
  33939. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  33940. };
  33941. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  33942. var renderPipeline = this._renderPipelines[renderPipelineName];
  33943. if (!renderPipeline) {
  33944. return;
  33945. }
  33946. renderPipeline._disableDisplayOnlyPass(cameras);
  33947. };
  33948. PostProcessRenderPipelineManager.prototype.update = function () {
  33949. for (var renderPipelineName in this._renderPipelines) {
  33950. var pipeline = this._renderPipelines[renderPipelineName];
  33951. if (!pipeline.isSupported) {
  33952. pipeline.dispose();
  33953. delete this._renderPipelines[renderPipelineName];
  33954. }
  33955. else {
  33956. pipeline._update();
  33957. }
  33958. }
  33959. };
  33960. return PostProcessRenderPipelineManager;
  33961. }());
  33962. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  33963. })(BABYLON || (BABYLON = {}));
  33964. var BABYLON;
  33965. (function (BABYLON) {
  33966. var BoundingBoxRenderer = (function () {
  33967. function BoundingBoxRenderer(scene) {
  33968. this.frontColor = new BABYLON.Color3(1, 1, 1);
  33969. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  33970. this.showBackLines = true;
  33971. this.renderList = new BABYLON.SmartArray(32);
  33972. this._vertexBuffers = {};
  33973. this._scene = scene;
  33974. }
  33975. BoundingBoxRenderer.prototype._prepareRessources = function () {
  33976. if (this._colorShader) {
  33977. return;
  33978. }
  33979. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  33980. attributes: [BABYLON.VertexBuffer.PositionKind],
  33981. uniforms: ["worldViewProjection", "color"]
  33982. });
  33983. var engine = this._scene.getEngine();
  33984. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  33985. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  33986. 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]);
  33987. };
  33988. BoundingBoxRenderer.prototype.reset = function () {
  33989. this.renderList.reset();
  33990. };
  33991. BoundingBoxRenderer.prototype.render = function () {
  33992. if (this.renderList.length === 0) {
  33993. return;
  33994. }
  33995. this._prepareRessources();
  33996. if (!this._colorShader.isReady()) {
  33997. return;
  33998. }
  33999. var engine = this._scene.getEngine();
  34000. engine.setDepthWrite(false);
  34001. this._colorShader._preBind();
  34002. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  34003. var boundingBox = this.renderList.data[boundingBoxIndex];
  34004. var min = boundingBox.minimum;
  34005. var max = boundingBox.maximum;
  34006. var diff = max.subtract(min);
  34007. var median = min.add(diff.scale(0.5));
  34008. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  34009. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  34010. .multiply(boundingBox.getWorldMatrix());
  34011. // VBOs
  34012. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  34013. if (this.showBackLines) {
  34014. // Back
  34015. engine.setDepthFunctionToGreaterOrEqual();
  34016. this._scene.resetCachedMaterial();
  34017. this._colorShader.setColor4("color", this.backColor.toColor4());
  34018. this._colorShader.bind(worldMatrix);
  34019. // Draw order
  34020. engine.draw(false, 0, 24);
  34021. }
  34022. // Front
  34023. engine.setDepthFunctionToLess();
  34024. this._scene.resetCachedMaterial();
  34025. this._colorShader.setColor4("color", this.frontColor.toColor4());
  34026. this._colorShader.bind(worldMatrix);
  34027. // Draw order
  34028. engine.draw(false, 0, 24);
  34029. }
  34030. this._colorShader.unbind();
  34031. engine.setDepthFunctionToLessOrEqual();
  34032. engine.setDepthWrite(true);
  34033. };
  34034. BoundingBoxRenderer.prototype.dispose = function () {
  34035. if (!this._colorShader) {
  34036. return;
  34037. }
  34038. this._colorShader.dispose();
  34039. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34040. if (buffer) {
  34041. buffer.dispose();
  34042. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34043. }
  34044. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34045. };
  34046. return BoundingBoxRenderer;
  34047. }());
  34048. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  34049. })(BABYLON || (BABYLON = {}));
  34050. var BABYLON;
  34051. (function (BABYLON) {
  34052. var Condition = (function () {
  34053. function Condition(actionManager) {
  34054. this._actionManager = actionManager;
  34055. }
  34056. Condition.prototype.isValid = function () {
  34057. return true;
  34058. };
  34059. Condition.prototype._getProperty = function (propertyPath) {
  34060. return this._actionManager._getProperty(propertyPath);
  34061. };
  34062. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  34063. return this._actionManager._getEffectiveTarget(target, propertyPath);
  34064. };
  34065. Condition.prototype.serialize = function () {
  34066. };
  34067. Condition.prototype._serialize = function (serializedCondition) {
  34068. return {
  34069. type: 2,
  34070. children: [],
  34071. name: serializedCondition.name,
  34072. properties: serializedCondition.properties
  34073. };
  34074. };
  34075. return Condition;
  34076. }());
  34077. BABYLON.Condition = Condition;
  34078. var ValueCondition = (function (_super) {
  34079. __extends(ValueCondition, _super);
  34080. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  34081. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  34082. _super.call(this, actionManager);
  34083. this.propertyPath = propertyPath;
  34084. this.value = value;
  34085. this.operator = operator;
  34086. this._target = target;
  34087. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  34088. this._property = this._getProperty(this.propertyPath);
  34089. }
  34090. Object.defineProperty(ValueCondition, "IsEqual", {
  34091. get: function () {
  34092. return ValueCondition._IsEqual;
  34093. },
  34094. enumerable: true,
  34095. configurable: true
  34096. });
  34097. Object.defineProperty(ValueCondition, "IsDifferent", {
  34098. get: function () {
  34099. return ValueCondition._IsDifferent;
  34100. },
  34101. enumerable: true,
  34102. configurable: true
  34103. });
  34104. Object.defineProperty(ValueCondition, "IsGreater", {
  34105. get: function () {
  34106. return ValueCondition._IsGreater;
  34107. },
  34108. enumerable: true,
  34109. configurable: true
  34110. });
  34111. Object.defineProperty(ValueCondition, "IsLesser", {
  34112. get: function () {
  34113. return ValueCondition._IsLesser;
  34114. },
  34115. enumerable: true,
  34116. configurable: true
  34117. });
  34118. // Methods
  34119. ValueCondition.prototype.isValid = function () {
  34120. switch (this.operator) {
  34121. case ValueCondition.IsGreater:
  34122. return this._effectiveTarget[this._property] > this.value;
  34123. case ValueCondition.IsLesser:
  34124. return this._effectiveTarget[this._property] < this.value;
  34125. case ValueCondition.IsEqual:
  34126. case ValueCondition.IsDifferent:
  34127. var check;
  34128. if (this.value.equals) {
  34129. check = this.value.equals(this._effectiveTarget[this._property]);
  34130. }
  34131. else {
  34132. check = this.value === this._effectiveTarget[this._property];
  34133. }
  34134. return this.operator === ValueCondition.IsEqual ? check : !check;
  34135. }
  34136. return false;
  34137. };
  34138. ValueCondition.prototype.serialize = function () {
  34139. return this._serialize({
  34140. name: "ValueCondition",
  34141. properties: [
  34142. BABYLON.Action._GetTargetProperty(this._target),
  34143. { name: "propertyPath", value: this.propertyPath },
  34144. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  34145. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  34146. ]
  34147. });
  34148. };
  34149. ValueCondition.GetOperatorName = function (operator) {
  34150. switch (operator) {
  34151. case ValueCondition._IsEqual: return "IsEqual";
  34152. case ValueCondition._IsDifferent: return "IsDifferent";
  34153. case ValueCondition._IsGreater: return "IsGreater";
  34154. case ValueCondition._IsLesser: return "IsLesser";
  34155. default: return "";
  34156. }
  34157. };
  34158. // Statics
  34159. ValueCondition._IsEqual = 0;
  34160. ValueCondition._IsDifferent = 1;
  34161. ValueCondition._IsGreater = 2;
  34162. ValueCondition._IsLesser = 3;
  34163. return ValueCondition;
  34164. }(Condition));
  34165. BABYLON.ValueCondition = ValueCondition;
  34166. var PredicateCondition = (function (_super) {
  34167. __extends(PredicateCondition, _super);
  34168. function PredicateCondition(actionManager, predicate) {
  34169. _super.call(this, actionManager);
  34170. this.predicate = predicate;
  34171. }
  34172. PredicateCondition.prototype.isValid = function () {
  34173. return this.predicate();
  34174. };
  34175. return PredicateCondition;
  34176. }(Condition));
  34177. BABYLON.PredicateCondition = PredicateCondition;
  34178. var StateCondition = (function (_super) {
  34179. __extends(StateCondition, _super);
  34180. function StateCondition(actionManager, target, value) {
  34181. _super.call(this, actionManager);
  34182. this.value = value;
  34183. this._target = target;
  34184. }
  34185. // Methods
  34186. StateCondition.prototype.isValid = function () {
  34187. return this._target.state === this.value;
  34188. };
  34189. StateCondition.prototype.serialize = function () {
  34190. return this._serialize({
  34191. name: "StateCondition",
  34192. properties: [
  34193. BABYLON.Action._GetTargetProperty(this._target),
  34194. { name: "value", value: this.value }
  34195. ]
  34196. });
  34197. };
  34198. return StateCondition;
  34199. }(Condition));
  34200. BABYLON.StateCondition = StateCondition;
  34201. })(BABYLON || (BABYLON = {}));
  34202. var BABYLON;
  34203. (function (BABYLON) {
  34204. var Action = (function () {
  34205. function Action(triggerOptions, condition) {
  34206. this.triggerOptions = triggerOptions;
  34207. if (triggerOptions.parameter) {
  34208. this.trigger = triggerOptions.trigger;
  34209. this._triggerParameter = triggerOptions.parameter;
  34210. }
  34211. else {
  34212. this.trigger = triggerOptions;
  34213. }
  34214. this._nextActiveAction = this;
  34215. this._condition = condition;
  34216. }
  34217. // Methods
  34218. Action.prototype._prepare = function () {
  34219. };
  34220. Action.prototype.getTriggerParameter = function () {
  34221. return this._triggerParameter;
  34222. };
  34223. Action.prototype._executeCurrent = function (evt) {
  34224. if (this._nextActiveAction._condition) {
  34225. var condition = this._nextActiveAction._condition;
  34226. var currentRenderId = this._actionManager.getScene().getRenderId();
  34227. // We cache the current evaluation for the current frame
  34228. if (condition._evaluationId === currentRenderId) {
  34229. if (!condition._currentResult) {
  34230. return;
  34231. }
  34232. }
  34233. else {
  34234. condition._evaluationId = currentRenderId;
  34235. if (!condition.isValid()) {
  34236. condition._currentResult = false;
  34237. return;
  34238. }
  34239. condition._currentResult = true;
  34240. }
  34241. }
  34242. this._nextActiveAction.execute(evt);
  34243. this.skipToNextActiveAction();
  34244. };
  34245. Action.prototype.execute = function (evt) {
  34246. };
  34247. Action.prototype.skipToNextActiveAction = function () {
  34248. if (this._nextActiveAction._child) {
  34249. if (!this._nextActiveAction._child._actionManager) {
  34250. this._nextActiveAction._child._actionManager = this._actionManager;
  34251. }
  34252. this._nextActiveAction = this._nextActiveAction._child;
  34253. }
  34254. else {
  34255. this._nextActiveAction = this;
  34256. }
  34257. };
  34258. Action.prototype.then = function (action) {
  34259. this._child = action;
  34260. action._actionManager = this._actionManager;
  34261. action._prepare();
  34262. return action;
  34263. };
  34264. Action.prototype._getProperty = function (propertyPath) {
  34265. return this._actionManager._getProperty(propertyPath);
  34266. };
  34267. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  34268. return this._actionManager._getEffectiveTarget(target, propertyPath);
  34269. };
  34270. Action.prototype.serialize = function (parent) {
  34271. };
  34272. // Called by BABYLON.Action objects in serialize(...). Internal use
  34273. Action.prototype._serialize = function (serializedAction, parent) {
  34274. var serializationObject = {
  34275. type: 1,
  34276. children: [],
  34277. name: serializedAction.name,
  34278. properties: serializedAction.properties || []
  34279. };
  34280. // Serialize child
  34281. if (this._child) {
  34282. this._child.serialize(serializationObject);
  34283. }
  34284. // Check if "this" has a condition
  34285. if (this._condition) {
  34286. var serializedCondition = this._condition.serialize();
  34287. serializedCondition.children.push(serializationObject);
  34288. if (parent) {
  34289. parent.children.push(serializedCondition);
  34290. }
  34291. return serializedCondition;
  34292. }
  34293. if (parent) {
  34294. parent.children.push(serializationObject);
  34295. }
  34296. return serializationObject;
  34297. };
  34298. Action._SerializeValueAsString = function (value) {
  34299. if (typeof value === "number") {
  34300. return value.toString();
  34301. }
  34302. if (typeof value === "boolean") {
  34303. return value ? "true" : "false";
  34304. }
  34305. if (value instanceof BABYLON.Vector2) {
  34306. return value.x + ", " + value.y;
  34307. }
  34308. if (value instanceof BABYLON.Vector3) {
  34309. return value.x + ", " + value.y + ", " + value.z;
  34310. }
  34311. if (value instanceof BABYLON.Color3) {
  34312. return value.r + ", " + value.g + ", " + value.b;
  34313. }
  34314. if (value instanceof BABYLON.Color4) {
  34315. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  34316. }
  34317. return value; // string
  34318. };
  34319. Action._GetTargetProperty = function (target) {
  34320. return {
  34321. name: "target",
  34322. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  34323. : target instanceof BABYLON.Light ? "LightProperties"
  34324. : target instanceof BABYLON.Camera ? "CameraProperties"
  34325. : "SceneProperties",
  34326. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  34327. };
  34328. };
  34329. return Action;
  34330. }());
  34331. BABYLON.Action = Action;
  34332. })(BABYLON || (BABYLON = {}));
  34333. var BABYLON;
  34334. (function (BABYLON) {
  34335. /**
  34336. * ActionEvent is the event beint sent when an action is triggered.
  34337. */
  34338. var ActionEvent = (function () {
  34339. /**
  34340. * @constructor
  34341. * @param source The mesh or sprite that triggered the action.
  34342. * @param pointerX The X mouse cursor position at the time of the event
  34343. * @param pointerY The Y mouse cursor position at the time of the event
  34344. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  34345. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  34346. */
  34347. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  34348. this.source = source;
  34349. this.pointerX = pointerX;
  34350. this.pointerY = pointerY;
  34351. this.meshUnderPointer = meshUnderPointer;
  34352. this.sourceEvent = sourceEvent;
  34353. this.additionalData = additionalData;
  34354. }
  34355. /**
  34356. * Helper function to auto-create an ActionEvent from a source mesh.
  34357. * @param source The source mesh that triggered the event
  34358. * @param evt {Event} The original (browser) event
  34359. */
  34360. ActionEvent.CreateNew = function (source, evt, additionalData) {
  34361. var scene = source.getScene();
  34362. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  34363. };
  34364. /**
  34365. * Helper function to auto-create an ActionEvent from a source mesh.
  34366. * @param source The source sprite that triggered the event
  34367. * @param scene Scene associated with the sprite
  34368. * @param evt {Event} The original (browser) event
  34369. */
  34370. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  34371. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  34372. };
  34373. /**
  34374. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  34375. * @param scene the scene where the event occurred
  34376. * @param evt {Event} The original (browser) event
  34377. */
  34378. ActionEvent.CreateNewFromScene = function (scene, evt) {
  34379. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  34380. };
  34381. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  34382. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  34383. };
  34384. return ActionEvent;
  34385. }());
  34386. BABYLON.ActionEvent = ActionEvent;
  34387. /**
  34388. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  34389. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  34390. */
  34391. var ActionManager = (function () {
  34392. function ActionManager(scene) {
  34393. // Members
  34394. this.actions = new Array();
  34395. this.hoverCursor = '';
  34396. this._scene = scene;
  34397. scene._actionManagers.push(this);
  34398. }
  34399. Object.defineProperty(ActionManager, "NothingTrigger", {
  34400. get: function () {
  34401. return ActionManager._NothingTrigger;
  34402. },
  34403. enumerable: true,
  34404. configurable: true
  34405. });
  34406. Object.defineProperty(ActionManager, "OnPickTrigger", {
  34407. get: function () {
  34408. return ActionManager._OnPickTrigger;
  34409. },
  34410. enumerable: true,
  34411. configurable: true
  34412. });
  34413. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  34414. get: function () {
  34415. return ActionManager._OnLeftPickTrigger;
  34416. },
  34417. enumerable: true,
  34418. configurable: true
  34419. });
  34420. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  34421. get: function () {
  34422. return ActionManager._OnRightPickTrigger;
  34423. },
  34424. enumerable: true,
  34425. configurable: true
  34426. });
  34427. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  34428. get: function () {
  34429. return ActionManager._OnCenterPickTrigger;
  34430. },
  34431. enumerable: true,
  34432. configurable: true
  34433. });
  34434. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  34435. get: function () {
  34436. return ActionManager._OnPickDownTrigger;
  34437. },
  34438. enumerable: true,
  34439. configurable: true
  34440. });
  34441. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  34442. get: function () {
  34443. return ActionManager._OnPickUpTrigger;
  34444. },
  34445. enumerable: true,
  34446. configurable: true
  34447. });
  34448. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  34449. /// This trigger will only be raised if you also declared a OnPickDown
  34450. get: function () {
  34451. return ActionManager._OnPickOutTrigger;
  34452. },
  34453. enumerable: true,
  34454. configurable: true
  34455. });
  34456. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  34457. get: function () {
  34458. return ActionManager._OnLongPressTrigger;
  34459. },
  34460. enumerable: true,
  34461. configurable: true
  34462. });
  34463. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  34464. get: function () {
  34465. return ActionManager._OnPointerOverTrigger;
  34466. },
  34467. enumerable: true,
  34468. configurable: true
  34469. });
  34470. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  34471. get: function () {
  34472. return ActionManager._OnPointerOutTrigger;
  34473. },
  34474. enumerable: true,
  34475. configurable: true
  34476. });
  34477. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  34478. get: function () {
  34479. return ActionManager._OnEveryFrameTrigger;
  34480. },
  34481. enumerable: true,
  34482. configurable: true
  34483. });
  34484. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  34485. get: function () {
  34486. return ActionManager._OnIntersectionEnterTrigger;
  34487. },
  34488. enumerable: true,
  34489. configurable: true
  34490. });
  34491. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  34492. get: function () {
  34493. return ActionManager._OnIntersectionExitTrigger;
  34494. },
  34495. enumerable: true,
  34496. configurable: true
  34497. });
  34498. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  34499. get: function () {
  34500. return ActionManager._OnKeyDownTrigger;
  34501. },
  34502. enumerable: true,
  34503. configurable: true
  34504. });
  34505. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  34506. get: function () {
  34507. return ActionManager._OnKeyUpTrigger;
  34508. },
  34509. enumerable: true,
  34510. configurable: true
  34511. });
  34512. // Methods
  34513. ActionManager.prototype.dispose = function () {
  34514. var index = this._scene._actionManagers.indexOf(this);
  34515. if (index > -1) {
  34516. this._scene._actionManagers.splice(index, 1);
  34517. }
  34518. };
  34519. ActionManager.prototype.getScene = function () {
  34520. return this._scene;
  34521. };
  34522. /**
  34523. * Does this action manager handles actions of any of the given triggers
  34524. * @param {number[]} triggers - the triggers to be tested
  34525. * @return {boolean} whether one (or more) of the triggers is handeled
  34526. */
  34527. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  34528. for (var index = 0; index < this.actions.length; index++) {
  34529. var action = this.actions[index];
  34530. if (triggers.indexOf(action.trigger) > -1) {
  34531. return true;
  34532. }
  34533. }
  34534. return false;
  34535. };
  34536. /**
  34537. * Does this action manager handles actions of a given trigger
  34538. * @param {number} trigger - the trigger to be tested
  34539. * @return {boolean} whether the trigger is handeled
  34540. */
  34541. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  34542. for (var index = 0; index < this.actions.length; index++) {
  34543. var action = this.actions[index];
  34544. if (action.trigger === trigger) {
  34545. return true;
  34546. }
  34547. }
  34548. return false;
  34549. };
  34550. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  34551. /**
  34552. * Does this action manager has pointer triggers
  34553. * @return {boolean} whether or not it has pointer triggers
  34554. */
  34555. get: function () {
  34556. for (var index = 0; index < this.actions.length; index++) {
  34557. var action = this.actions[index];
  34558. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  34559. return true;
  34560. }
  34561. }
  34562. return false;
  34563. },
  34564. enumerable: true,
  34565. configurable: true
  34566. });
  34567. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  34568. /**
  34569. * Does this action manager has pick triggers
  34570. * @return {boolean} whether or not it has pick triggers
  34571. */
  34572. get: function () {
  34573. for (var index = 0; index < this.actions.length; index++) {
  34574. var action = this.actions[index];
  34575. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  34576. return true;
  34577. }
  34578. }
  34579. return false;
  34580. },
  34581. enumerable: true,
  34582. configurable: true
  34583. });
  34584. /**
  34585. * Registers an action to this action manager
  34586. * @param {BABYLON.Action} action - the action to be registered
  34587. * @return {BABYLON.Action} the action amended (prepared) after registration
  34588. */
  34589. ActionManager.prototype.registerAction = function (action) {
  34590. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  34591. if (this.getScene().actionManager !== this) {
  34592. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  34593. return null;
  34594. }
  34595. }
  34596. this.actions.push(action);
  34597. action._actionManager = this;
  34598. action._prepare();
  34599. return action;
  34600. };
  34601. /**
  34602. * Process a specific trigger
  34603. * @param {number} trigger - the trigger to process
  34604. * @param evt {BABYLON.ActionEvent} the event details to be processed
  34605. */
  34606. ActionManager.prototype.processTrigger = function (trigger, evt) {
  34607. for (var index = 0; index < this.actions.length; index++) {
  34608. var action = this.actions[index];
  34609. if (action.trigger === trigger) {
  34610. if (trigger === ActionManager.OnKeyUpTrigger
  34611. || trigger === ActionManager.OnKeyDownTrigger) {
  34612. var parameter = action.getTriggerParameter();
  34613. if (parameter) {
  34614. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  34615. var actualkey = String.fromCharCode(unicode).toLowerCase();
  34616. if (actualkey !== parameter.toLowerCase()) {
  34617. continue;
  34618. }
  34619. }
  34620. }
  34621. action._executeCurrent(evt);
  34622. }
  34623. }
  34624. };
  34625. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  34626. var properties = propertyPath.split(".");
  34627. for (var index = 0; index < properties.length - 1; index++) {
  34628. target = target[properties[index]];
  34629. }
  34630. return target;
  34631. };
  34632. ActionManager.prototype._getProperty = function (propertyPath) {
  34633. var properties = propertyPath.split(".");
  34634. return properties[properties.length - 1];
  34635. };
  34636. ActionManager.prototype.serialize = function (name) {
  34637. var root = {
  34638. children: [],
  34639. name: name,
  34640. type: 3,
  34641. properties: [] // Empty for root but required
  34642. };
  34643. for (var i = 0; i < this.actions.length; i++) {
  34644. var triggerObject = {
  34645. type: 0,
  34646. children: [],
  34647. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  34648. properties: []
  34649. };
  34650. var triggerOptions = this.actions[i].triggerOptions;
  34651. if (triggerOptions && typeof triggerOptions !== "number") {
  34652. if (triggerOptions.parameter instanceof BABYLON.Node) {
  34653. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  34654. }
  34655. else {
  34656. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  34657. }
  34658. }
  34659. // Serialize child action, recursively
  34660. this.actions[i].serialize(triggerObject);
  34661. // Add serialized trigger
  34662. root.children.push(triggerObject);
  34663. }
  34664. return root;
  34665. };
  34666. ActionManager.Parse = function (parsedActions, object, scene) {
  34667. var actionManager = new BABYLON.ActionManager(scene);
  34668. if (object === null)
  34669. scene.actionManager = actionManager;
  34670. else
  34671. object.actionManager = actionManager;
  34672. // instanciate a new object
  34673. var instanciate = function (name, params) {
  34674. var newInstance = Object.create(BABYLON[name].prototype);
  34675. newInstance.constructor.apply(newInstance, params);
  34676. return newInstance;
  34677. };
  34678. var parseParameter = function (name, value, target, propertyPath) {
  34679. if (propertyPath === null) {
  34680. // String, boolean or float
  34681. var floatValue = parseFloat(value);
  34682. if (value === "true" || value === "false")
  34683. return value === "true";
  34684. else
  34685. return isNaN(floatValue) ? value : floatValue;
  34686. }
  34687. var effectiveTarget = propertyPath.split(".");
  34688. var values = value.split(",");
  34689. // Get effective Target
  34690. for (var i = 0; i < effectiveTarget.length; i++) {
  34691. target = target[effectiveTarget[i]];
  34692. }
  34693. // Return appropriate value with its type
  34694. if (typeof (target) === "boolean")
  34695. return values[0] === "true";
  34696. if (typeof (target) === "string")
  34697. return values[0];
  34698. // Parameters with multiple values such as Vector3 etc.
  34699. var split = new Array();
  34700. for (var i = 0; i < values.length; i++)
  34701. split.push(parseFloat(values[i]));
  34702. if (target instanceof BABYLON.Vector3)
  34703. return BABYLON.Vector3.FromArray(split);
  34704. if (target instanceof BABYLON.Vector4)
  34705. return BABYLON.Vector4.FromArray(split);
  34706. if (target instanceof BABYLON.Color3)
  34707. return BABYLON.Color3.FromArray(split);
  34708. if (target instanceof BABYLON.Color4)
  34709. return BABYLON.Color4.FromArray(split);
  34710. return parseFloat(values[0]);
  34711. };
  34712. // traverse graph per trigger
  34713. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  34714. if (combineArray === void 0) { combineArray = null; }
  34715. if (parsedAction.detached)
  34716. return;
  34717. var parameters = new Array();
  34718. var target = null;
  34719. var propertyPath = null;
  34720. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  34721. // Parameters
  34722. if (parsedAction.type === 2)
  34723. parameters.push(actionManager);
  34724. else
  34725. parameters.push(trigger);
  34726. if (combine) {
  34727. var actions = new Array();
  34728. for (var j = 0; j < parsedAction.combine.length; j++) {
  34729. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  34730. }
  34731. parameters.push(actions);
  34732. }
  34733. else {
  34734. for (var i = 0; i < parsedAction.properties.length; i++) {
  34735. var value = parsedAction.properties[i].value;
  34736. var name = parsedAction.properties[i].name;
  34737. var targetType = parsedAction.properties[i].targetType;
  34738. if (name === "target")
  34739. if (targetType !== null && targetType === "SceneProperties")
  34740. value = target = scene;
  34741. else
  34742. value = target = scene.getNodeByName(value);
  34743. else if (name === "parent")
  34744. value = scene.getNodeByName(value);
  34745. else if (name === "sound")
  34746. value = scene.getSoundByName(value);
  34747. else if (name !== "propertyPath") {
  34748. if (parsedAction.type === 2 && name === "operator")
  34749. value = BABYLON.ValueCondition[value];
  34750. else
  34751. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  34752. }
  34753. else {
  34754. propertyPath = value;
  34755. }
  34756. parameters.push(value);
  34757. }
  34758. }
  34759. if (combineArray === null) {
  34760. parameters.push(condition);
  34761. }
  34762. else {
  34763. parameters.push(null);
  34764. }
  34765. // If interpolate value action
  34766. if (parsedAction.name === "InterpolateValueAction") {
  34767. var param = parameters[parameters.length - 2];
  34768. parameters[parameters.length - 1] = param;
  34769. parameters[parameters.length - 2] = condition;
  34770. }
  34771. // Action or condition(s) and not CombineAction
  34772. var newAction = instanciate(parsedAction.name, parameters);
  34773. if (newAction instanceof BABYLON.Condition && condition !== null) {
  34774. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  34775. if (action)
  34776. action.then(nothing);
  34777. else
  34778. actionManager.registerAction(nothing);
  34779. action = nothing;
  34780. }
  34781. if (combineArray === null) {
  34782. if (newAction instanceof BABYLON.Condition) {
  34783. condition = newAction;
  34784. newAction = action;
  34785. }
  34786. else {
  34787. condition = null;
  34788. if (action)
  34789. action.then(newAction);
  34790. else
  34791. actionManager.registerAction(newAction);
  34792. }
  34793. }
  34794. else {
  34795. combineArray.push(newAction);
  34796. }
  34797. for (var i = 0; i < parsedAction.children.length; i++)
  34798. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  34799. };
  34800. // triggers
  34801. for (var i = 0; i < parsedActions.children.length; i++) {
  34802. var triggerParams;
  34803. var trigger = parsedActions.children[i];
  34804. if (trigger.properties.length > 0) {
  34805. var param = trigger.properties[0].value;
  34806. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  34807. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  34808. }
  34809. else
  34810. triggerParams = BABYLON.ActionManager[trigger.name];
  34811. for (var j = 0; j < trigger.children.length; j++) {
  34812. if (!trigger.detached)
  34813. traverse(trigger.children[j], triggerParams, null, null);
  34814. }
  34815. }
  34816. };
  34817. ActionManager.GetTriggerName = function (trigger) {
  34818. switch (trigger) {
  34819. case 0: return "NothingTrigger";
  34820. case 1: return "OnPickTrigger";
  34821. case 2: return "OnLeftPickTrigger";
  34822. case 3: return "OnRightPickTrigger";
  34823. case 4: return "OnCenterPickTrigger";
  34824. case 5: return "OnPickDownTrigger";
  34825. case 6: return "OnPickUpTrigger";
  34826. case 7: return "OnLongPressTrigger";
  34827. case 8: return "OnPointerOverTrigger";
  34828. case 9: return "OnPointerOutTrigger";
  34829. case 10: return "OnEveryFrameTrigger";
  34830. case 11: return "OnIntersectionEnterTrigger";
  34831. case 12: return "OnIntersectionExitTrigger";
  34832. case 13: return "OnKeyDownTrigger";
  34833. case 14: return "OnKeyUpTrigger";
  34834. case 15: return "OnPickOutTrigger";
  34835. default: return "";
  34836. }
  34837. };
  34838. // Statics
  34839. ActionManager._NothingTrigger = 0;
  34840. ActionManager._OnPickTrigger = 1;
  34841. ActionManager._OnLeftPickTrigger = 2;
  34842. ActionManager._OnRightPickTrigger = 3;
  34843. ActionManager._OnCenterPickTrigger = 4;
  34844. ActionManager._OnPickDownTrigger = 5;
  34845. ActionManager._OnPickUpTrigger = 6;
  34846. ActionManager._OnLongPressTrigger = 7;
  34847. ActionManager._OnPointerOverTrigger = 8;
  34848. ActionManager._OnPointerOutTrigger = 9;
  34849. ActionManager._OnEveryFrameTrigger = 10;
  34850. ActionManager._OnIntersectionEnterTrigger = 11;
  34851. ActionManager._OnIntersectionExitTrigger = 12;
  34852. ActionManager._OnKeyDownTrigger = 13;
  34853. ActionManager._OnKeyUpTrigger = 14;
  34854. ActionManager._OnPickOutTrigger = 15;
  34855. ActionManager.DragMovementThreshold = 10; // in pixels
  34856. ActionManager.LongPressDelay = 500; // in milliseconds
  34857. return ActionManager;
  34858. }());
  34859. BABYLON.ActionManager = ActionManager;
  34860. })(BABYLON || (BABYLON = {}));
  34861. var BABYLON;
  34862. (function (BABYLON) {
  34863. var InterpolateValueAction = (function (_super) {
  34864. __extends(InterpolateValueAction, _super);
  34865. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  34866. if (duration === void 0) { duration = 1000; }
  34867. _super.call(this, triggerOptions, condition);
  34868. this.propertyPath = propertyPath;
  34869. this.value = value;
  34870. this.duration = duration;
  34871. this.stopOtherAnimations = stopOtherAnimations;
  34872. this.onInterpolationDone = onInterpolationDone;
  34873. this._target = this._effectiveTarget = target;
  34874. }
  34875. InterpolateValueAction.prototype._prepare = function () {
  34876. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34877. this._property = this._getProperty(this.propertyPath);
  34878. };
  34879. InterpolateValueAction.prototype.execute = function () {
  34880. var scene = this._actionManager.getScene();
  34881. var keys = [
  34882. {
  34883. frame: 0,
  34884. value: this._effectiveTarget[this._property]
  34885. }, {
  34886. frame: 100,
  34887. value: this.value
  34888. }
  34889. ];
  34890. var dataType;
  34891. if (typeof this.value === "number") {
  34892. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  34893. }
  34894. else if (this.value instanceof BABYLON.Color3) {
  34895. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  34896. }
  34897. else if (this.value instanceof BABYLON.Vector3) {
  34898. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  34899. }
  34900. else if (this.value instanceof BABYLON.Matrix) {
  34901. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  34902. }
  34903. else if (this.value instanceof BABYLON.Quaternion) {
  34904. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  34905. }
  34906. else {
  34907. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  34908. return;
  34909. }
  34910. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  34911. animation.setKeys(keys);
  34912. if (this.stopOtherAnimations) {
  34913. scene.stopAnimation(this._effectiveTarget);
  34914. }
  34915. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  34916. };
  34917. InterpolateValueAction.prototype.serialize = function (parent) {
  34918. return _super.prototype._serialize.call(this, {
  34919. name: "InterpolateValueAction",
  34920. properties: [
  34921. BABYLON.Action._GetTargetProperty(this._target),
  34922. { name: "propertyPath", value: this.propertyPath },
  34923. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  34924. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  34925. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  34926. ]
  34927. }, parent);
  34928. };
  34929. return InterpolateValueAction;
  34930. }(BABYLON.Action));
  34931. BABYLON.InterpolateValueAction = InterpolateValueAction;
  34932. })(BABYLON || (BABYLON = {}));
  34933. var BABYLON;
  34934. (function (BABYLON) {
  34935. var SwitchBooleanAction = (function (_super) {
  34936. __extends(SwitchBooleanAction, _super);
  34937. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  34938. _super.call(this, triggerOptions, condition);
  34939. this.propertyPath = propertyPath;
  34940. this._target = this._effectiveTarget = target;
  34941. }
  34942. SwitchBooleanAction.prototype._prepare = function () {
  34943. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34944. this._property = this._getProperty(this.propertyPath);
  34945. };
  34946. SwitchBooleanAction.prototype.execute = function () {
  34947. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  34948. };
  34949. SwitchBooleanAction.prototype.serialize = function (parent) {
  34950. return _super.prototype._serialize.call(this, {
  34951. name: "SwitchBooleanAction",
  34952. properties: [
  34953. BABYLON.Action._GetTargetProperty(this._target),
  34954. { name: "propertyPath", value: this.propertyPath }
  34955. ]
  34956. }, parent);
  34957. };
  34958. return SwitchBooleanAction;
  34959. }(BABYLON.Action));
  34960. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  34961. var SetStateAction = (function (_super) {
  34962. __extends(SetStateAction, _super);
  34963. function SetStateAction(triggerOptions, target, value, condition) {
  34964. _super.call(this, triggerOptions, condition);
  34965. this.value = value;
  34966. this._target = target;
  34967. }
  34968. SetStateAction.prototype.execute = function () {
  34969. this._target.state = this.value;
  34970. };
  34971. SetStateAction.prototype.serialize = function (parent) {
  34972. return _super.prototype._serialize.call(this, {
  34973. name: "SetStateAction",
  34974. properties: [
  34975. BABYLON.Action._GetTargetProperty(this._target),
  34976. { name: "value", value: this.value }
  34977. ]
  34978. }, parent);
  34979. };
  34980. return SetStateAction;
  34981. }(BABYLON.Action));
  34982. BABYLON.SetStateAction = SetStateAction;
  34983. var SetValueAction = (function (_super) {
  34984. __extends(SetValueAction, _super);
  34985. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  34986. _super.call(this, triggerOptions, condition);
  34987. this.propertyPath = propertyPath;
  34988. this.value = value;
  34989. this._target = this._effectiveTarget = target;
  34990. }
  34991. SetValueAction.prototype._prepare = function () {
  34992. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34993. this._property = this._getProperty(this.propertyPath);
  34994. };
  34995. SetValueAction.prototype.execute = function () {
  34996. this._effectiveTarget[this._property] = this.value;
  34997. if (this._target.markAsDirty) {
  34998. this._target.markAsDirty(this._property);
  34999. }
  35000. };
  35001. SetValueAction.prototype.serialize = function (parent) {
  35002. return _super.prototype._serialize.call(this, {
  35003. name: "SetValueAction",
  35004. properties: [
  35005. BABYLON.Action._GetTargetProperty(this._target),
  35006. { name: "propertyPath", value: this.propertyPath },
  35007. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  35008. ]
  35009. }, parent);
  35010. };
  35011. return SetValueAction;
  35012. }(BABYLON.Action));
  35013. BABYLON.SetValueAction = SetValueAction;
  35014. var IncrementValueAction = (function (_super) {
  35015. __extends(IncrementValueAction, _super);
  35016. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  35017. _super.call(this, triggerOptions, condition);
  35018. this.propertyPath = propertyPath;
  35019. this.value = value;
  35020. this._target = this._effectiveTarget = target;
  35021. }
  35022. IncrementValueAction.prototype._prepare = function () {
  35023. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35024. this._property = this._getProperty(this.propertyPath);
  35025. if (typeof this._effectiveTarget[this._property] !== "number") {
  35026. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  35027. }
  35028. };
  35029. IncrementValueAction.prototype.execute = function () {
  35030. this._effectiveTarget[this._property] += this.value;
  35031. if (this._target.markAsDirty) {
  35032. this._target.markAsDirty(this._property);
  35033. }
  35034. };
  35035. IncrementValueAction.prototype.serialize = function (parent) {
  35036. return _super.prototype._serialize.call(this, {
  35037. name: "IncrementValueAction",
  35038. properties: [
  35039. BABYLON.Action._GetTargetProperty(this._target),
  35040. { name: "propertyPath", value: this.propertyPath },
  35041. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  35042. ]
  35043. }, parent);
  35044. };
  35045. return IncrementValueAction;
  35046. }(BABYLON.Action));
  35047. BABYLON.IncrementValueAction = IncrementValueAction;
  35048. var PlayAnimationAction = (function (_super) {
  35049. __extends(PlayAnimationAction, _super);
  35050. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  35051. _super.call(this, triggerOptions, condition);
  35052. this.from = from;
  35053. this.to = to;
  35054. this.loop = loop;
  35055. this._target = target;
  35056. }
  35057. PlayAnimationAction.prototype._prepare = function () {
  35058. };
  35059. PlayAnimationAction.prototype.execute = function () {
  35060. var scene = this._actionManager.getScene();
  35061. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  35062. };
  35063. PlayAnimationAction.prototype.serialize = function (parent) {
  35064. return _super.prototype._serialize.call(this, {
  35065. name: "PlayAnimationAction",
  35066. properties: [
  35067. BABYLON.Action._GetTargetProperty(this._target),
  35068. { name: "from", value: String(this.from) },
  35069. { name: "to", value: String(this.to) },
  35070. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  35071. ]
  35072. }, parent);
  35073. };
  35074. return PlayAnimationAction;
  35075. }(BABYLON.Action));
  35076. BABYLON.PlayAnimationAction = PlayAnimationAction;
  35077. var StopAnimationAction = (function (_super) {
  35078. __extends(StopAnimationAction, _super);
  35079. function StopAnimationAction(triggerOptions, target, condition) {
  35080. _super.call(this, triggerOptions, condition);
  35081. this._target = target;
  35082. }
  35083. StopAnimationAction.prototype._prepare = function () {
  35084. };
  35085. StopAnimationAction.prototype.execute = function () {
  35086. var scene = this._actionManager.getScene();
  35087. scene.stopAnimation(this._target);
  35088. };
  35089. StopAnimationAction.prototype.serialize = function (parent) {
  35090. return _super.prototype._serialize.call(this, {
  35091. name: "StopAnimationAction",
  35092. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  35093. }, parent);
  35094. };
  35095. return StopAnimationAction;
  35096. }(BABYLON.Action));
  35097. BABYLON.StopAnimationAction = StopAnimationAction;
  35098. var DoNothingAction = (function (_super) {
  35099. __extends(DoNothingAction, _super);
  35100. function DoNothingAction(triggerOptions, condition) {
  35101. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  35102. _super.call(this, triggerOptions, condition);
  35103. }
  35104. DoNothingAction.prototype.execute = function () {
  35105. };
  35106. DoNothingAction.prototype.serialize = function (parent) {
  35107. return _super.prototype._serialize.call(this, {
  35108. name: "DoNothingAction",
  35109. properties: []
  35110. }, parent);
  35111. };
  35112. return DoNothingAction;
  35113. }(BABYLON.Action));
  35114. BABYLON.DoNothingAction = DoNothingAction;
  35115. var CombineAction = (function (_super) {
  35116. __extends(CombineAction, _super);
  35117. function CombineAction(triggerOptions, children, condition) {
  35118. _super.call(this, triggerOptions, condition);
  35119. this.children = children;
  35120. }
  35121. CombineAction.prototype._prepare = function () {
  35122. for (var index = 0; index < this.children.length; index++) {
  35123. this.children[index]._actionManager = this._actionManager;
  35124. this.children[index]._prepare();
  35125. }
  35126. };
  35127. CombineAction.prototype.execute = function (evt) {
  35128. for (var index = 0; index < this.children.length; index++) {
  35129. this.children[index].execute(evt);
  35130. }
  35131. };
  35132. CombineAction.prototype.serialize = function (parent) {
  35133. var serializationObject = _super.prototype._serialize.call(this, {
  35134. name: "CombineAction",
  35135. properties: [],
  35136. combine: []
  35137. }, parent);
  35138. for (var i = 0; i < this.children.length; i++) {
  35139. serializationObject.combine.push(this.children[i].serialize(null));
  35140. }
  35141. return serializationObject;
  35142. };
  35143. return CombineAction;
  35144. }(BABYLON.Action));
  35145. BABYLON.CombineAction = CombineAction;
  35146. var ExecuteCodeAction = (function (_super) {
  35147. __extends(ExecuteCodeAction, _super);
  35148. function ExecuteCodeAction(triggerOptions, func, condition) {
  35149. _super.call(this, triggerOptions, condition);
  35150. this.func = func;
  35151. }
  35152. ExecuteCodeAction.prototype.execute = function (evt) {
  35153. this.func(evt);
  35154. };
  35155. return ExecuteCodeAction;
  35156. }(BABYLON.Action));
  35157. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  35158. var SetParentAction = (function (_super) {
  35159. __extends(SetParentAction, _super);
  35160. function SetParentAction(triggerOptions, target, parent, condition) {
  35161. _super.call(this, triggerOptions, condition);
  35162. this._target = target;
  35163. this._parent = parent;
  35164. }
  35165. SetParentAction.prototype._prepare = function () {
  35166. };
  35167. SetParentAction.prototype.execute = function () {
  35168. if (this._target.parent === this._parent) {
  35169. return;
  35170. }
  35171. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  35172. invertParentWorldMatrix.invert();
  35173. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  35174. this._target.parent = this._parent;
  35175. };
  35176. SetParentAction.prototype.serialize = function (parent) {
  35177. return _super.prototype._serialize.call(this, {
  35178. name: "SetParentAction",
  35179. properties: [
  35180. BABYLON.Action._GetTargetProperty(this._target),
  35181. BABYLON.Action._GetTargetProperty(this._parent),
  35182. ]
  35183. }, parent);
  35184. };
  35185. return SetParentAction;
  35186. }(BABYLON.Action));
  35187. BABYLON.SetParentAction = SetParentAction;
  35188. var PlaySoundAction = (function (_super) {
  35189. __extends(PlaySoundAction, _super);
  35190. function PlaySoundAction(triggerOptions, sound, condition) {
  35191. _super.call(this, triggerOptions, condition);
  35192. this._sound = sound;
  35193. }
  35194. PlaySoundAction.prototype._prepare = function () {
  35195. };
  35196. PlaySoundAction.prototype.execute = function () {
  35197. if (this._sound !== undefined)
  35198. this._sound.play();
  35199. };
  35200. PlaySoundAction.prototype.serialize = function (parent) {
  35201. return _super.prototype._serialize.call(this, {
  35202. name: "PlaySoundAction",
  35203. properties: [{ name: "sound", value: this._sound.name }]
  35204. }, parent);
  35205. };
  35206. return PlaySoundAction;
  35207. }(BABYLON.Action));
  35208. BABYLON.PlaySoundAction = PlaySoundAction;
  35209. var StopSoundAction = (function (_super) {
  35210. __extends(StopSoundAction, _super);
  35211. function StopSoundAction(triggerOptions, sound, condition) {
  35212. _super.call(this, triggerOptions, condition);
  35213. this._sound = sound;
  35214. }
  35215. StopSoundAction.prototype._prepare = function () {
  35216. };
  35217. StopSoundAction.prototype.execute = function () {
  35218. if (this._sound !== undefined)
  35219. this._sound.stop();
  35220. };
  35221. StopSoundAction.prototype.serialize = function (parent) {
  35222. return _super.prototype._serialize.call(this, {
  35223. name: "StopSoundAction",
  35224. properties: [{ name: "sound", value: this._sound.name }]
  35225. }, parent);
  35226. };
  35227. return StopSoundAction;
  35228. }(BABYLON.Action));
  35229. BABYLON.StopSoundAction = StopSoundAction;
  35230. })(BABYLON || (BABYLON = {}));
  35231. var BABYLON;
  35232. (function (BABYLON) {
  35233. var Geometry = (function () {
  35234. function Geometry(id, scene, vertexData, updatable, mesh) {
  35235. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35236. this._totalVertices = 0;
  35237. this._isDisposed = false;
  35238. this.id = id;
  35239. this._engine = scene.getEngine();
  35240. this._meshes = [];
  35241. this._scene = scene;
  35242. //Init vertex buffer cache
  35243. this._vertexBuffers = {};
  35244. this._indices = [];
  35245. // vertexData
  35246. if (vertexData) {
  35247. this.setAllVerticesData(vertexData, updatable);
  35248. }
  35249. else {
  35250. this._totalVertices = 0;
  35251. this._indices = [];
  35252. }
  35253. // applyToMesh
  35254. if (mesh) {
  35255. if (mesh instanceof BABYLON.LinesMesh) {
  35256. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  35257. this.updateExtend();
  35258. }
  35259. this.applyToMesh(mesh);
  35260. mesh.computeWorldMatrix(true);
  35261. }
  35262. }
  35263. Object.defineProperty(Geometry.prototype, "boundingBias", {
  35264. /**
  35265. * 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
  35266. * @returns The Bias Vector
  35267. */
  35268. get: function () {
  35269. return this._boundingBias;
  35270. },
  35271. set: function (value) {
  35272. if (this._boundingBias && this._boundingBias.equals(value)) {
  35273. return;
  35274. }
  35275. this._boundingBias = value.clone();
  35276. this.updateBoundingInfo(true, null);
  35277. },
  35278. enumerable: true,
  35279. configurable: true
  35280. });
  35281. Object.defineProperty(Geometry.prototype, "extend", {
  35282. get: function () {
  35283. return this._extend;
  35284. },
  35285. enumerable: true,
  35286. configurable: true
  35287. });
  35288. Geometry.prototype.getScene = function () {
  35289. return this._scene;
  35290. };
  35291. Geometry.prototype.getEngine = function () {
  35292. return this._engine;
  35293. };
  35294. Geometry.prototype.isReady = function () {
  35295. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  35296. };
  35297. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35298. vertexData.applyToGeometry(this, updatable);
  35299. this.notifyUpdate();
  35300. };
  35301. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  35302. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  35303. this.setVerticesBuffer(buffer);
  35304. };
  35305. Geometry.prototype.setVerticesBuffer = function (buffer) {
  35306. var kind = buffer.getKind();
  35307. if (this._vertexBuffers[kind]) {
  35308. this._vertexBuffers[kind].dispose();
  35309. }
  35310. this._vertexBuffers[kind] = buffer;
  35311. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35312. var data = buffer.getData();
  35313. var stride = buffer.getStrideSize();
  35314. this._totalVertices = data.length / stride;
  35315. this.updateExtend(data, stride);
  35316. var meshes = this._meshes;
  35317. var numOfMeshes = meshes.length;
  35318. for (var index = 0; index < numOfMeshes; index++) {
  35319. var mesh = meshes[index];
  35320. mesh._resetPointsArrayCache();
  35321. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35322. mesh._createGlobalSubMesh();
  35323. mesh.computeWorldMatrix(true);
  35324. }
  35325. }
  35326. this.notifyUpdate(kind);
  35327. };
  35328. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35329. var vertexBuffer = this.getVertexBuffer(kind);
  35330. if (!vertexBuffer) {
  35331. return;
  35332. }
  35333. vertexBuffer.updateDirectly(data, offset);
  35334. this.notifyUpdate(kind);
  35335. };
  35336. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35337. var vertexBuffer = this.getVertexBuffer(kind);
  35338. if (!vertexBuffer) {
  35339. return;
  35340. }
  35341. vertexBuffer.update(data);
  35342. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35343. var stride = vertexBuffer.getStrideSize();
  35344. this._totalVertices = data.length / stride;
  35345. this.updateBoundingInfo(updateExtends, data);
  35346. }
  35347. this.notifyUpdate(kind);
  35348. };
  35349. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35350. if (updateExtends) {
  35351. this.updateExtend(data);
  35352. }
  35353. var meshes = this._meshes;
  35354. var numOfMeshes = meshes.length;
  35355. for (var index = 0; index < numOfMeshes; index++) {
  35356. var mesh = meshes[index];
  35357. mesh._resetPointsArrayCache();
  35358. if (updateExtends) {
  35359. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35360. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35361. var subMesh = mesh.subMeshes[subIndex];
  35362. subMesh.refreshBoundingInfo();
  35363. }
  35364. }
  35365. }
  35366. };
  35367. Geometry.prototype.getTotalVertices = function () {
  35368. if (!this.isReady()) {
  35369. return 0;
  35370. }
  35371. return this._totalVertices;
  35372. };
  35373. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  35374. var vertexBuffer = this.getVertexBuffer(kind);
  35375. if (!vertexBuffer) {
  35376. return null;
  35377. }
  35378. var orig = vertexBuffer.getData();
  35379. if (!copyWhenShared || this._meshes.length === 1) {
  35380. return orig;
  35381. }
  35382. else {
  35383. var len = orig.length;
  35384. var copy = [];
  35385. for (var i = 0; i < len; i++) {
  35386. copy.push(orig[i]);
  35387. }
  35388. return copy;
  35389. }
  35390. };
  35391. Geometry.prototype.getVertexBuffer = function (kind) {
  35392. if (!this.isReady()) {
  35393. return null;
  35394. }
  35395. return this._vertexBuffers[kind];
  35396. };
  35397. Geometry.prototype.getVertexBuffers = function () {
  35398. if (!this.isReady()) {
  35399. return null;
  35400. }
  35401. return this._vertexBuffers;
  35402. };
  35403. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35404. if (!this._vertexBuffers) {
  35405. if (this._delayInfo) {
  35406. return this._delayInfo.indexOf(kind) !== -1;
  35407. }
  35408. return false;
  35409. }
  35410. return this._vertexBuffers[kind] !== undefined;
  35411. };
  35412. Geometry.prototype.getVerticesDataKinds = function () {
  35413. var result = [];
  35414. var kind;
  35415. if (!this._vertexBuffers && this._delayInfo) {
  35416. for (kind in this._delayInfo) {
  35417. result.push(kind);
  35418. }
  35419. }
  35420. else {
  35421. for (kind in this._vertexBuffers) {
  35422. result.push(kind);
  35423. }
  35424. }
  35425. return result;
  35426. };
  35427. Geometry.prototype.setIndices = function (indices, totalVertices) {
  35428. if (this._indexBuffer) {
  35429. this._engine._releaseBuffer(this._indexBuffer);
  35430. }
  35431. this._indices = indices;
  35432. if (this._meshes.length !== 0 && this._indices) {
  35433. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35434. }
  35435. if (totalVertices !== undefined) {
  35436. this._totalVertices = totalVertices;
  35437. }
  35438. var meshes = this._meshes;
  35439. var numOfMeshes = meshes.length;
  35440. for (var index = 0; index < numOfMeshes; index++) {
  35441. meshes[index]._createGlobalSubMesh();
  35442. }
  35443. this.notifyUpdate();
  35444. };
  35445. Geometry.prototype.getTotalIndices = function () {
  35446. if (!this.isReady()) {
  35447. return 0;
  35448. }
  35449. return this._indices.length;
  35450. };
  35451. Geometry.prototype.getIndices = function (copyWhenShared) {
  35452. if (!this.isReady()) {
  35453. return null;
  35454. }
  35455. var orig = this._indices;
  35456. if (!copyWhenShared || this._meshes.length === 1) {
  35457. return orig;
  35458. }
  35459. else {
  35460. var len = orig.length;
  35461. var copy = [];
  35462. for (var i = 0; i < len; i++) {
  35463. copy.push(orig[i]);
  35464. }
  35465. return copy;
  35466. }
  35467. };
  35468. Geometry.prototype.getIndexBuffer = function () {
  35469. if (!this.isReady()) {
  35470. return null;
  35471. }
  35472. return this._indexBuffer;
  35473. };
  35474. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35475. var meshes = this._meshes;
  35476. var index = meshes.indexOf(mesh);
  35477. if (index === -1) {
  35478. return;
  35479. }
  35480. for (var kind in this._vertexBuffers) {
  35481. this._vertexBuffers[kind].dispose();
  35482. }
  35483. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  35484. this._indexBuffer = null;
  35485. }
  35486. meshes.splice(index, 1);
  35487. mesh._geometry = null;
  35488. if (meshes.length === 0 && shouldDispose) {
  35489. this.dispose();
  35490. }
  35491. };
  35492. Geometry.prototype.applyToMesh = function (mesh) {
  35493. if (mesh._geometry === this) {
  35494. return;
  35495. }
  35496. var previousGeometry = mesh._geometry;
  35497. if (previousGeometry) {
  35498. previousGeometry.releaseForMesh(mesh);
  35499. }
  35500. var meshes = this._meshes;
  35501. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35502. mesh._geometry = this;
  35503. this._scene.pushGeometry(this);
  35504. meshes.push(mesh);
  35505. if (this.isReady()) {
  35506. this._applyToMesh(mesh);
  35507. }
  35508. else {
  35509. mesh._boundingInfo = this._boundingInfo;
  35510. }
  35511. };
  35512. Geometry.prototype.updateExtend = function (data, stride) {
  35513. if (data === void 0) { data = null; }
  35514. if (!data) {
  35515. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35516. }
  35517. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35518. };
  35519. Geometry.prototype._applyToMesh = function (mesh) {
  35520. var numOfMeshes = this._meshes.length;
  35521. // vertexBuffers
  35522. for (var kind in this._vertexBuffers) {
  35523. if (numOfMeshes === 1) {
  35524. this._vertexBuffers[kind].create();
  35525. }
  35526. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  35527. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35528. mesh._resetPointsArrayCache();
  35529. if (!this._extend) {
  35530. this.updateExtend(this._vertexBuffers[kind].getData());
  35531. }
  35532. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35533. mesh._createGlobalSubMesh();
  35534. //bounding info was just created again, world matrix should be applied again.
  35535. mesh._updateBoundingInfo();
  35536. }
  35537. }
  35538. // indexBuffer
  35539. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35540. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35541. }
  35542. if (this._indexBuffer) {
  35543. this._indexBuffer.references = numOfMeshes;
  35544. }
  35545. };
  35546. Geometry.prototype.notifyUpdate = function (kind) {
  35547. if (this.onGeometryUpdated) {
  35548. this.onGeometryUpdated(this, kind);
  35549. }
  35550. };
  35551. Geometry.prototype.load = function (scene, onLoaded) {
  35552. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35553. return;
  35554. }
  35555. if (this.isReady()) {
  35556. if (onLoaded) {
  35557. onLoaded();
  35558. }
  35559. return;
  35560. }
  35561. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35562. this._queueLoad(scene, onLoaded);
  35563. };
  35564. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35565. var _this = this;
  35566. scene._addPendingData(this);
  35567. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  35568. _this._delayLoadingFunction(JSON.parse(data), _this);
  35569. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35570. _this._delayInfo = [];
  35571. scene._removePendingData(_this);
  35572. var meshes = _this._meshes;
  35573. var numOfMeshes = meshes.length;
  35574. for (var index = 0; index < numOfMeshes; index++) {
  35575. _this._applyToMesh(meshes[index]);
  35576. }
  35577. if (onLoaded) {
  35578. onLoaded();
  35579. }
  35580. }, function () { }, scene.database);
  35581. };
  35582. /**
  35583. * Invert the geometry to move from a right handed system to a left handed one.
  35584. */
  35585. Geometry.prototype.toLeftHanded = function () {
  35586. // Flip faces
  35587. var tIndices = this.getIndices(false);
  35588. if (tIndices != null && tIndices.length > 0) {
  35589. for (var i = 0; i < tIndices.length; i += 3) {
  35590. var tTemp = tIndices[i + 0];
  35591. tIndices[i + 0] = tIndices[i + 2];
  35592. tIndices[i + 2] = tTemp;
  35593. }
  35594. this.setIndices(tIndices);
  35595. }
  35596. // Negate position.z
  35597. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35598. if (tPositions != null && tPositions.length > 0) {
  35599. for (var i = 0; i < tPositions.length; i += 3) {
  35600. tPositions[i + 2] = -tPositions[i + 2];
  35601. }
  35602. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35603. }
  35604. // Negate normal.z
  35605. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35606. if (tNormals != null && tNormals.length > 0) {
  35607. for (var i = 0; i < tNormals.length; i += 3) {
  35608. tNormals[i + 2] = -tNormals[i + 2];
  35609. }
  35610. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35611. }
  35612. };
  35613. Geometry.prototype.isDisposed = function () {
  35614. return this._isDisposed;
  35615. };
  35616. Geometry.prototype.dispose = function () {
  35617. var meshes = this._meshes;
  35618. var numOfMeshes = meshes.length;
  35619. var index;
  35620. for (index = 0; index < numOfMeshes; index++) {
  35621. this.releaseForMesh(meshes[index]);
  35622. }
  35623. this._meshes = [];
  35624. for (var kind in this._vertexBuffers) {
  35625. this._vertexBuffers[kind].dispose();
  35626. }
  35627. this._vertexBuffers = {};
  35628. this._totalVertices = 0;
  35629. if (this._indexBuffer) {
  35630. this._engine._releaseBuffer(this._indexBuffer);
  35631. }
  35632. this._indexBuffer = null;
  35633. this._indices = [];
  35634. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35635. this.delayLoadingFile = null;
  35636. this._delayLoadingFunction = null;
  35637. this._delayInfo = [];
  35638. this._boundingInfo = null;
  35639. this._scene.removeGeometry(this);
  35640. this._isDisposed = true;
  35641. };
  35642. Geometry.prototype.copy = function (id) {
  35643. var vertexData = new BABYLON.VertexData();
  35644. vertexData.indices = [];
  35645. var indices = this.getIndices();
  35646. for (var index = 0; index < indices.length; index++) {
  35647. vertexData.indices.push(indices[index]);
  35648. }
  35649. var updatable = false;
  35650. var stopChecking = false;
  35651. var kind;
  35652. for (kind in this._vertexBuffers) {
  35653. // using slice() to make a copy of the array and not just reference it
  35654. var data = this.getVerticesData(kind);
  35655. if (data instanceof Float32Array) {
  35656. vertexData.set(new Float32Array(data), kind);
  35657. }
  35658. else {
  35659. vertexData.set(data.slice(0), kind);
  35660. }
  35661. if (!stopChecking) {
  35662. updatable = this.getVertexBuffer(kind).isUpdatable();
  35663. stopChecking = !updatable;
  35664. }
  35665. }
  35666. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  35667. geometry.delayLoadState = this.delayLoadState;
  35668. geometry.delayLoadingFile = this.delayLoadingFile;
  35669. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35670. for (kind in this._delayInfo) {
  35671. geometry._delayInfo = geometry._delayInfo || [];
  35672. geometry._delayInfo.push(kind);
  35673. }
  35674. // Bounding info
  35675. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35676. return geometry;
  35677. };
  35678. Geometry.prototype.serialize = function () {
  35679. var serializationObject = {};
  35680. serializationObject.id = this.id;
  35681. if (BABYLON.Tags.HasTags(this)) {
  35682. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35683. }
  35684. return serializationObject;
  35685. };
  35686. Geometry.prototype.serializeVerticeData = function () {
  35687. var serializationObject = this.serialize();
  35688. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35689. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35690. }
  35691. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35692. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35693. }
  35694. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35695. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35696. }
  35697. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35698. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  35699. }
  35700. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35701. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  35702. }
  35703. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35704. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  35705. }
  35706. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35707. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  35708. }
  35709. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35710. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  35711. }
  35712. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35713. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  35714. }
  35715. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35716. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35717. serializationObject.matricesIndices._isExpanded = true;
  35718. }
  35719. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35720. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  35721. }
  35722. serializationObject.indices = this.getIndices();
  35723. return serializationObject;
  35724. };
  35725. // Statics
  35726. Geometry.ExtractFromMesh = function (mesh, id) {
  35727. var geometry = mesh._geometry;
  35728. if (!geometry) {
  35729. return null;
  35730. }
  35731. return geometry.copy(id);
  35732. };
  35733. /**
  35734. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35735. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35736. * Be aware Math.random() could cause collisions, but:
  35737. * "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"
  35738. */
  35739. Geometry.RandomId = function () {
  35740. return BABYLON.Tools.RandomId();
  35741. };
  35742. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  35743. var scene = mesh.getScene();
  35744. // Geometry
  35745. var geometryId = parsedGeometry.geometryId;
  35746. if (geometryId) {
  35747. var geometry = scene.getGeometryByID(geometryId);
  35748. if (geometry) {
  35749. geometry.applyToMesh(mesh);
  35750. }
  35751. }
  35752. else if (parsedGeometry instanceof ArrayBuffer) {
  35753. var binaryInfo = mesh._binaryInfo;
  35754. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35755. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35756. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35757. }
  35758. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35759. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35760. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35761. }
  35762. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35763. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35764. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35765. }
  35766. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35767. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35768. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35769. }
  35770. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35771. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35772. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35773. }
  35774. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35775. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35776. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35777. }
  35778. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35779. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35780. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35781. }
  35782. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35783. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35784. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35785. }
  35786. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35787. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35788. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35789. }
  35790. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35791. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35792. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35793. }
  35794. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35795. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35796. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35797. }
  35798. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35799. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35800. mesh.setIndices(indicesData);
  35801. }
  35802. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35803. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35804. mesh.subMeshes = [];
  35805. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35806. var materialIndex = subMeshesData[(i * 5) + 0];
  35807. var verticesStart = subMeshesData[(i * 5) + 1];
  35808. var verticesCount = subMeshesData[(i * 5) + 2];
  35809. var indexStart = subMeshesData[(i * 5) + 3];
  35810. var indexCount = subMeshesData[(i * 5) + 4];
  35811. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35812. }
  35813. }
  35814. }
  35815. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35816. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  35817. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  35818. if (parsedGeometry.uvs) {
  35819. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  35820. }
  35821. if (parsedGeometry.uvs2) {
  35822. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  35823. }
  35824. if (parsedGeometry.uvs3) {
  35825. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  35826. }
  35827. if (parsedGeometry.uvs4) {
  35828. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  35829. }
  35830. if (parsedGeometry.uvs5) {
  35831. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  35832. }
  35833. if (parsedGeometry.uvs6) {
  35834. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  35835. }
  35836. if (parsedGeometry.colors) {
  35837. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  35838. }
  35839. if (parsedGeometry.matricesIndices) {
  35840. if (!parsedGeometry.matricesIndices._isExpanded) {
  35841. var floatIndices = [];
  35842. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35843. var matricesIndex = parsedGeometry.matricesIndices[i];
  35844. floatIndices.push(matricesIndex & 0x000000FF);
  35845. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35846. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35847. floatIndices.push(matricesIndex >> 24);
  35848. }
  35849. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  35850. }
  35851. else {
  35852. delete parsedGeometry.matricesIndices._isExpanded;
  35853. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  35854. }
  35855. }
  35856. if (parsedGeometry.matricesIndicesExtra) {
  35857. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35858. var floatIndices = [];
  35859. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35860. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35861. floatIndices.push(matricesIndex & 0x000000FF);
  35862. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35863. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35864. floatIndices.push(matricesIndex >> 24);
  35865. }
  35866. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  35867. }
  35868. else {
  35869. delete parsedGeometry.matricesIndices._isExpanded;
  35870. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  35871. }
  35872. }
  35873. if (parsedGeometry.matricesWeights) {
  35874. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  35875. }
  35876. if (parsedGeometry.matricesWeightsExtra) {
  35877. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  35878. }
  35879. mesh.setIndices(parsedGeometry.indices);
  35880. }
  35881. // SubMeshes
  35882. if (parsedGeometry.subMeshes) {
  35883. mesh.subMeshes = [];
  35884. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35885. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35886. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35887. }
  35888. }
  35889. // Flat shading
  35890. if (mesh._shouldGenerateFlatShading) {
  35891. mesh.convertToFlatShadedMesh();
  35892. delete mesh._shouldGenerateFlatShading;
  35893. }
  35894. // Update
  35895. mesh.computeWorldMatrix(true);
  35896. // Octree
  35897. if (scene['_selectionOctree']) {
  35898. scene['_selectionOctree'].addMesh(mesh);
  35899. }
  35900. };
  35901. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35902. if (scene.getGeometryByID(parsedVertexData.id)) {
  35903. return null; // null since geometry could be something else than a box...
  35904. }
  35905. var geometry = new Geometry(parsedVertexData.id, scene);
  35906. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35907. if (parsedVertexData.delayLoadingFile) {
  35908. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35909. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35910. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35911. geometry._delayInfo = [];
  35912. if (parsedVertexData.hasUVs) {
  35913. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35914. }
  35915. if (parsedVertexData.hasUVs2) {
  35916. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35917. }
  35918. if (parsedVertexData.hasUVs3) {
  35919. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35920. }
  35921. if (parsedVertexData.hasUVs4) {
  35922. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35923. }
  35924. if (parsedVertexData.hasUVs5) {
  35925. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35926. }
  35927. if (parsedVertexData.hasUVs6) {
  35928. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35929. }
  35930. if (parsedVertexData.hasColors) {
  35931. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35932. }
  35933. if (parsedVertexData.hasMatricesIndices) {
  35934. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35935. }
  35936. if (parsedVertexData.hasMatricesWeights) {
  35937. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35938. }
  35939. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35940. }
  35941. else {
  35942. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35943. }
  35944. scene.pushGeometry(geometry, true);
  35945. return geometry;
  35946. };
  35947. return Geometry;
  35948. }());
  35949. BABYLON.Geometry = Geometry;
  35950. /////// Primitives //////////////////////////////////////////////
  35951. var Geometry;
  35952. (function (Geometry) {
  35953. var Primitives;
  35954. (function (Primitives) {
  35955. /// Abstract class
  35956. var _Primitive = (function (_super) {
  35957. __extends(_Primitive, _super);
  35958. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  35959. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  35960. this._canBeRegenerated = _canBeRegenerated;
  35961. this._beingRegenerated = true;
  35962. this.regenerate();
  35963. this._beingRegenerated = false;
  35964. }
  35965. _Primitive.prototype.canBeRegenerated = function () {
  35966. return this._canBeRegenerated;
  35967. };
  35968. _Primitive.prototype.regenerate = function () {
  35969. if (!this._canBeRegenerated) {
  35970. return;
  35971. }
  35972. this._beingRegenerated = true;
  35973. this.setAllVerticesData(this._regenerateVertexData(), false);
  35974. this._beingRegenerated = false;
  35975. };
  35976. _Primitive.prototype.asNewGeometry = function (id) {
  35977. return _super.prototype.copy.call(this, id);
  35978. };
  35979. // overrides
  35980. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  35981. if (!this._beingRegenerated) {
  35982. return;
  35983. }
  35984. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35985. };
  35986. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  35987. if (!this._beingRegenerated) {
  35988. return;
  35989. }
  35990. _super.prototype.setVerticesData.call(this, kind, data, false);
  35991. };
  35992. // to override
  35993. // protected
  35994. _Primitive.prototype._regenerateVertexData = function () {
  35995. throw new Error("Abstract method");
  35996. };
  35997. _Primitive.prototype.copy = function (id) {
  35998. throw new Error("Must be overriden in sub-classes.");
  35999. };
  36000. _Primitive.prototype.serialize = function () {
  36001. var serializationObject = _super.prototype.serialize.call(this);
  36002. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36003. return serializationObject;
  36004. };
  36005. return _Primitive;
  36006. }(Geometry));
  36007. Primitives._Primitive = _Primitive;
  36008. var Ribbon = (function (_super) {
  36009. __extends(Ribbon, _super);
  36010. // Members
  36011. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  36012. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36013. _super.call(this, id, scene, canBeRegenerated, mesh);
  36014. this.pathArray = pathArray;
  36015. this.closeArray = closeArray;
  36016. this.closePath = closePath;
  36017. this.offset = offset;
  36018. this.side = side;
  36019. }
  36020. Ribbon.prototype._regenerateVertexData = function () {
  36021. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36022. };
  36023. Ribbon.prototype.copy = function (id) {
  36024. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  36025. };
  36026. return Ribbon;
  36027. }(_Primitive));
  36028. Primitives.Ribbon = Ribbon;
  36029. var Box = (function (_super) {
  36030. __extends(Box, _super);
  36031. // Members
  36032. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  36033. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36034. _super.call(this, id, scene, canBeRegenerated, mesh);
  36035. this.size = size;
  36036. this.side = side;
  36037. }
  36038. Box.prototype._regenerateVertexData = function () {
  36039. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36040. };
  36041. Box.prototype.copy = function (id) {
  36042. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36043. };
  36044. Box.prototype.serialize = function () {
  36045. var serializationObject = _super.prototype.serialize.call(this);
  36046. serializationObject.size = this.size;
  36047. return serializationObject;
  36048. };
  36049. Box.Parse = function (parsedBox, scene) {
  36050. if (scene.getGeometryByID(parsedBox.id)) {
  36051. return null; // null since geometry could be something else than a box...
  36052. }
  36053. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36054. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36055. scene.pushGeometry(box, true);
  36056. return box;
  36057. };
  36058. return Box;
  36059. }(_Primitive));
  36060. Primitives.Box = Box;
  36061. var Sphere = (function (_super) {
  36062. __extends(Sphere, _super);
  36063. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  36064. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36065. _super.call(this, id, scene, canBeRegenerated, mesh);
  36066. this.segments = segments;
  36067. this.diameter = diameter;
  36068. this.side = side;
  36069. }
  36070. Sphere.prototype._regenerateVertexData = function () {
  36071. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36072. };
  36073. Sphere.prototype.copy = function (id) {
  36074. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36075. };
  36076. Sphere.prototype.serialize = function () {
  36077. var serializationObject = _super.prototype.serialize.call(this);
  36078. serializationObject.segments = this.segments;
  36079. serializationObject.diameter = this.diameter;
  36080. return serializationObject;
  36081. };
  36082. Sphere.Parse = function (parsedSphere, scene) {
  36083. if (scene.getGeometryByID(parsedSphere.id)) {
  36084. return null; // null since geometry could be something else than a sphere...
  36085. }
  36086. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36087. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36088. scene.pushGeometry(sphere, true);
  36089. return sphere;
  36090. };
  36091. return Sphere;
  36092. }(_Primitive));
  36093. Primitives.Sphere = Sphere;
  36094. var Disc = (function (_super) {
  36095. __extends(Disc, _super);
  36096. // Members
  36097. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  36098. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36099. _super.call(this, id, scene, canBeRegenerated, mesh);
  36100. this.radius = radius;
  36101. this.tessellation = tessellation;
  36102. this.side = side;
  36103. }
  36104. Disc.prototype._regenerateVertexData = function () {
  36105. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36106. };
  36107. Disc.prototype.copy = function (id) {
  36108. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36109. };
  36110. return Disc;
  36111. }(_Primitive));
  36112. Primitives.Disc = Disc;
  36113. var Cylinder = (function (_super) {
  36114. __extends(Cylinder, _super);
  36115. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  36116. if (subdivisions === void 0) { subdivisions = 1; }
  36117. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36118. _super.call(this, id, scene, canBeRegenerated, mesh);
  36119. this.height = height;
  36120. this.diameterTop = diameterTop;
  36121. this.diameterBottom = diameterBottom;
  36122. this.tessellation = tessellation;
  36123. this.subdivisions = subdivisions;
  36124. this.side = side;
  36125. }
  36126. Cylinder.prototype._regenerateVertexData = function () {
  36127. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36128. };
  36129. Cylinder.prototype.copy = function (id) {
  36130. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36131. };
  36132. Cylinder.prototype.serialize = function () {
  36133. var serializationObject = _super.prototype.serialize.call(this);
  36134. serializationObject.height = this.height;
  36135. serializationObject.diameterTop = this.diameterTop;
  36136. serializationObject.diameterBottom = this.diameterBottom;
  36137. serializationObject.tessellation = this.tessellation;
  36138. return serializationObject;
  36139. };
  36140. Cylinder.Parse = function (parsedCylinder, scene) {
  36141. if (scene.getGeometryByID(parsedCylinder.id)) {
  36142. return null; // null since geometry could be something else than a cylinder...
  36143. }
  36144. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36145. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36146. scene.pushGeometry(cylinder, true);
  36147. return cylinder;
  36148. };
  36149. return Cylinder;
  36150. }(_Primitive));
  36151. Primitives.Cylinder = Cylinder;
  36152. var Torus = (function (_super) {
  36153. __extends(Torus, _super);
  36154. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  36155. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36156. _super.call(this, id, scene, canBeRegenerated, mesh);
  36157. this.diameter = diameter;
  36158. this.thickness = thickness;
  36159. this.tessellation = tessellation;
  36160. this.side = side;
  36161. }
  36162. Torus.prototype._regenerateVertexData = function () {
  36163. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36164. };
  36165. Torus.prototype.copy = function (id) {
  36166. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36167. };
  36168. Torus.prototype.serialize = function () {
  36169. var serializationObject = _super.prototype.serialize.call(this);
  36170. serializationObject.diameter = this.diameter;
  36171. serializationObject.thickness = this.thickness;
  36172. serializationObject.tessellation = this.tessellation;
  36173. return serializationObject;
  36174. };
  36175. Torus.Parse = function (parsedTorus, scene) {
  36176. if (scene.getGeometryByID(parsedTorus.id)) {
  36177. return null; // null since geometry could be something else than a torus...
  36178. }
  36179. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36180. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36181. scene.pushGeometry(torus, true);
  36182. return torus;
  36183. };
  36184. return Torus;
  36185. }(_Primitive));
  36186. Primitives.Torus = Torus;
  36187. var Ground = (function (_super) {
  36188. __extends(Ground, _super);
  36189. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  36190. _super.call(this, id, scene, canBeRegenerated, mesh);
  36191. this.width = width;
  36192. this.height = height;
  36193. this.subdivisions = subdivisions;
  36194. }
  36195. Ground.prototype._regenerateVertexData = function () {
  36196. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36197. };
  36198. Ground.prototype.copy = function (id) {
  36199. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36200. };
  36201. Ground.prototype.serialize = function () {
  36202. var serializationObject = _super.prototype.serialize.call(this);
  36203. serializationObject.width = this.width;
  36204. serializationObject.height = this.height;
  36205. serializationObject.subdivisions = this.subdivisions;
  36206. return serializationObject;
  36207. };
  36208. Ground.Parse = function (parsedGround, scene) {
  36209. if (scene.getGeometryByID(parsedGround.id)) {
  36210. return null; // null since geometry could be something else than a ground...
  36211. }
  36212. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36213. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36214. scene.pushGeometry(ground, true);
  36215. return ground;
  36216. };
  36217. return Ground;
  36218. }(_Primitive));
  36219. Primitives.Ground = Ground;
  36220. var TiledGround = (function (_super) {
  36221. __extends(TiledGround, _super);
  36222. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  36223. _super.call(this, id, scene, canBeRegenerated, mesh);
  36224. this.xmin = xmin;
  36225. this.zmin = zmin;
  36226. this.xmax = xmax;
  36227. this.zmax = zmax;
  36228. this.subdivisions = subdivisions;
  36229. this.precision = precision;
  36230. }
  36231. TiledGround.prototype._regenerateVertexData = function () {
  36232. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36233. };
  36234. TiledGround.prototype.copy = function (id) {
  36235. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36236. };
  36237. return TiledGround;
  36238. }(_Primitive));
  36239. Primitives.TiledGround = TiledGround;
  36240. var Plane = (function (_super) {
  36241. __extends(Plane, _super);
  36242. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  36243. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36244. _super.call(this, id, scene, canBeRegenerated, mesh);
  36245. this.size = size;
  36246. this.side = side;
  36247. }
  36248. Plane.prototype._regenerateVertexData = function () {
  36249. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36250. };
  36251. Plane.prototype.copy = function (id) {
  36252. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36253. };
  36254. Plane.prototype.serialize = function () {
  36255. var serializationObject = _super.prototype.serialize.call(this);
  36256. serializationObject.size = this.size;
  36257. return serializationObject;
  36258. };
  36259. Plane.Parse = function (parsedPlane, scene) {
  36260. if (scene.getGeometryByID(parsedPlane.id)) {
  36261. return null; // null since geometry could be something else than a ground...
  36262. }
  36263. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36264. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36265. scene.pushGeometry(plane, true);
  36266. return plane;
  36267. };
  36268. return Plane;
  36269. }(_Primitive));
  36270. Primitives.Plane = Plane;
  36271. var TorusKnot = (function (_super) {
  36272. __extends(TorusKnot, _super);
  36273. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  36274. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36275. _super.call(this, id, scene, canBeRegenerated, mesh);
  36276. this.radius = radius;
  36277. this.tube = tube;
  36278. this.radialSegments = radialSegments;
  36279. this.tubularSegments = tubularSegments;
  36280. this.p = p;
  36281. this.q = q;
  36282. this.side = side;
  36283. }
  36284. TorusKnot.prototype._regenerateVertexData = function () {
  36285. 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 });
  36286. };
  36287. TorusKnot.prototype.copy = function (id) {
  36288. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36289. };
  36290. TorusKnot.prototype.serialize = function () {
  36291. var serializationObject = _super.prototype.serialize.call(this);
  36292. serializationObject.radius = this.radius;
  36293. serializationObject.tube = this.tube;
  36294. serializationObject.radialSegments = this.radialSegments;
  36295. serializationObject.tubularSegments = this.tubularSegments;
  36296. serializationObject.p = this.p;
  36297. serializationObject.q = this.q;
  36298. return serializationObject;
  36299. };
  36300. ;
  36301. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  36302. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36303. return null; // null since geometry could be something else than a ground...
  36304. }
  36305. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36306. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36307. scene.pushGeometry(torusKnot, true);
  36308. return torusKnot;
  36309. };
  36310. return TorusKnot;
  36311. }(_Primitive));
  36312. Primitives.TorusKnot = TorusKnot;
  36313. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  36314. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  36315. })(BABYLON || (BABYLON = {}));
  36316. var BABYLON;
  36317. (function (BABYLON) {
  36318. var GroundMesh = (function (_super) {
  36319. __extends(GroundMesh, _super);
  36320. function GroundMesh(name, scene) {
  36321. _super.call(this, name, scene);
  36322. this.generateOctree = false;
  36323. this._worldInverse = new BABYLON.Matrix();
  36324. }
  36325. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  36326. get: function () {
  36327. return Math.min(this._subdivisionsX, this._subdivisionsY);
  36328. },
  36329. enumerable: true,
  36330. configurable: true
  36331. });
  36332. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  36333. get: function () {
  36334. return this._subdivisionsX;
  36335. },
  36336. enumerable: true,
  36337. configurable: true
  36338. });
  36339. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  36340. get: function () {
  36341. return this._subdivisionsY;
  36342. },
  36343. enumerable: true,
  36344. configurable: true
  36345. });
  36346. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  36347. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  36348. this._subdivisionsX = chunksCount;
  36349. this._subdivisionsY = chunksCount;
  36350. this.subdivide(chunksCount);
  36351. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  36352. };
  36353. /**
  36354. * Returns a height (y) value in the Worl system :
  36355. * the ground altitude at the coordinates (x, z) expressed in the World system.
  36356. * Returns the ground y position if (x, z) are outside the ground surface.
  36357. * Not pertinent if the ground is rotated.
  36358. */
  36359. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  36360. // express x and y in the ground local system
  36361. x -= this.position.x;
  36362. z -= this.position.z;
  36363. x /= this.scaling.x;
  36364. z /= this.scaling.z;
  36365. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  36366. return this.position.y;
  36367. }
  36368. if (!this._heightQuads || this._heightQuads.length == 0) {
  36369. this._initHeightQuads();
  36370. this._computeHeightQuads();
  36371. }
  36372. var facet = this._getFacetAt(x, z);
  36373. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  36374. // return y in the World system
  36375. return y * this.scaling.y + this.position.y;
  36376. };
  36377. /**
  36378. * Returns a normalized vector (Vector3) orthogonal to the ground
  36379. * at the ground coordinates (x, z) expressed in the World system.
  36380. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  36381. * Not pertinent if the ground is rotated.
  36382. */
  36383. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  36384. var normal = new BABYLON.Vector3(0, 1, 0);
  36385. this.getNormalAtCoordinatesToRef(x, z, normal);
  36386. return normal;
  36387. };
  36388. /**
  36389. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  36390. * at the ground coordinates (x, z) expressed in the World system.
  36391. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  36392. * Not pertinent if the ground is rotated.
  36393. */
  36394. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  36395. // express x and y in the ground local system
  36396. x -= this.position.x;
  36397. z -= this.position.z;
  36398. x /= this.scaling.x;
  36399. z /= this.scaling.z;
  36400. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  36401. return;
  36402. }
  36403. if (!this._heightQuads || this._heightQuads.length == 0) {
  36404. this._initHeightQuads();
  36405. this._computeHeightQuads();
  36406. }
  36407. var facet = this._getFacetAt(x, z);
  36408. ref.x = facet.x;
  36409. ref.y = facet.y;
  36410. ref.z = facet.z;
  36411. };
  36412. /**
  36413. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  36414. * if the ground has been updated.
  36415. * This can be used in the render loop
  36416. */
  36417. GroundMesh.prototype.updateCoordinateHeights = function () {
  36418. if (!this._heightQuads || this._heightQuads.length == 0) {
  36419. this._initHeightQuads();
  36420. }
  36421. this._computeHeightQuads();
  36422. };
  36423. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  36424. GroundMesh.prototype._getFacetAt = function (x, z) {
  36425. // retrieve col and row from x, z coordinates in the ground local system
  36426. var subdivisionsX = this._subdivisionsX;
  36427. var subdivisionsY = this._subdivisionsY;
  36428. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  36429. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  36430. var quad = this._heightQuads[row * this._subdivisionsX + col];
  36431. var facet;
  36432. if (z < quad.slope.x * x + quad.slope.y) {
  36433. facet = quad.facet1;
  36434. }
  36435. else {
  36436. facet = quad.facet2;
  36437. }
  36438. return facet;
  36439. };
  36440. // Creates and populates the heightMap array with "facet" elements :
  36441. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  36442. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  36443. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  36444. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  36445. GroundMesh.prototype._initHeightQuads = function () {
  36446. var subdivisionsX = this._subdivisionsX;
  36447. var subdivisionsY = this._subdivisionsY;
  36448. this._heightQuads = new Array();
  36449. for (var row = 0; row < subdivisionsY; row++) {
  36450. for (var col = 0; col < subdivisionsX; col++) {
  36451. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  36452. this._heightQuads[row * subdivisionsX + col] = quad;
  36453. }
  36454. }
  36455. };
  36456. // Compute each quad element values and update the the heightMap array :
  36457. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  36458. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  36459. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  36460. GroundMesh.prototype._computeHeightQuads = function () {
  36461. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36462. var v1 = BABYLON.Tmp.Vector3[3];
  36463. var v2 = BABYLON.Tmp.Vector3[2];
  36464. var v3 = BABYLON.Tmp.Vector3[1];
  36465. var v4 = BABYLON.Tmp.Vector3[0];
  36466. var v1v2 = BABYLON.Tmp.Vector3[4];
  36467. var v1v3 = BABYLON.Tmp.Vector3[5];
  36468. var v1v4 = BABYLON.Tmp.Vector3[6];
  36469. var norm1 = BABYLON.Tmp.Vector3[7];
  36470. var norm2 = BABYLON.Tmp.Vector3[8];
  36471. var i = 0;
  36472. var j = 0;
  36473. var k = 0;
  36474. var cd = 0; // 2D slope coefficient : z = cd * x + h
  36475. var h = 0;
  36476. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  36477. var d2 = 0;
  36478. var subdivisionsX = this._subdivisionsX;
  36479. var subdivisionsY = this._subdivisionsY;
  36480. for (var row = 0; row < subdivisionsY; row++) {
  36481. for (var col = 0; col < subdivisionsX; col++) {
  36482. i = col * 3;
  36483. j = row * (subdivisionsX + 1) * 3;
  36484. k = (row + 1) * (subdivisionsX + 1) * 3;
  36485. v1.x = positions[j + i];
  36486. v1.y = positions[j + i + 1];
  36487. v1.z = positions[j + i + 2];
  36488. v2.x = positions[j + i + 3];
  36489. v2.y = positions[j + i + 4];
  36490. v2.z = positions[j + i + 5];
  36491. v3.x = positions[k + i];
  36492. v3.y = positions[k + i + 1];
  36493. v3.z = positions[k + i + 2];
  36494. v4.x = positions[k + i + 3];
  36495. v4.y = positions[k + i + 4];
  36496. v4.z = positions[k + i + 5];
  36497. // 2D slope V1V4
  36498. cd = (v4.z - v1.z) / (v4.x - v1.x);
  36499. h = v1.z - cd * v1.x; // v1 belongs to the slope
  36500. // facet equations :
  36501. // we compute each facet normal vector
  36502. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  36503. // we compute the value d by applying the equation to v1 which belongs to the plane
  36504. // then we store the facet equation in a Vector4
  36505. v2.subtractToRef(v1, v1v2);
  36506. v3.subtractToRef(v1, v1v3);
  36507. v4.subtractToRef(v1, v1v4);
  36508. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  36509. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  36510. norm1.normalize();
  36511. norm2.normalize();
  36512. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  36513. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  36514. var quad = this._heightQuads[row * subdivisionsX + col];
  36515. quad.slope.copyFromFloats(cd, h);
  36516. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  36517. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  36518. }
  36519. }
  36520. };
  36521. return GroundMesh;
  36522. }(BABYLON.Mesh));
  36523. BABYLON.GroundMesh = GroundMesh;
  36524. })(BABYLON || (BABYLON = {}));
  36525. var BABYLON;
  36526. (function (BABYLON) {
  36527. var LinesMesh = (function (_super) {
  36528. __extends(LinesMesh, _super);
  36529. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  36530. if (parent === void 0) { parent = null; }
  36531. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  36532. this.color = new BABYLON.Color3(1, 1, 1);
  36533. this.alpha = 1;
  36534. this._positionBuffer = {};
  36535. if (source) {
  36536. this.color = source.color.clone();
  36537. this.alpha = source.alpha;
  36538. }
  36539. this._intersectionThreshold = 0.1;
  36540. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  36541. attributes: [BABYLON.VertexBuffer.PositionKind],
  36542. uniforms: ["worldViewProjection", "color"],
  36543. needAlphaBlending: true
  36544. });
  36545. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  36546. }
  36547. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  36548. /**
  36549. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  36550. * This margin is expressed in world space coordinates, so its value may vary.
  36551. * Default value is 0.1
  36552. * @returns the intersection Threshold value.
  36553. */
  36554. get: function () {
  36555. return this._intersectionThreshold;
  36556. },
  36557. /**
  36558. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  36559. * This margin is expressed in world space coordinates, so its value may vary.
  36560. * @param value the new threshold to apply
  36561. */
  36562. set: function (value) {
  36563. if (this._intersectionThreshold === value) {
  36564. return;
  36565. }
  36566. this._intersectionThreshold = value;
  36567. if (this.geometry) {
  36568. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  36569. }
  36570. },
  36571. enumerable: true,
  36572. configurable: true
  36573. });
  36574. Object.defineProperty(LinesMesh.prototype, "material", {
  36575. get: function () {
  36576. return this._colorShader;
  36577. },
  36578. enumerable: true,
  36579. configurable: true
  36580. });
  36581. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  36582. get: function () {
  36583. return false;
  36584. },
  36585. enumerable: true,
  36586. configurable: true
  36587. });
  36588. LinesMesh.prototype.createInstance = function (name) {
  36589. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  36590. return null;
  36591. };
  36592. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  36593. var engine = this.getScene().getEngine();
  36594. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  36595. // VBOs
  36596. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  36597. // Color
  36598. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  36599. };
  36600. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  36601. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  36602. return;
  36603. }
  36604. var engine = this.getScene().getEngine();
  36605. // Draw order
  36606. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  36607. };
  36608. LinesMesh.prototype.dispose = function (doNotRecurse) {
  36609. this._colorShader.dispose();
  36610. _super.prototype.dispose.call(this, doNotRecurse);
  36611. };
  36612. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  36613. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  36614. };
  36615. return LinesMesh;
  36616. }(BABYLON.Mesh));
  36617. BABYLON.LinesMesh = LinesMesh;
  36618. })(BABYLON || (BABYLON = {}));
  36619. var BABYLON;
  36620. (function (BABYLON) {
  36621. var DefaultLoadingScreen = (function () {
  36622. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  36623. var _this = this;
  36624. if (_loadingText === void 0) { _loadingText = ""; }
  36625. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  36626. this._renderingCanvas = _renderingCanvas;
  36627. this._loadingText = _loadingText;
  36628. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  36629. // Resize
  36630. this._resizeLoadingUI = function () {
  36631. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  36632. _this._loadingDiv.style.position = "absolute";
  36633. _this._loadingDiv.style.left = canvasRect.left + "px";
  36634. _this._loadingDiv.style.top = canvasRect.top + "px";
  36635. _this._loadingDiv.style.width = canvasRect.width + "px";
  36636. _this._loadingDiv.style.height = canvasRect.height + "px";
  36637. };
  36638. }
  36639. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  36640. var _this = this;
  36641. if (this._loadingDiv) {
  36642. // Do not add a loading screen if there is already one
  36643. return;
  36644. }
  36645. this._loadingDiv = document.createElement("div");
  36646. this._loadingDiv.id = "babylonjsLoadingDiv";
  36647. this._loadingDiv.style.opacity = "0";
  36648. this._loadingDiv.style.transition = "opacity 1.5s ease";
  36649. // Loading text
  36650. this._loadingTextDiv = document.createElement("div");
  36651. this._loadingTextDiv.style.position = "absolute";
  36652. this._loadingTextDiv.style.left = "0";
  36653. this._loadingTextDiv.style.top = "50%";
  36654. this._loadingTextDiv.style.marginTop = "80px";
  36655. this._loadingTextDiv.style.width = "100%";
  36656. this._loadingTextDiv.style.height = "20px";
  36657. this._loadingTextDiv.style.fontFamily = "Arial";
  36658. this._loadingTextDiv.style.fontSize = "14px";
  36659. this._loadingTextDiv.style.color = "white";
  36660. this._loadingTextDiv.style.textAlign = "center";
  36661. this._loadingTextDiv.innerHTML = "Loading";
  36662. this._loadingDiv.appendChild(this._loadingTextDiv);
  36663. //set the predefined text
  36664. this._loadingTextDiv.innerHTML = this._loadingText;
  36665. // Loading img
  36666. var imgBack = new Image();
  36667. 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==";
  36668. imgBack.style.position = "absolute";
  36669. imgBack.style.left = "50%";
  36670. imgBack.style.top = "50%";
  36671. imgBack.style.marginLeft = "-50px";
  36672. imgBack.style.marginTop = "-50px";
  36673. imgBack.style.transition = "transform 1.0s ease";
  36674. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  36675. var deg = 360;
  36676. var onTransitionEnd = function () {
  36677. deg += 360;
  36678. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  36679. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  36680. };
  36681. imgBack.addEventListener("transitionend", onTransitionEnd);
  36682. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  36683. this._loadingDiv.appendChild(imgBack);
  36684. // front image
  36685. var imgFront = new Image();
  36686. 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=";
  36687. imgFront.style.position = "absolute";
  36688. imgFront.style.left = "50%";
  36689. imgFront.style.top = "50%";
  36690. imgFront.style.marginLeft = "-50px";
  36691. imgFront.style.marginTop = "-50px";
  36692. this._loadingDiv.appendChild(imgFront);
  36693. this._resizeLoadingUI();
  36694. window.addEventListener("resize", this._resizeLoadingUI);
  36695. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  36696. document.body.appendChild(this._loadingDiv);
  36697. setTimeout(function () {
  36698. _this._loadingDiv.style.opacity = "1";
  36699. imgBack.style.transform = "rotateZ(360deg)";
  36700. imgBack.style.webkitTransform = "rotateZ(360deg)";
  36701. }, 0);
  36702. };
  36703. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  36704. var _this = this;
  36705. if (!this._loadingDiv) {
  36706. return;
  36707. }
  36708. var onTransitionEnd = function () {
  36709. if (!_this._loadingDiv) {
  36710. return;
  36711. }
  36712. document.body.removeChild(_this._loadingDiv);
  36713. window.removeEventListener("resize", _this._resizeLoadingUI);
  36714. _this._loadingDiv = null;
  36715. };
  36716. this._loadingDiv.style.opacity = "0";
  36717. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  36718. };
  36719. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  36720. set: function (text) {
  36721. this._loadingText = text;
  36722. if (this._loadingTextDiv) {
  36723. this._loadingTextDiv.innerHTML = this._loadingText;
  36724. }
  36725. },
  36726. enumerable: true,
  36727. configurable: true
  36728. });
  36729. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  36730. get: function () {
  36731. return this._loadingDivBackgroundColor;
  36732. },
  36733. set: function (color) {
  36734. this._loadingDivBackgroundColor = color;
  36735. if (!this._loadingDiv) {
  36736. return;
  36737. }
  36738. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  36739. },
  36740. enumerable: true,
  36741. configurable: true
  36742. });
  36743. return DefaultLoadingScreen;
  36744. }());
  36745. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  36746. })(BABYLON || (BABYLON = {}));
  36747. var BABYLON;
  36748. (function (BABYLON) {
  36749. var AudioEngine = (function () {
  36750. function AudioEngine() {
  36751. this._audioContext = null;
  36752. this._audioContextInitialized = false;
  36753. this.canUseWebAudio = false;
  36754. this.WarnedWebAudioUnsupported = false;
  36755. this.unlocked = false;
  36756. this.isMP3supported = false;
  36757. this.isOGGsupported = false;
  36758. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  36759. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  36760. this.canUseWebAudio = true;
  36761. }
  36762. var audioElem = document.createElement('audio');
  36763. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  36764. this.isMP3supported = true;
  36765. }
  36766. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  36767. this.isOGGsupported = true;
  36768. }
  36769. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  36770. this._unlockiOSaudio();
  36771. }
  36772. else {
  36773. this.unlocked = true;
  36774. }
  36775. }
  36776. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  36777. get: function () {
  36778. if (!this._audioContextInitialized) {
  36779. this._initializeAudioContext();
  36780. }
  36781. return this._audioContext;
  36782. },
  36783. enumerable: true,
  36784. configurable: true
  36785. });
  36786. AudioEngine.prototype._unlockiOSaudio = function () {
  36787. var _this = this;
  36788. var unlockaudio = function () {
  36789. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  36790. var source = _this.audioContext.createBufferSource();
  36791. source.buffer = buffer;
  36792. source.connect(_this.audioContext.destination);
  36793. source.start(0);
  36794. setTimeout(function () {
  36795. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  36796. _this.unlocked = true;
  36797. window.removeEventListener('touchend', unlockaudio, false);
  36798. if (_this.onAudioUnlocked) {
  36799. _this.onAudioUnlocked();
  36800. }
  36801. }
  36802. }, 0);
  36803. };
  36804. window.addEventListener('touchend', unlockaudio, false);
  36805. };
  36806. AudioEngine.prototype._initializeAudioContext = function () {
  36807. try {
  36808. if (this.canUseWebAudio) {
  36809. this._audioContext = new AudioContext();
  36810. // create a global volume gain node
  36811. this.masterGain = this._audioContext.createGain();
  36812. this.masterGain.gain.value = 1;
  36813. this.masterGain.connect(this._audioContext.destination);
  36814. this._audioContextInitialized = true;
  36815. }
  36816. }
  36817. catch (e) {
  36818. this.canUseWebAudio = false;
  36819. BABYLON.Tools.Error("Web Audio: " + e.message);
  36820. }
  36821. };
  36822. AudioEngine.prototype.dispose = function () {
  36823. if (this.canUseWebAudio && this._audioContextInitialized) {
  36824. if (this._connectedAnalyser) {
  36825. this._connectedAnalyser.stopDebugCanvas();
  36826. this._connectedAnalyser.dispose();
  36827. this.masterGain.disconnect();
  36828. this.masterGain.connect(this._audioContext.destination);
  36829. this._connectedAnalyser = null;
  36830. }
  36831. this.masterGain.gain.value = 1;
  36832. }
  36833. this.WarnedWebAudioUnsupported = false;
  36834. };
  36835. AudioEngine.prototype.getGlobalVolume = function () {
  36836. if (this.canUseWebAudio && this._audioContextInitialized) {
  36837. return this.masterGain.gain.value;
  36838. }
  36839. else {
  36840. return -1;
  36841. }
  36842. };
  36843. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  36844. if (this.canUseWebAudio && this._audioContextInitialized) {
  36845. this.masterGain.gain.value = newVolume;
  36846. }
  36847. };
  36848. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  36849. if (this._connectedAnalyser) {
  36850. this._connectedAnalyser.stopDebugCanvas();
  36851. }
  36852. if (this.canUseWebAudio && this._audioContextInitialized) {
  36853. this._connectedAnalyser = analyser;
  36854. this.masterGain.disconnect();
  36855. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  36856. }
  36857. };
  36858. return AudioEngine;
  36859. }());
  36860. BABYLON.AudioEngine = AudioEngine;
  36861. })(BABYLON || (BABYLON = {}));
  36862. var BABYLON;
  36863. (function (BABYLON) {
  36864. var Sound = (function () {
  36865. /**
  36866. * Create a sound and attach it to a scene
  36867. * @param name Name of your sound
  36868. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  36869. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  36870. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  36871. */
  36872. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  36873. var _this = this;
  36874. this.autoplay = false;
  36875. this.loop = false;
  36876. this.useCustomAttenuation = false;
  36877. this.spatialSound = false;
  36878. this.refDistance = 1;
  36879. this.rolloffFactor = 1;
  36880. this.maxDistance = 100;
  36881. this.distanceModel = "linear";
  36882. this._panningModel = "equalpower";
  36883. this._playbackRate = 1;
  36884. this._streaming = false;
  36885. this._startTime = 0;
  36886. this._startOffset = 0;
  36887. this._position = BABYLON.Vector3.Zero();
  36888. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  36889. this._volume = 1;
  36890. this._isLoaded = false;
  36891. this._isReadyToPlay = false;
  36892. this.isPlaying = false;
  36893. this.isPaused = false;
  36894. this._isDirectional = false;
  36895. // Used if you'd like to create a directional sound.
  36896. // If not set, the sound will be omnidirectional
  36897. this._coneInnerAngle = 360;
  36898. this._coneOuterAngle = 360;
  36899. this._coneOuterGain = 0;
  36900. this._isOutputConnected = false;
  36901. this._urlType = "Unknown";
  36902. this.name = name;
  36903. this._scene = scene;
  36904. this._readyToPlayCallback = readyToPlayCallback;
  36905. // Default custom attenuation function is a linear attenuation
  36906. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  36907. if (currentDistance < maxDistance) {
  36908. return currentVolume * (1 - currentDistance / maxDistance);
  36909. }
  36910. else {
  36911. return 0;
  36912. }
  36913. };
  36914. if (options) {
  36915. this.autoplay = options.autoplay || false;
  36916. this.loop = options.loop || false;
  36917. // if volume === 0, we need another way to check this option
  36918. if (options.volume !== undefined) {
  36919. this._volume = options.volume;
  36920. }
  36921. this.spatialSound = options.spatialSound || false;
  36922. this.maxDistance = options.maxDistance || 100;
  36923. this.useCustomAttenuation = options.useCustomAttenuation || false;
  36924. this.rolloffFactor = options.rolloffFactor || 1;
  36925. this.refDistance = options.refDistance || 1;
  36926. this.distanceModel = options.distanceModel || "linear";
  36927. this._playbackRate = options.playbackRate || 1;
  36928. this._streaming = options.streaming || false;
  36929. }
  36930. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36931. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  36932. this._soundGain.gain.value = this._volume;
  36933. this._inputAudioNode = this._soundGain;
  36934. this._ouputAudioNode = this._soundGain;
  36935. if (this.spatialSound) {
  36936. this._createSpatialParameters();
  36937. }
  36938. this._scene.mainSoundTrack.AddSound(this);
  36939. var validParameter = true;
  36940. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  36941. if (urlOrArrayBuffer) {
  36942. if (typeof (urlOrArrayBuffer) === "string")
  36943. this._urlType = "String";
  36944. if (Array.isArray(urlOrArrayBuffer))
  36945. this._urlType = "Array";
  36946. if (urlOrArrayBuffer instanceof ArrayBuffer)
  36947. this._urlType = "ArrayBuffer";
  36948. var urls = [];
  36949. var codecSupportedFound = false;
  36950. switch (this._urlType) {
  36951. case "ArrayBuffer":
  36952. if (urlOrArrayBuffer.byteLength > 0) {
  36953. codecSupportedFound = true;
  36954. this._soundLoaded(urlOrArrayBuffer);
  36955. }
  36956. break;
  36957. case "String":
  36958. urls.push(urlOrArrayBuffer);
  36959. case "Array":
  36960. if (urls.length === 0)
  36961. urls = urlOrArrayBuffer;
  36962. // If we found a supported format, we load it immediately and stop the loop
  36963. for (var i = 0; i < urls.length; i++) {
  36964. var url = urls[i];
  36965. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  36966. codecSupportedFound = true;
  36967. }
  36968. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  36969. codecSupportedFound = true;
  36970. }
  36971. if (url.indexOf(".wav", url.length - 4) !== -1) {
  36972. codecSupportedFound = true;
  36973. }
  36974. if (codecSupportedFound) {
  36975. // Loading sound using XHR2
  36976. if (!this._streaming) {
  36977. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  36978. }
  36979. else {
  36980. this._htmlAudioElement = new Audio(url);
  36981. this._htmlAudioElement.controls = false;
  36982. this._htmlAudioElement.loop = this.loop;
  36983. this._htmlAudioElement.crossOrigin = "anonymous";
  36984. this._htmlAudioElement.preload = "auto";
  36985. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  36986. _this._isReadyToPlay = true;
  36987. if (_this.autoplay) {
  36988. _this.play();
  36989. }
  36990. if (_this._readyToPlayCallback) {
  36991. _this._readyToPlayCallback();
  36992. }
  36993. });
  36994. document.body.appendChild(this._htmlAudioElement);
  36995. }
  36996. break;
  36997. }
  36998. }
  36999. break;
  37000. default:
  37001. validParameter = false;
  37002. break;
  37003. }
  37004. if (!validParameter) {
  37005. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  37006. }
  37007. else {
  37008. if (!codecSupportedFound) {
  37009. this._isReadyToPlay = true;
  37010. // Simulating a ready to play event to avoid breaking code path
  37011. if (this._readyToPlayCallback) {
  37012. window.setTimeout(function () {
  37013. _this._readyToPlayCallback();
  37014. }, 1000);
  37015. }
  37016. }
  37017. }
  37018. }
  37019. }
  37020. else {
  37021. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  37022. this._scene.mainSoundTrack.AddSound(this);
  37023. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  37024. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  37025. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  37026. }
  37027. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  37028. if (this._readyToPlayCallback) {
  37029. window.setTimeout(function () {
  37030. _this._readyToPlayCallback();
  37031. }, 1000);
  37032. }
  37033. }
  37034. }
  37035. Sound.prototype.dispose = function () {
  37036. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  37037. if (this.isPlaying) {
  37038. this.stop();
  37039. }
  37040. this._isReadyToPlay = false;
  37041. if (this.soundTrackId === -1) {
  37042. this._scene.mainSoundTrack.RemoveSound(this);
  37043. }
  37044. else {
  37045. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  37046. }
  37047. if (this._soundGain) {
  37048. this._soundGain.disconnect();
  37049. this._soundGain = null;
  37050. }
  37051. if (this._soundPanner) {
  37052. this._soundPanner.disconnect();
  37053. this._soundPanner = null;
  37054. }
  37055. if (this._soundSource) {
  37056. this._soundSource.disconnect();
  37057. this._soundSource = null;
  37058. }
  37059. this._audioBuffer = null;
  37060. if (this._htmlAudioElement) {
  37061. this._htmlAudioElement.pause();
  37062. this._htmlAudioElement.src = "";
  37063. document.body.removeChild(this._htmlAudioElement);
  37064. }
  37065. if (this._connectedMesh) {
  37066. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  37067. this._connectedMesh = null;
  37068. }
  37069. }
  37070. };
  37071. Sound.prototype._soundLoaded = function (audioData) {
  37072. var _this = this;
  37073. this._isLoaded = true;
  37074. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  37075. _this._audioBuffer = buffer;
  37076. _this._isReadyToPlay = true;
  37077. if (_this.autoplay) {
  37078. _this.play();
  37079. }
  37080. if (_this._readyToPlayCallback) {
  37081. _this._readyToPlayCallback();
  37082. }
  37083. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  37084. };
  37085. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  37086. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37087. this._audioBuffer = audioBuffer;
  37088. this._isReadyToPlay = true;
  37089. }
  37090. };
  37091. Sound.prototype.updateOptions = function (options) {
  37092. if (options) {
  37093. this.loop = options.loop || this.loop;
  37094. this.maxDistance = options.maxDistance || this.maxDistance;
  37095. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  37096. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  37097. this.refDistance = options.refDistance || this.refDistance;
  37098. this.distanceModel = options.distanceModel || this.distanceModel;
  37099. this._playbackRate = options.playbackRate || this._playbackRate;
  37100. this._updateSpatialParameters();
  37101. if (this.isPlaying) {
  37102. if (this._streaming) {
  37103. this._htmlAudioElement.playbackRate = this._playbackRate;
  37104. }
  37105. else {
  37106. this._soundSource.playbackRate.value = this._playbackRate;
  37107. }
  37108. }
  37109. }
  37110. };
  37111. Sound.prototype._createSpatialParameters = function () {
  37112. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37113. if (this._scene.headphone) {
  37114. this._panningModel = "HRTF";
  37115. }
  37116. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  37117. this._updateSpatialParameters();
  37118. this._soundPanner.connect(this._ouputAudioNode);
  37119. this._inputAudioNode = this._soundPanner;
  37120. }
  37121. };
  37122. Sound.prototype._updateSpatialParameters = function () {
  37123. if (this.spatialSound) {
  37124. if (this.useCustomAttenuation) {
  37125. // Tricks to disable in a way embedded Web Audio attenuation
  37126. this._soundPanner.distanceModel = "linear";
  37127. this._soundPanner.maxDistance = Number.MAX_VALUE;
  37128. this._soundPanner.refDistance = 1;
  37129. this._soundPanner.rolloffFactor = 1;
  37130. this._soundPanner.panningModel = this._panningModel;
  37131. }
  37132. else {
  37133. this._soundPanner.distanceModel = this.distanceModel;
  37134. this._soundPanner.maxDistance = this.maxDistance;
  37135. this._soundPanner.refDistance = this.refDistance;
  37136. this._soundPanner.rolloffFactor = this.rolloffFactor;
  37137. this._soundPanner.panningModel = this._panningModel;
  37138. }
  37139. }
  37140. };
  37141. Sound.prototype.switchPanningModelToHRTF = function () {
  37142. this._panningModel = "HRTF";
  37143. this._switchPanningModel();
  37144. };
  37145. Sound.prototype.switchPanningModelToEqualPower = function () {
  37146. this._panningModel = "equalpower";
  37147. this._switchPanningModel();
  37148. };
  37149. Sound.prototype._switchPanningModel = function () {
  37150. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  37151. this._soundPanner.panningModel = this._panningModel;
  37152. }
  37153. };
  37154. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  37155. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37156. if (this._isOutputConnected) {
  37157. this._ouputAudioNode.disconnect();
  37158. }
  37159. this._ouputAudioNode.connect(soundTrackAudioNode);
  37160. this._isOutputConnected = true;
  37161. }
  37162. };
  37163. /**
  37164. * Transform this sound into a directional source
  37165. * @param coneInnerAngle Size of the inner cone in degree
  37166. * @param coneOuterAngle Size of the outer cone in degree
  37167. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  37168. */
  37169. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  37170. if (coneOuterAngle < coneInnerAngle) {
  37171. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  37172. return;
  37173. }
  37174. this._coneInnerAngle = coneInnerAngle;
  37175. this._coneOuterAngle = coneOuterAngle;
  37176. this._coneOuterGain = coneOuterGain;
  37177. this._isDirectional = true;
  37178. if (this.isPlaying && this.loop) {
  37179. this.stop();
  37180. this.play();
  37181. }
  37182. };
  37183. Sound.prototype.setPosition = function (newPosition) {
  37184. this._position = newPosition;
  37185. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  37186. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  37187. }
  37188. };
  37189. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  37190. this._localDirection = newLocalDirection;
  37191. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  37192. this._updateDirection();
  37193. }
  37194. };
  37195. Sound.prototype._updateDirection = function () {
  37196. var mat = this._connectedMesh.getWorldMatrix();
  37197. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  37198. direction.normalize();
  37199. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  37200. };
  37201. Sound.prototype.updateDistanceFromListener = function () {
  37202. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  37203. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  37204. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  37205. }
  37206. };
  37207. Sound.prototype.setAttenuationFunction = function (callback) {
  37208. this._customAttenuationFunction = callback;
  37209. };
  37210. /**
  37211. * Play the sound
  37212. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  37213. * @param offset (optional) Start the sound setting it at a specific time
  37214. */
  37215. Sound.prototype.play = function (time, offset) {
  37216. var _this = this;
  37217. if (this._isReadyToPlay && this._scene.audioEnabled) {
  37218. try {
  37219. if (this._startOffset < 0) {
  37220. time = -this._startOffset;
  37221. this._startOffset = 0;
  37222. }
  37223. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  37224. if (!this._soundSource || !this._streamingSource) {
  37225. if (this.spatialSound) {
  37226. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  37227. if (this._isDirectional) {
  37228. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  37229. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  37230. this._soundPanner.coneOuterGain = this._coneOuterGain;
  37231. if (this._connectedMesh) {
  37232. this._updateDirection();
  37233. }
  37234. else {
  37235. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  37236. }
  37237. }
  37238. }
  37239. }
  37240. if (this._streaming) {
  37241. if (!this._streamingSource) {
  37242. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  37243. this._htmlAudioElement.onended = function () { _this._onended(); };
  37244. this._htmlAudioElement.playbackRate = this._playbackRate;
  37245. }
  37246. this._streamingSource.disconnect();
  37247. this._streamingSource.connect(this._inputAudioNode);
  37248. this._htmlAudioElement.play();
  37249. }
  37250. else {
  37251. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  37252. this._soundSource.buffer = this._audioBuffer;
  37253. this._soundSource.connect(this._inputAudioNode);
  37254. this._soundSource.loop = this.loop;
  37255. this._soundSource.playbackRate.value = this._playbackRate;
  37256. this._soundSource.onended = function () { _this._onended(); };
  37257. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  37258. }
  37259. this._startTime = startTime;
  37260. this.isPlaying = true;
  37261. this.isPaused = false;
  37262. }
  37263. catch (ex) {
  37264. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  37265. }
  37266. }
  37267. };
  37268. Sound.prototype._onended = function () {
  37269. this.isPlaying = false;
  37270. if (this.onended) {
  37271. this.onended();
  37272. }
  37273. };
  37274. /**
  37275. * Stop the sound
  37276. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  37277. */
  37278. Sound.prototype.stop = function (time) {
  37279. if (this.isPlaying) {
  37280. if (this._streaming) {
  37281. this._htmlAudioElement.pause();
  37282. // Test needed for Firefox or it will generate an Invalid State Error
  37283. if (this._htmlAudioElement.currentTime > 0) {
  37284. this._htmlAudioElement.currentTime = 0;
  37285. }
  37286. }
  37287. else {
  37288. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  37289. this._soundSource.stop(stopTime);
  37290. this._soundSource.onended = null;
  37291. if (!this.isPaused) {
  37292. this._startOffset = 0;
  37293. }
  37294. }
  37295. this.isPlaying = false;
  37296. }
  37297. };
  37298. Sound.prototype.pause = function () {
  37299. if (this.isPlaying) {
  37300. this.isPaused = true;
  37301. if (this._streaming) {
  37302. this._htmlAudioElement.pause();
  37303. }
  37304. else {
  37305. this.stop(0);
  37306. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  37307. }
  37308. }
  37309. };
  37310. Sound.prototype.setVolume = function (newVolume, time) {
  37311. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37312. if (time) {
  37313. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  37314. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  37315. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  37316. }
  37317. else {
  37318. this._soundGain.gain.value = newVolume;
  37319. }
  37320. }
  37321. this._volume = newVolume;
  37322. };
  37323. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  37324. this._playbackRate = newPlaybackRate;
  37325. if (this.isPlaying) {
  37326. if (this._streaming) {
  37327. this._htmlAudioElement.playbackRate = this._playbackRate;
  37328. }
  37329. else {
  37330. this._soundSource.playbackRate.value = this._playbackRate;
  37331. }
  37332. }
  37333. };
  37334. Sound.prototype.getVolume = function () {
  37335. return this._volume;
  37336. };
  37337. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  37338. var _this = this;
  37339. if (this._connectedMesh) {
  37340. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  37341. this._registerFunc = null;
  37342. }
  37343. this._connectedMesh = meshToConnectTo;
  37344. if (!this.spatialSound) {
  37345. this.spatialSound = true;
  37346. this._createSpatialParameters();
  37347. if (this.isPlaying && this.loop) {
  37348. this.stop();
  37349. this.play();
  37350. }
  37351. }
  37352. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  37353. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  37354. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  37355. };
  37356. Sound.prototype.detachFromMesh = function () {
  37357. if (this._connectedMesh) {
  37358. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  37359. this._registerFunc = null;
  37360. this._connectedMesh = null;
  37361. }
  37362. };
  37363. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  37364. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  37365. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  37366. this._updateDirection();
  37367. }
  37368. };
  37369. Sound.prototype.clone = function () {
  37370. var _this = this;
  37371. if (!this._streaming) {
  37372. var setBufferAndRun = function () {
  37373. if (_this._isReadyToPlay) {
  37374. clonedSound._audioBuffer = _this.getAudioBuffer();
  37375. clonedSound._isReadyToPlay = true;
  37376. if (clonedSound.autoplay) {
  37377. clonedSound.play();
  37378. }
  37379. }
  37380. else {
  37381. window.setTimeout(setBufferAndRun, 300);
  37382. }
  37383. };
  37384. var currentOptions = {
  37385. autoplay: this.autoplay, loop: this.loop,
  37386. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  37387. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  37388. refDistance: this.refDistance, distanceModel: this.distanceModel
  37389. };
  37390. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  37391. if (this.useCustomAttenuation) {
  37392. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  37393. }
  37394. clonedSound.setPosition(this._position);
  37395. clonedSound.setPlaybackRate(this._playbackRate);
  37396. setBufferAndRun();
  37397. return clonedSound;
  37398. }
  37399. else {
  37400. return null;
  37401. }
  37402. };
  37403. Sound.prototype.getAudioBuffer = function () {
  37404. return this._audioBuffer;
  37405. };
  37406. Sound.prototype.serialize = function () {
  37407. var serializationObject = {
  37408. name: this.name,
  37409. url: this.name,
  37410. autoplay: this.autoplay,
  37411. loop: this.loop,
  37412. volume: this._volume,
  37413. spatialSound: this.spatialSound,
  37414. maxDistance: this.maxDistance,
  37415. rolloffFactor: this.rolloffFactor,
  37416. refDistance: this.refDistance,
  37417. distanceModel: this.distanceModel,
  37418. playbackRate: this._playbackRate,
  37419. panningModel: this._panningModel,
  37420. soundTrackId: this.soundTrackId
  37421. };
  37422. if (this.spatialSound) {
  37423. if (this._connectedMesh)
  37424. serializationObject.connectedMeshId = this._connectedMesh.id;
  37425. serializationObject.position = this._position.asArray();
  37426. serializationObject.refDistance = this.refDistance;
  37427. serializationObject.distanceModel = this.distanceModel;
  37428. serializationObject.isDirectional = this._isDirectional;
  37429. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  37430. serializationObject.coneInnerAngle = this._coneInnerAngle;
  37431. serializationObject.coneOuterAngle = this._coneOuterAngle;
  37432. serializationObject.coneOuterGain = this._coneOuterGain;
  37433. }
  37434. return serializationObject;
  37435. };
  37436. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  37437. var soundName = parsedSound.name;
  37438. var soundUrl;
  37439. if (parsedSound.url) {
  37440. soundUrl = rootUrl + parsedSound.url;
  37441. }
  37442. else {
  37443. soundUrl = rootUrl + soundName;
  37444. }
  37445. var options = {
  37446. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  37447. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  37448. rolloffFactor: parsedSound.rolloffFactor,
  37449. refDistance: parsedSound.refDistance,
  37450. distanceModel: parsedSound.distanceModel,
  37451. playbackRate: parsedSound.playbackRate
  37452. };
  37453. var newSound;
  37454. if (!sourceSound) {
  37455. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  37456. scene._addPendingData(newSound);
  37457. }
  37458. else {
  37459. var setBufferAndRun = function () {
  37460. if (sourceSound._isReadyToPlay) {
  37461. newSound._audioBuffer = sourceSound.getAudioBuffer();
  37462. newSound._isReadyToPlay = true;
  37463. if (newSound.autoplay) {
  37464. newSound.play();
  37465. }
  37466. }
  37467. else {
  37468. window.setTimeout(setBufferAndRun, 300);
  37469. }
  37470. };
  37471. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  37472. setBufferAndRun();
  37473. }
  37474. if (parsedSound.position) {
  37475. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  37476. newSound.setPosition(soundPosition);
  37477. }
  37478. if (parsedSound.isDirectional) {
  37479. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  37480. if (parsedSound.localDirectionToMesh) {
  37481. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  37482. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  37483. }
  37484. }
  37485. if (parsedSound.connectedMeshId) {
  37486. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  37487. if (connectedMesh) {
  37488. newSound.attachToMesh(connectedMesh);
  37489. }
  37490. }
  37491. return newSound;
  37492. };
  37493. return Sound;
  37494. }());
  37495. BABYLON.Sound = Sound;
  37496. })(BABYLON || (BABYLON = {}));
  37497. var BABYLON;
  37498. (function (BABYLON) {
  37499. var SoundTrack = (function () {
  37500. function SoundTrack(scene, options) {
  37501. this.id = -1;
  37502. this._isMainTrack = false;
  37503. this._isInitialized = false;
  37504. this._scene = scene;
  37505. this.soundCollection = new Array();
  37506. this._options = options;
  37507. if (!this._isMainTrack) {
  37508. this._scene.soundTracks.push(this);
  37509. this.id = this._scene.soundTracks.length - 1;
  37510. }
  37511. }
  37512. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  37513. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37514. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  37515. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  37516. if (this._options) {
  37517. if (this._options.volume) {
  37518. this._outputAudioNode.gain.value = this._options.volume;
  37519. }
  37520. if (this._options.mainTrack) {
  37521. this._isMainTrack = this._options.mainTrack;
  37522. }
  37523. }
  37524. this._isInitialized = true;
  37525. }
  37526. };
  37527. SoundTrack.prototype.dispose = function () {
  37528. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37529. if (this._connectedAnalyser) {
  37530. this._connectedAnalyser.stopDebugCanvas();
  37531. }
  37532. while (this.soundCollection.length) {
  37533. this.soundCollection[0].dispose();
  37534. }
  37535. if (this._outputAudioNode) {
  37536. this._outputAudioNode.disconnect();
  37537. }
  37538. this._outputAudioNode = null;
  37539. }
  37540. };
  37541. SoundTrack.prototype.AddSound = function (sound) {
  37542. if (!this._isInitialized) {
  37543. this._initializeSoundTrackAudioGraph();
  37544. }
  37545. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37546. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  37547. }
  37548. if (sound.soundTrackId) {
  37549. if (sound.soundTrackId === -1) {
  37550. this._scene.mainSoundTrack.RemoveSound(sound);
  37551. }
  37552. else {
  37553. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  37554. }
  37555. }
  37556. this.soundCollection.push(sound);
  37557. sound.soundTrackId = this.id;
  37558. };
  37559. SoundTrack.prototype.RemoveSound = function (sound) {
  37560. var index = this.soundCollection.indexOf(sound);
  37561. if (index !== -1) {
  37562. this.soundCollection.splice(index, 1);
  37563. }
  37564. };
  37565. SoundTrack.prototype.setVolume = function (newVolume) {
  37566. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37567. this._outputAudioNode.gain.value = newVolume;
  37568. }
  37569. };
  37570. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  37571. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37572. for (var i = 0; i < this.soundCollection.length; i++) {
  37573. this.soundCollection[i].switchPanningModelToHRTF();
  37574. }
  37575. }
  37576. };
  37577. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  37578. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37579. for (var i = 0; i < this.soundCollection.length; i++) {
  37580. this.soundCollection[i].switchPanningModelToEqualPower();
  37581. }
  37582. }
  37583. };
  37584. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  37585. if (this._connectedAnalyser) {
  37586. this._connectedAnalyser.stopDebugCanvas();
  37587. }
  37588. this._connectedAnalyser = analyser;
  37589. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37590. this._outputAudioNode.disconnect();
  37591. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  37592. }
  37593. };
  37594. return SoundTrack;
  37595. }());
  37596. BABYLON.SoundTrack = SoundTrack;
  37597. })(BABYLON || (BABYLON = {}));
  37598. var BABYLON;
  37599. (function (BABYLON) {
  37600. /**
  37601. * Special Glow Blur post process only blurring the alpha channel
  37602. * It enforces keeping the most luminous color in the color channel.
  37603. */
  37604. var GlowBlurPostProcess = (function (_super) {
  37605. __extends(GlowBlurPostProcess, _super);
  37606. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  37607. var _this = this;
  37608. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  37609. _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  37610. this.direction = direction;
  37611. this.blurWidth = blurWidth;
  37612. this.onApplyObservable.add(function (effect) {
  37613. effect.setFloat2("screenSize", _this.width, _this.height);
  37614. effect.setVector2("direction", _this.direction);
  37615. effect.setFloat("blurWidth", _this.blurWidth);
  37616. });
  37617. }
  37618. return GlowBlurPostProcess;
  37619. }(BABYLON.PostProcess));
  37620. /**
  37621. * The highlight layer Helps adding a glow effect around a mesh.
  37622. *
  37623. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  37624. * glowy meshes to your scene.
  37625. *
  37626. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  37627. */
  37628. var HighlightLayer = (function () {
  37629. /**
  37630. * Instantiates a new highlight Layer and references it to the scene..
  37631. * @param name The name of the layer
  37632. * @param scene The scene to use the layer in
  37633. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  37634. */
  37635. function HighlightLayer(name, scene, options) {
  37636. this._vertexBuffers = {};
  37637. this._mainTextureDesiredSize = { width: 0, height: 0 };
  37638. this._meshes = {};
  37639. this._maxSize = 0;
  37640. this._shouldRender = false;
  37641. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  37642. this._excludedMeshes = {};
  37643. /**
  37644. * Specifies whether or not the inner glow is ACTIVE in the layer.
  37645. */
  37646. this.innerGlow = true;
  37647. /**
  37648. * Specifies whether or not the outer glow is ACTIVE in the layer.
  37649. */
  37650. this.outerGlow = true;
  37651. /**
  37652. * An event triggered when the highlight layer has been disposed.
  37653. * @type {BABYLON.Observable}
  37654. */
  37655. this.onDisposeObservable = new BABYLON.Observable();
  37656. /**
  37657. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  37658. * @type {BABYLON.Observable}
  37659. */
  37660. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  37661. /**
  37662. * An event triggered when the highlight layer is being blurred.
  37663. * @type {BABYLON.Observable}
  37664. */
  37665. this.onBeforeBlurObservable = new BABYLON.Observable();
  37666. /**
  37667. * An event triggered when the highlight layer has been blurred.
  37668. * @type {BABYLON.Observable}
  37669. */
  37670. this.onAfterBlurObservable = new BABYLON.Observable();
  37671. /**
  37672. * An event triggered when the glowing blurred texture is being merged in the scene.
  37673. * @type {BABYLON.Observable}
  37674. */
  37675. this.onBeforeComposeObservable = new BABYLON.Observable();
  37676. /**
  37677. * An event triggered when the glowing blurred texture has been merged in the scene.
  37678. * @type {BABYLON.Observable}
  37679. */
  37680. this.onAfterComposeObservable = new BABYLON.Observable();
  37681. /**
  37682. * An event triggered when the highlight layer changes its size.
  37683. * @type {BABYLON.Observable}
  37684. */
  37685. this.onSizeChangedObservable = new BABYLON.Observable();
  37686. this._scene = scene;
  37687. var engine = scene.getEngine();
  37688. this._engine = engine;
  37689. this._maxSize = this._engine.getCaps().maxTextureSize;
  37690. this._scene.highlightLayers.push(this);
  37691. // Warn on stencil.
  37692. if (!this._engine.isStencilEnable) {
  37693. 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 }");
  37694. }
  37695. // Adapt options
  37696. this._options = options || {
  37697. mainTextureRatio: 0.25,
  37698. blurTextureSizeRatio: 0.5,
  37699. blurHorizontalSize: 1,
  37700. blurVerticalSize: 1,
  37701. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  37702. };
  37703. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  37704. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  37705. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  37706. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  37707. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  37708. // VBO
  37709. var vertices = [];
  37710. vertices.push(1, 1);
  37711. vertices.push(-1, 1);
  37712. vertices.push(-1, -1);
  37713. vertices.push(1, -1);
  37714. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37715. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  37716. // Indices
  37717. var indices = [];
  37718. indices.push(0);
  37719. indices.push(1);
  37720. indices.push(2);
  37721. indices.push(0);
  37722. indices.push(2);
  37723. indices.push(3);
  37724. this._indexBuffer = engine.createIndexBuffer(indices);
  37725. // Effect
  37726. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  37727. // Render target
  37728. this.setMainTextureSize();
  37729. // Create Textures and post processes
  37730. this.createTextureAndPostProcesses();
  37731. }
  37732. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  37733. /**
  37734. * Gets the horizontal size of the blur.
  37735. */
  37736. get: function () {
  37737. return this._horizontalBlurPostprocess.blurWidth;
  37738. },
  37739. /**
  37740. * Specifies the horizontal size of the blur.
  37741. */
  37742. set: function (value) {
  37743. this._horizontalBlurPostprocess.blurWidth = value;
  37744. },
  37745. enumerable: true,
  37746. configurable: true
  37747. });
  37748. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  37749. /**
  37750. * Gets the vertical size of the blur.
  37751. */
  37752. get: function () {
  37753. return this._verticalBlurPostprocess.blurWidth;
  37754. },
  37755. /**
  37756. * Specifies the vertical size of the blur.
  37757. */
  37758. set: function (value) {
  37759. this._verticalBlurPostprocess.blurWidth = value;
  37760. },
  37761. enumerable: true,
  37762. configurable: true
  37763. });
  37764. Object.defineProperty(HighlightLayer.prototype, "camera", {
  37765. /**
  37766. * Gets the camera attached to the layer.
  37767. */
  37768. get: function () {
  37769. return this._options.camera;
  37770. },
  37771. enumerable: true,
  37772. configurable: true
  37773. });
  37774. /**
  37775. * Creates the render target textures and post processes used in the highlight layer.
  37776. */
  37777. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  37778. var _this = this;
  37779. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  37780. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  37781. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  37782. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  37783. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  37784. width: this._mainTextureDesiredSize.width,
  37785. height: this._mainTextureDesiredSize.height
  37786. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  37787. this._mainTexture.activeCamera = this._options.camera;
  37788. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37789. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37790. this._mainTexture.anisotropicFilteringLevel = 1;
  37791. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37792. this._mainTexture.renderParticles = false;
  37793. this._mainTexture.renderList = null;
  37794. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  37795. width: blurTextureWidth,
  37796. height: blurTextureHeight
  37797. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  37798. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37799. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37800. this._blurTexture.anisotropicFilteringLevel = 16;
  37801. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  37802. this._blurTexture.renderParticles = false;
  37803. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  37804. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  37805. effect.setTexture("textureSampler", _this._mainTexture);
  37806. });
  37807. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  37808. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  37809. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  37810. });
  37811. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  37812. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  37813. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  37814. });
  37815. this._mainTexture.onAfterUnbindObservable.add(function () {
  37816. _this.onBeforeBlurObservable.notifyObservers(_this);
  37817. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  37818. _this.onAfterBlurObservable.notifyObservers(_this);
  37819. });
  37820. // Custom render function
  37821. var renderSubMesh = function (subMesh) {
  37822. var mesh = subMesh.getRenderingMesh();
  37823. var scene = _this._scene;
  37824. var engine = scene.getEngine();
  37825. // Culling
  37826. engine.setState(subMesh.getMaterial().backFaceCulling);
  37827. // Managing instances
  37828. var batch = mesh._getInstancesRenderList(subMesh._id);
  37829. if (batch.mustReturn) {
  37830. return;
  37831. }
  37832. // Excluded Mesh
  37833. if (_this._excludedMeshes[mesh.id]) {
  37834. return;
  37835. }
  37836. ;
  37837. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  37838. var highlightLayerMesh = _this._meshes[mesh.id];
  37839. var material = subMesh.getMaterial();
  37840. var emissiveTexture = null;
  37841. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  37842. emissiveTexture = material.emissiveTexture;
  37843. }
  37844. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  37845. engine.enableEffect(_this._glowMapGenerationEffect);
  37846. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  37847. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  37848. if (highlightLayerMesh) {
  37849. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  37850. }
  37851. else {
  37852. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  37853. }
  37854. // Alpha test
  37855. if (material && material.needAlphaTesting()) {
  37856. var alphaTexture = material.getAlphaTestTexture();
  37857. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  37858. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  37859. }
  37860. // Glow emissive only
  37861. if (emissiveTexture) {
  37862. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  37863. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  37864. }
  37865. // Bones
  37866. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37867. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  37868. }
  37869. // Draw
  37870. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  37871. }
  37872. else {
  37873. // Need to reset refresh rate of the shadowMap
  37874. _this._mainTexture.resetRefreshCounter();
  37875. }
  37876. };
  37877. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  37878. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  37879. var index;
  37880. for (index = 0; index < opaqueSubMeshes.length; index++) {
  37881. renderSubMesh(opaqueSubMeshes.data[index]);
  37882. }
  37883. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  37884. renderSubMesh(alphaTestSubMeshes.data[index]);
  37885. }
  37886. for (index = 0; index < transparentSubMeshes.length; index++) {
  37887. renderSubMesh(transparentSubMeshes.data[index]);
  37888. }
  37889. };
  37890. this._mainTexture.onClearObservable.add(function (engine) {
  37891. engine.clear(HighlightLayer.neutralColor, true, true, true);
  37892. });
  37893. };
  37894. /**
  37895. * Checks for the readiness of the element composing the layer.
  37896. * @param subMesh the mesh to check for
  37897. * @param useInstances specify wether or not to use instances to render the mesh
  37898. * @param emissiveTexture the associated emissive texture used to generate the glow
  37899. * @return true if ready otherwise, false
  37900. */
  37901. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  37902. if (!subMesh.getMaterial().isReady()) {
  37903. return false;
  37904. }
  37905. var defines = [];
  37906. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37907. var mesh = subMesh.getMesh();
  37908. var material = subMesh.getMaterial();
  37909. var uv1 = false;
  37910. var uv2 = false;
  37911. // Alpha test
  37912. if (material && material.needAlphaTesting()) {
  37913. var alphaTexture = material.getAlphaTestTexture();
  37914. if (alphaTexture) {
  37915. defines.push("#define ALPHATEST");
  37916. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  37917. alphaTexture.coordinatesIndex === 1) {
  37918. defines.push("#define DIFFUSEUV2");
  37919. uv2 = true;
  37920. }
  37921. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37922. defines.push("#define DIFFUSEUV1");
  37923. uv1 = true;
  37924. }
  37925. }
  37926. }
  37927. // Emissive
  37928. if (emissiveTexture) {
  37929. defines.push("#define EMISSIVE");
  37930. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  37931. emissiveTexture.coordinatesIndex === 1) {
  37932. defines.push("#define EMISSIVEUV2");
  37933. uv2 = true;
  37934. }
  37935. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37936. defines.push("#define EMISSIVEUV1");
  37937. uv1 = true;
  37938. }
  37939. }
  37940. if (uv1) {
  37941. attribs.push(BABYLON.VertexBuffer.UVKind);
  37942. defines.push("#define UV1");
  37943. }
  37944. if (uv2) {
  37945. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37946. defines.push("#define UV2");
  37947. }
  37948. // Bones
  37949. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37950. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37951. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37952. if (mesh.numBoneInfluencers > 4) {
  37953. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37954. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37955. }
  37956. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  37957. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  37958. }
  37959. else {
  37960. defines.push("#define NUM_BONE_INFLUENCERS 0");
  37961. }
  37962. // Instances
  37963. if (useInstances) {
  37964. defines.push("#define INSTANCES");
  37965. attribs.push("world0");
  37966. attribs.push("world1");
  37967. attribs.push("world2");
  37968. attribs.push("world3");
  37969. }
  37970. // Get correct effect
  37971. var join = defines.join("\n");
  37972. if (this._cachedDefines !== join) {
  37973. this._cachedDefines = join;
  37974. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  37975. }
  37976. return this._glowMapGenerationEffect.isReady();
  37977. };
  37978. /**
  37979. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  37980. */
  37981. HighlightLayer.prototype.render = function () {
  37982. var currentEffect = this._glowMapMergeEffect;
  37983. // Check
  37984. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  37985. return;
  37986. var engine = this._scene.getEngine();
  37987. this.onBeforeComposeObservable.notifyObservers(this);
  37988. // Render
  37989. engine.enableEffect(currentEffect);
  37990. engine.setState(false);
  37991. // Cache
  37992. var previousStencilBuffer = engine.getStencilBuffer();
  37993. var previousStencilFunction = engine.getStencilFunction();
  37994. var previousStencilMask = engine.getStencilMask();
  37995. var previousAlphaMode = engine.getAlphaMode();
  37996. // Texture
  37997. currentEffect.setTexture("textureSampler", this._blurTexture);
  37998. // VBOs
  37999. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  38000. // Draw order
  38001. engine.setAlphaMode(this._options.alphaBlendingMode);
  38002. engine.setStencilMask(0x00);
  38003. engine.setStencilBuffer(true);
  38004. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  38005. if (this.outerGlow) {
  38006. currentEffect.setFloat("offset", 0);
  38007. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  38008. engine.draw(true, 0, 6);
  38009. }
  38010. if (this.innerGlow) {
  38011. currentEffect.setFloat("offset", 1);
  38012. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  38013. engine.draw(true, 0, 6);
  38014. }
  38015. // Restore Cache
  38016. engine.setStencilFunction(previousStencilFunction);
  38017. engine.setStencilMask(previousStencilMask);
  38018. engine.setAlphaMode(previousAlphaMode);
  38019. engine.setStencilBuffer(previousStencilBuffer);
  38020. this.onAfterComposeObservable.notifyObservers(this);
  38021. // Handle size changes.
  38022. var size = this._mainTexture.getSize();
  38023. this.setMainTextureSize();
  38024. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  38025. // Recreate RTT and post processes on size change.
  38026. this.onSizeChangedObservable.notifyObservers(this);
  38027. this.disposeTextureAndPostProcesses();
  38028. this.createTextureAndPostProcesses();
  38029. }
  38030. };
  38031. /**
  38032. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  38033. * @param mesh The mesh to exclude from the highlight layer
  38034. */
  38035. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  38036. var meshExcluded = this._excludedMeshes[mesh.id];
  38037. if (!meshExcluded) {
  38038. this._excludedMeshes[mesh.id] = {
  38039. mesh: mesh,
  38040. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  38041. mesh.getEngine().setStencilBuffer(false);
  38042. }),
  38043. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  38044. mesh.getEngine().setStencilBuffer(true);
  38045. }),
  38046. };
  38047. }
  38048. };
  38049. /**
  38050. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  38051. * @param mesh The mesh to highlight
  38052. */
  38053. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  38054. var meshExcluded = this._excludedMeshes[mesh.id];
  38055. if (meshExcluded) {
  38056. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  38057. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  38058. }
  38059. this._excludedMeshes[mesh.id] = undefined;
  38060. };
  38061. /**
  38062. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  38063. * @param mesh The mesh to highlight
  38064. * @param color The color of the highlight
  38065. * @param glowEmissiveOnly Extract the glow from the emissive texture
  38066. */
  38067. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  38068. var _this = this;
  38069. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  38070. var meshHighlight = this._meshes[mesh.id];
  38071. if (meshHighlight) {
  38072. meshHighlight.color = color;
  38073. }
  38074. else {
  38075. this._meshes[mesh.id] = {
  38076. mesh: mesh,
  38077. color: color,
  38078. // Lambda required for capture due to Observable this context
  38079. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  38080. if (_this._excludedMeshes[mesh.id]) {
  38081. _this.defaultStencilReference(mesh);
  38082. }
  38083. else {
  38084. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  38085. }
  38086. }),
  38087. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  38088. glowEmissiveOnly: glowEmissiveOnly
  38089. };
  38090. }
  38091. this._shouldRender = true;
  38092. };
  38093. /**
  38094. * Remove a mesh from the highlight layer in order to make it stop glowing.
  38095. * @param mesh The mesh to highlight
  38096. */
  38097. HighlightLayer.prototype.removeMesh = function (mesh) {
  38098. var meshHighlight = this._meshes[mesh.id];
  38099. if (meshHighlight) {
  38100. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  38101. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  38102. }
  38103. this._meshes[mesh.id] = undefined;
  38104. this._shouldRender = false;
  38105. for (var meshHighlightToCheck in this._meshes) {
  38106. if (meshHighlightToCheck) {
  38107. this._shouldRender = true;
  38108. break;
  38109. }
  38110. }
  38111. };
  38112. /**
  38113. * Returns true if the layer contains information to display, otherwise false.
  38114. */
  38115. HighlightLayer.prototype.shouldRender = function () {
  38116. return this._shouldRender;
  38117. };
  38118. /**
  38119. * Sets the main texture desired size which is the closest power of two
  38120. * of the engine canvas size.
  38121. */
  38122. HighlightLayer.prototype.setMainTextureSize = function () {
  38123. if (this._options.mainTextureFixedSize) {
  38124. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  38125. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  38126. }
  38127. else {
  38128. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  38129. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  38130. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  38131. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  38132. }
  38133. };
  38134. /**
  38135. * Force the stencil to the normal expected value for none glowing parts
  38136. */
  38137. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  38138. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  38139. };
  38140. /**
  38141. * Dispose only the render target textures and post process.
  38142. */
  38143. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  38144. this._blurTexture.dispose();
  38145. this._mainTexture.dispose();
  38146. this._downSamplePostprocess.dispose();
  38147. this._horizontalBlurPostprocess.dispose();
  38148. this._verticalBlurPostprocess.dispose();
  38149. };
  38150. /**
  38151. * Dispose the highlight layer and free resources.
  38152. */
  38153. HighlightLayer.prototype.dispose = function () {
  38154. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  38155. if (vertexBuffer) {
  38156. vertexBuffer.dispose();
  38157. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  38158. }
  38159. if (this._indexBuffer) {
  38160. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38161. this._indexBuffer = null;
  38162. }
  38163. // Clean textures and post processes
  38164. this.disposeTextureAndPostProcesses();
  38165. // Clean mesh references
  38166. for (var id in this._meshes) {
  38167. var meshHighlight = this._meshes[id];
  38168. if (meshHighlight && meshHighlight.mesh) {
  38169. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  38170. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  38171. }
  38172. }
  38173. this._meshes = null;
  38174. for (var id in this._excludedMeshes) {
  38175. var meshHighlight = this._excludedMeshes[id];
  38176. if (meshHighlight) {
  38177. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  38178. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  38179. }
  38180. }
  38181. this._excludedMeshes = null;
  38182. // Remove from scene
  38183. var index = this._scene.highlightLayers.indexOf(this, 0);
  38184. if (index > -1) {
  38185. this._scene.highlightLayers.splice(index, 1);
  38186. }
  38187. // Callback
  38188. this.onDisposeObservable.notifyObservers(this);
  38189. this.onDisposeObservable.clear();
  38190. this.onBeforeRenderMainTextureObservable.clear();
  38191. this.onBeforeBlurObservable.clear();
  38192. this.onBeforeComposeObservable.clear();
  38193. this.onAfterComposeObservable.clear();
  38194. this.onSizeChangedObservable.clear();
  38195. };
  38196. /**
  38197. * The neutral color used during the preparation of the glow effect.
  38198. * This is black by default as the blend operation is a blend operation.
  38199. */
  38200. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  38201. /**
  38202. * Stencil value used for glowing meshes.
  38203. */
  38204. HighlightLayer.glowingMeshStencilReference = 0x02;
  38205. /**
  38206. * Stencil value used for the other meshes in the scene.
  38207. */
  38208. HighlightLayer.normalMeshStencilReference = 0x01;
  38209. return HighlightLayer;
  38210. }());
  38211. BABYLON.HighlightLayer = HighlightLayer;
  38212. })(BABYLON || (BABYLON = {}));
  38213. var BABYLON;
  38214. (function (BABYLON) {
  38215. var SIMDVector3 = (function () {
  38216. function SIMDVector3() {
  38217. }
  38218. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  38219. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  38220. };
  38221. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  38222. var m = transformation.m;
  38223. var m0 = SIMD.Float32x4.load(m, 0);
  38224. var m1 = SIMD.Float32x4.load(m, 4);
  38225. var m2 = SIMD.Float32x4.load(m, 8);
  38226. var m3 = SIMD.Float32x4.load(m, 12);
  38227. 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));
  38228. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  38229. result.x = SIMD.Float32x4.extractLane(r, 0);
  38230. result.y = SIMD.Float32x4.extractLane(r, 1);
  38231. result.z = SIMD.Float32x4.extractLane(r, 2);
  38232. };
  38233. return SIMDVector3;
  38234. }());
  38235. var SIMDMatrix = (function () {
  38236. function SIMDMatrix() {
  38237. }
  38238. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  38239. var tm = this.m;
  38240. var om = other.m;
  38241. var m0 = SIMD.Float32x4.load(om, 0);
  38242. var m1 = SIMD.Float32x4.load(om, 4);
  38243. var m2 = SIMD.Float32x4.load(om, 8);
  38244. var m3 = SIMD.Float32x4.load(om, 12);
  38245. for (var i = 0; i < 16; i += 4) {
  38246. 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)))));
  38247. }
  38248. return this;
  38249. };
  38250. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  38251. var src = this.m;
  38252. var dest = other.m;
  38253. // Load the 4 rows
  38254. var src0 = SIMD.Float32x4.load(src, 0);
  38255. var src1 = SIMD.Float32x4.load(src, 4);
  38256. var src2 = SIMD.Float32x4.load(src, 8);
  38257. var src3 = SIMD.Float32x4.load(src, 12);
  38258. // Transpose the source matrix. Sort of. Not a true transpose operation
  38259. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  38260. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  38261. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  38262. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  38263. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  38264. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  38265. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  38266. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  38267. // This is a true transposition, but it will lead to an incorrect result
  38268. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  38269. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  38270. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  38271. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  38272. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  38273. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  38274. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  38275. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  38276. // ----
  38277. tmp1 = SIMD.Float32x4.mul(row2, row3);
  38278. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  38279. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  38280. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  38281. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  38282. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  38283. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  38284. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  38285. // ----
  38286. tmp1 = SIMD.Float32x4.mul(row1, row2);
  38287. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  38288. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  38289. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  38290. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  38291. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  38292. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  38293. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  38294. // ----
  38295. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  38296. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  38297. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  38298. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  38299. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  38300. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  38301. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  38302. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  38303. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  38304. // ----
  38305. tmp1 = SIMD.Float32x4.mul(row0, row1);
  38306. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  38307. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  38308. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  38309. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  38310. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  38311. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  38312. // ----
  38313. tmp1 = SIMD.Float32x4.mul(row0, row3);
  38314. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  38315. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  38316. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  38317. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  38318. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  38319. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  38320. // ----
  38321. tmp1 = SIMD.Float32x4.mul(row0, row2);
  38322. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  38323. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  38324. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  38325. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  38326. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  38327. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  38328. // Compute determinant
  38329. var det = SIMD.Float32x4.mul(row0, minor0);
  38330. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  38331. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  38332. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  38333. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  38334. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  38335. // These shuffles aren't necessary if the faulty transposition is done
  38336. // up at the top of this function.
  38337. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  38338. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  38339. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  38340. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  38341. // Compute final values by multiplying with 1/det
  38342. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  38343. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  38344. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  38345. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  38346. return this;
  38347. };
  38348. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  38349. var out = result.m;
  38350. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  38351. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  38352. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  38353. // cc.kmVec3Subtract(f, pCenter, pEye);
  38354. var f = SIMD.Float32x4.sub(center, eye);
  38355. // cc.kmVec3Normalize(f, f);
  38356. var tmp = SIMD.Float32x4.mul(f, f);
  38357. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  38358. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  38359. // cc.kmVec3Assign(up, pUp);
  38360. // cc.kmVec3Normalize(up, up);
  38361. tmp = SIMD.Float32x4.mul(up, up);
  38362. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  38363. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  38364. // cc.kmVec3Cross(s, f, up);
  38365. 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)));
  38366. // cc.kmVec3Normalize(s, s);
  38367. tmp = SIMD.Float32x4.mul(s, s);
  38368. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  38369. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  38370. // cc.kmVec3Cross(u, s, f);
  38371. 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)));
  38372. // cc.kmVec3Normalize(s, s);
  38373. tmp = SIMD.Float32x4.mul(s, s);
  38374. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  38375. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  38376. var zero = SIMD.Float32x4.splat(0.0);
  38377. s = SIMD.Float32x4.neg(s);
  38378. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  38379. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  38380. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  38381. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  38382. 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);
  38383. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  38384. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  38385. 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)))));
  38386. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  38387. 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)))));
  38388. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  38389. 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)))));
  38390. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  38391. 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)))));
  38392. };
  38393. return SIMDMatrix;
  38394. }());
  38395. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  38396. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  38397. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  38398. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  38399. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  38400. var SIMDHelper = (function () {
  38401. function SIMDHelper() {
  38402. }
  38403. Object.defineProperty(SIMDHelper, "IsEnabled", {
  38404. get: function () {
  38405. return SIMDHelper._isEnabled;
  38406. },
  38407. enumerable: true,
  38408. configurable: true
  38409. });
  38410. SIMDHelper.DisableSIMD = function () {
  38411. // Replace functions
  38412. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  38413. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  38414. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  38415. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  38416. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  38417. SIMDHelper._isEnabled = false;
  38418. };
  38419. SIMDHelper.EnableSIMD = function () {
  38420. if (self.SIMD === undefined) {
  38421. return;
  38422. }
  38423. // check if polyfills needed
  38424. if (!self.Math.fround) {
  38425. self.Math.fround = (function (array) { return function (x) {
  38426. return array[0] = x, array[0];
  38427. }; })(new Float32Array(1));
  38428. }
  38429. if (!self.Math.imul) {
  38430. self.Math.imul = function (a, b) {
  38431. var ah = (a >>> 16) & 0xffff;
  38432. var al = a & 0xffff;
  38433. var bh = (b >>> 16) & 0xffff;
  38434. var bl = b & 0xffff;
  38435. // the shift by 0 fixes the sign on the high part
  38436. // the final |0 converts the unsigned value into a signed value
  38437. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  38438. };
  38439. }
  38440. // Replace functions
  38441. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  38442. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  38443. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  38444. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  38445. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  38446. SIMDHelper._isEnabled = true;
  38447. };
  38448. SIMDHelper._isEnabled = false;
  38449. return SIMDHelper;
  38450. }());
  38451. BABYLON.SIMDHelper = SIMDHelper;
  38452. })(BABYLON || (BABYLON = {}));
  38453. var BABYLON;
  38454. (function (BABYLON) {
  38455. /**
  38456. * This class describe a rectangle that were added to the map.
  38457. * You have access to its coordinates either in pixel or normalized (UV)
  38458. */
  38459. var PackedRect = (function () {
  38460. function PackedRect(root, parent, pos, size) {
  38461. this._pos = pos;
  38462. this._size = size;
  38463. this._root = root;
  38464. this._parent = parent;
  38465. this._contentSize = null;
  38466. this._bottomNode = null;
  38467. this._leftNode = null;
  38468. this._initialSize = null;
  38469. this._rightNode = null;
  38470. }
  38471. Object.defineProperty(PackedRect.prototype, "pos", {
  38472. /**
  38473. * @returns the position of this node into the map
  38474. */
  38475. get: function () {
  38476. return this._pos;
  38477. },
  38478. enumerable: true,
  38479. configurable: true
  38480. });
  38481. Object.defineProperty(PackedRect.prototype, "contentSize", {
  38482. /**
  38483. * @returns the size of the rectangle this node handles
  38484. */
  38485. get: function () {
  38486. return this._contentSize;
  38487. },
  38488. enumerable: true,
  38489. configurable: true
  38490. });
  38491. Object.defineProperty(PackedRect.prototype, "UVs", {
  38492. /**
  38493. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  38494. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  38495. */
  38496. get: function () {
  38497. return this.getUVsForCustomSize(this._root._size);
  38498. },
  38499. enumerable: true,
  38500. configurable: true
  38501. });
  38502. /**
  38503. * 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.
  38504. * This method will return the UVs for this part by given the custom size of what you really use
  38505. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  38506. */
  38507. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  38508. var mainWidth = this._root._size.width;
  38509. var mainHeight = this._root._size.height;
  38510. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  38511. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  38512. var uvs = new Array();
  38513. uvs.push(topLeft);
  38514. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  38515. uvs.push(rightBottom);
  38516. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  38517. return uvs;
  38518. };
  38519. /**
  38520. * Free this rectangle from the map.
  38521. * Call this method when you no longer need the rectangle to be in the map.
  38522. */
  38523. PackedRect.prototype.freeContent = function () {
  38524. if (!this.contentSize) {
  38525. return;
  38526. }
  38527. this._contentSize = null;
  38528. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  38529. this.attemptDefrag();
  38530. };
  38531. Object.defineProperty(PackedRect.prototype, "isUsed", {
  38532. get: function () {
  38533. return this._contentSize != null || this._leftNode != null;
  38534. },
  38535. enumerable: true,
  38536. configurable: true
  38537. });
  38538. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  38539. var node = this.findNode(contentSize);
  38540. // Not enough space...
  38541. if (!node) {
  38542. return null;
  38543. }
  38544. node.splitNode(contentSize);
  38545. return node;
  38546. };
  38547. PackedRect.prototype.findNode = function (size) {
  38548. var resNode = null;
  38549. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  38550. if (this.isUsed) {
  38551. if (this._leftNode) {
  38552. resNode = this._leftNode.findNode(size);
  38553. }
  38554. if (!resNode && this._rightNode) {
  38555. resNode = this._rightNode.findNode(size);
  38556. }
  38557. if (!resNode && this._bottomNode) {
  38558. resNode = this._bottomNode.findNode(size);
  38559. }
  38560. }
  38561. else if (this._initialSize) {
  38562. if ((size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  38563. resNode = this;
  38564. }
  38565. else {
  38566. return null;
  38567. }
  38568. }
  38569. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  38570. resNode = this;
  38571. }
  38572. return resNode;
  38573. };
  38574. PackedRect.prototype.splitNode = function (contentSize) {
  38575. // 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)
  38576. if (!this._contentSize && this._initialSize) {
  38577. this._contentSize = contentSize.clone();
  38578. 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));
  38579. return this._leftNode.splitNode(contentSize);
  38580. }
  38581. else {
  38582. this._contentSize = contentSize.clone();
  38583. this._initialSize = contentSize.clone();
  38584. if (contentSize.width !== this._size.width) {
  38585. 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));
  38586. }
  38587. if (contentSize.height !== this._size.height) {
  38588. 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));
  38589. }
  38590. return this;
  38591. }
  38592. };
  38593. PackedRect.prototype.attemptDefrag = function () {
  38594. if (!this.isUsed && this.isRecursiveFree) {
  38595. this.clearNode();
  38596. if (this._parent) {
  38597. this._parent.attemptDefrag();
  38598. }
  38599. }
  38600. };
  38601. PackedRect.prototype.clearNode = function () {
  38602. this._initialSize = null;
  38603. this._rightNode = null;
  38604. this._bottomNode = null;
  38605. };
  38606. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  38607. get: function () {
  38608. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  38609. },
  38610. enumerable: true,
  38611. configurable: true
  38612. });
  38613. PackedRect.prototype.evalFreeSize = function (size) {
  38614. var levelSize = 0;
  38615. if (!this.isUsed) {
  38616. if (this._initialSize) {
  38617. levelSize = this._initialSize.surface;
  38618. }
  38619. else {
  38620. levelSize = this._size.surface;
  38621. }
  38622. }
  38623. if (this._rightNode) {
  38624. levelSize += this._rightNode.evalFreeSize(0);
  38625. }
  38626. if (this._bottomNode) {
  38627. levelSize += this._bottomNode.evalFreeSize(0);
  38628. }
  38629. return levelSize + size;
  38630. };
  38631. return PackedRect;
  38632. }());
  38633. BABYLON.PackedRect = PackedRect;
  38634. /**
  38635. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  38636. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  38637. * 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.
  38638. */
  38639. var RectPackingMap = (function (_super) {
  38640. __extends(RectPackingMap, _super);
  38641. /**
  38642. * Create an instance of the object with a dimension using the given size
  38643. * @param size The dimension of the rectangle that will contain all the sub ones.
  38644. */
  38645. function RectPackingMap(size) {
  38646. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  38647. this._root = this;
  38648. }
  38649. /**
  38650. * Add a rectangle, finding the best location to store it into the map
  38651. * @param size the dimension of the rectangle to store
  38652. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  38653. */
  38654. RectPackingMap.prototype.addRect = function (size) {
  38655. var node = this.findAndSplitNode(size);
  38656. return node;
  38657. };
  38658. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  38659. /**
  38660. * Return the current space free normalized between [0;1]
  38661. * @returns {}
  38662. */
  38663. get: function () {
  38664. var freeSize = 0;
  38665. freeSize = this.evalFreeSize(freeSize);
  38666. return freeSize / (this._size.width * this._size.height);
  38667. },
  38668. enumerable: true,
  38669. configurable: true
  38670. });
  38671. return RectPackingMap;
  38672. }(PackedRect));
  38673. BABYLON.RectPackingMap = RectPackingMap;
  38674. })(BABYLON || (BABYLON = {}));
  38675. var BABYLON;
  38676. (function (BABYLON) {
  38677. var DynamicFloatArrayElementInfo = (function () {
  38678. function DynamicFloatArrayElementInfo() {
  38679. }
  38680. return DynamicFloatArrayElementInfo;
  38681. }());
  38682. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  38683. /**
  38684. * 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.
  38685. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  38686. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  38687. * 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.
  38688. * 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.
  38689. * 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".
  38690. */
  38691. var DynamicFloatArray = (function () {
  38692. /**
  38693. * Construct an instance of the dynamic float array
  38694. * @param stride size of one element in float (i.e. not bytes!)
  38695. * @param initialElementCount the number of available entries at construction
  38696. */
  38697. function DynamicFloatArray(stride, initialElementCount) {
  38698. this.compareValueOffset = null;
  38699. this.sortingAscending = true;
  38700. this._stride = stride;
  38701. this.buffer = new Float32Array(stride * initialElementCount);
  38702. this._lastUsed = 0;
  38703. this._firstFree = 0;
  38704. this._allEntries = new Array(initialElementCount);
  38705. this._freeEntries = new Array(initialElementCount);
  38706. for (var i = 0; i < initialElementCount; i++) {
  38707. var element = new DynamicFloatArrayElementInfo();
  38708. element.offset = i * stride;
  38709. this._allEntries[i] = element;
  38710. this._freeEntries[initialElementCount - i - 1] = element;
  38711. }
  38712. }
  38713. /**
  38714. * Allocate an element in the array.
  38715. * @return the element info instance that contains the offset into the main buffer of the element's location.
  38716. * Beware, this offset may change when you call pack()
  38717. */
  38718. DynamicFloatArray.prototype.allocElement = function () {
  38719. if (this._freeEntries.length === 0) {
  38720. this._growBuffer();
  38721. }
  38722. var el = this._freeEntries.pop();
  38723. this._lastUsed = Math.max(el.offset, this._lastUsed);
  38724. if (el.offset === this._firstFree) {
  38725. if (this._freeEntries.length > 0) {
  38726. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  38727. }
  38728. else {
  38729. this._firstFree += this._stride;
  38730. }
  38731. }
  38732. return el;
  38733. };
  38734. /**
  38735. * Free the element corresponding to the given element info
  38736. * @param elInfo the element that describe the allocated element
  38737. */
  38738. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  38739. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  38740. this._freeEntries.push(elInfo);
  38741. };
  38742. /**
  38743. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  38744. * 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().
  38745. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  38746. */
  38747. DynamicFloatArray.prototype.pack = function () {
  38748. // no free slot? no need to pack
  38749. if (this._freeEntries.length === 0) {
  38750. return this.buffer;
  38751. }
  38752. // If the buffer is already packed the last used will always be lower than the first free
  38753. // 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.
  38754. if (this._lastUsed < this._firstFree) {
  38755. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  38756. return elementsBuffer_1;
  38757. }
  38758. var s = this._stride;
  38759. // 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
  38760. var lastFree = new DynamicFloatArrayElementInfo();
  38761. lastFree.offset = this.totalElementCount * s;
  38762. this._freeEntries.push(lastFree);
  38763. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  38764. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  38765. var firstFreeSlotOffset = sortedFree[0].offset;
  38766. var freeZoneSize = 1;
  38767. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  38768. var prevOffset = sortedFree[0].offset;
  38769. for (var i = 1; i < sortedFree.length; i++) {
  38770. // 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
  38771. if (firstFreeSlotOffset >= occupiedZoneSize) {
  38772. break;
  38773. }
  38774. var curFree = sortedFree[i];
  38775. var curOffset = curFree.offset;
  38776. // Compute the distance between this offset and the previous
  38777. var distance = curOffset - prevOffset;
  38778. // If the distance is the stride size, they are adjacent, it good, move to the next
  38779. if (distance === s) {
  38780. // Free zone is one element bigger
  38781. ++freeZoneSize;
  38782. // as we're about to iterate to the next, the cur becomes the previous...
  38783. prevOffset = curOffset;
  38784. continue;
  38785. }
  38786. // Distance is bigger, which means there's x element between the previous free and this one
  38787. var usedRange = (distance / s) - 1;
  38788. // Two cases the free zone is smaller than the data to move or bigger
  38789. // Copy what can fit in the free zone
  38790. var curMoveOffset = curOffset - s;
  38791. var copyCount = Math.min(freeZoneSize, usedRange);
  38792. for (var j = 0; j < copyCount; j++) {
  38793. var freeI = firstFreeSlotOffset / s;
  38794. var curI = curMoveOffset / s;
  38795. var moveEl = sortedAll[curI];
  38796. this._moveElement(moveEl, firstFreeSlotOffset);
  38797. var replacedEl = sortedAll[freeI];
  38798. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  38799. replacedEl.offset = curMoveOffset;
  38800. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  38801. sortedAll[freeI] = moveEl;
  38802. sortedAll[curI] = replacedEl;
  38803. curMoveOffset -= s;
  38804. firstFreeSlotOffset += s;
  38805. }
  38806. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  38807. if (freeZoneSize <= usedRange) {
  38808. firstFreeSlotOffset = curMoveOffset + s;
  38809. freeZoneSize = 1 + copyCount;
  38810. }
  38811. else {
  38812. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  38813. }
  38814. // as we're about to iterate to the next, the cur becomes the previous...
  38815. prevOffset = curOffset;
  38816. }
  38817. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  38818. this._lastUsed = firstFreeSlotOffset - s;
  38819. this._firstFree = firstFreeSlotOffset;
  38820. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  38821. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  38822. this._allEntries = sortedAll;
  38823. return elementsBuffer;
  38824. };
  38825. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  38826. for (var i = 0; i < this._stride; i++) {
  38827. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  38828. }
  38829. element.offset = destOffset;
  38830. };
  38831. DynamicFloatArray.prototype._growBuffer = function () {
  38832. // Allocate the new buffer with 50% more entries, copy the content of the current one
  38833. var newElCount = Math.floor(this.totalElementCount * 1.5);
  38834. var newBuffer = new Float32Array(newElCount * this._stride);
  38835. newBuffer.set(this.buffer);
  38836. var curCount = this.totalElementCount;
  38837. var addedCount = newElCount - this.totalElementCount;
  38838. for (var i = 0; i < addedCount; i++) {
  38839. var element = new DynamicFloatArrayElementInfo();
  38840. element.offset = (curCount + i) * this.stride;
  38841. this._allEntries.push(element);
  38842. this._freeEntries[addedCount - i - 1] = element;
  38843. }
  38844. this._firstFree = curCount * this.stride;
  38845. this.buffer = newBuffer;
  38846. };
  38847. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  38848. /**
  38849. * Get the total count of entries that can fit in the current buffer
  38850. * @returns the elements count
  38851. */
  38852. get: function () {
  38853. return this._allEntries.length;
  38854. },
  38855. enumerable: true,
  38856. configurable: true
  38857. });
  38858. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  38859. /**
  38860. * Get the count of free entries that can still be allocated without resizing the buffer
  38861. * @returns the free elements count
  38862. */
  38863. get: function () {
  38864. return this._freeEntries.length;
  38865. },
  38866. enumerable: true,
  38867. configurable: true
  38868. });
  38869. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  38870. /**
  38871. * Get the count of allocated elements
  38872. * @returns the allocated elements count
  38873. */
  38874. get: function () {
  38875. return this._allEntries.length - this._freeEntries.length;
  38876. },
  38877. enumerable: true,
  38878. configurable: true
  38879. });
  38880. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  38881. /**
  38882. * Return the size of one element in float
  38883. * @returns the size in float
  38884. */
  38885. get: function () {
  38886. return this._stride;
  38887. },
  38888. enumerable: true,
  38889. configurable: true
  38890. });
  38891. DynamicFloatArray.prototype.sort = function () {
  38892. var _this = this;
  38893. if (!this.compareValueOffset) {
  38894. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  38895. }
  38896. var count = this.usedElementCount;
  38897. // Do we have to (re)create the sort table?
  38898. if (!this._sortTable || this._sortTable.length < count) {
  38899. // 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...
  38900. var newCount = Math.min(this.totalElementCount, count * 2);
  38901. this._sortTable = new Array(newCount);
  38902. }
  38903. if (!this._sortedTable || this._sortedTable.length !== count) {
  38904. this._sortedTable = new Array(count);
  38905. }
  38906. // Because, you know...
  38907. this.pack();
  38908. //let stride = this.stride;
  38909. //for (let i = 0; i < count; i++) {
  38910. // let si = this._sortTable[i];
  38911. // if (!si) {
  38912. // si = new SortInfo();
  38913. // this._sortTable[i] = si;
  38914. // }
  38915. // si.entry = this._allEntries[i];
  38916. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  38917. // si.swapedOffset = null;
  38918. // this._sortedTable[i] = si;
  38919. //}
  38920. var curOffset = 0;
  38921. var stride = this.stride;
  38922. for (var i = 0; i < count; i++, curOffset += stride) {
  38923. var si = this._sortTable[i];
  38924. if (!si) {
  38925. si = new SortInfo();
  38926. this._sortTable[i] = si;
  38927. }
  38928. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  38929. si.offset = curOffset;
  38930. si.swapedOffset = null;
  38931. this._sortedTable[i] = si;
  38932. }
  38933. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  38934. if (this.sortingAscending) {
  38935. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  38936. }
  38937. else {
  38938. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  38939. }
  38940. var swapElements = function (src, dst) {
  38941. for (var i = 0; i < stride; i++) {
  38942. var tps = _this.buffer[dst + i];
  38943. _this.buffer[dst + i] = _this.buffer[src + i];
  38944. _this.buffer[src + i] = tps;
  38945. }
  38946. };
  38947. // 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:
  38948. // 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),
  38949. // and I still want something with a good algorithm complexity.
  38950. // 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,
  38951. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  38952. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  38953. // 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
  38954. // until we find a SortInfo object without a swapedOffset which means we got the right location
  38955. // 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
  38956. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  38957. for (var i = 0; i < count; i++) {
  38958. // Get the element to move
  38959. var sourceSI = this._sortedTable[i];
  38960. var destSI = this._sortTable[i];
  38961. var sourceOff = sourceSI.offset;
  38962. // If the source changed location, find the new one
  38963. if (sourceSI.swapedOffset) {
  38964. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  38965. var curSI = sourceSI;
  38966. while (curSI.swapedOffset) {
  38967. curSI = this._sortTable[curSI.swapedOffset / stride];
  38968. }
  38969. // Finally get the right location
  38970. sourceOff = curSI.offset;
  38971. }
  38972. // Tag the element being replaced with its new location
  38973. destSI.swapedOffset = sourceOff;
  38974. // Swap elements (only if needed)
  38975. if (sourceOff !== destSI.offset) {
  38976. swapElements(sourceOff, destSI.offset);
  38977. }
  38978. // Update the offset in the corresponding DFAE
  38979. //sourceSI.entry.offset = destSI.entry.offset;
  38980. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  38981. }
  38982. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  38983. return true;
  38984. };
  38985. return DynamicFloatArray;
  38986. }());
  38987. BABYLON.DynamicFloatArray = DynamicFloatArray;
  38988. var SortInfo = (function () {
  38989. function SortInfo() {
  38990. this.compareData = this.offset = this.swapedOffset = null;
  38991. }
  38992. return SortInfo;
  38993. }());
  38994. })(BABYLON || (BABYLON = {}));
  38995. var BABYLON;
  38996. (function (BABYLON) {
  38997. /**
  38998. * This class given information about a given character.
  38999. */
  39000. var CharInfo = (function () {
  39001. function CharInfo() {
  39002. }
  39003. return CharInfo;
  39004. }());
  39005. BABYLON.CharInfo = CharInfo;
  39006. var FontTexture = (function (_super) {
  39007. __extends(FontTexture, _super);
  39008. /**
  39009. * Create a new instance of the FontTexture class
  39010. * @param name the name of the texture
  39011. * @param font the font to use, use the W3C CSS notation
  39012. * @param scene the scene that owns the texture
  39013. * @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
  39014. * @param samplingMode the texture sampling mode
  39015. * @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.
  39016. */
  39017. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample, signedDistanceField) {
  39018. if (maxCharCount === void 0) { maxCharCount = 200; }
  39019. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39020. if (superSample === void 0) { superSample = false; }
  39021. if (signedDistanceField === void 0) { signedDistanceField = false; }
  39022. _super.call(this, null, scene, true, false, samplingMode);
  39023. this._charInfos = {};
  39024. this._curCharCount = 0;
  39025. this._lastUpdateCharCount = -1;
  39026. this._usedCounter = 1;
  39027. this.name = name;
  39028. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39029. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39030. this._sdfScale = 8;
  39031. this._signedDistanceField = signedDistanceField;
  39032. this._superSample = false;
  39033. // SDF will use supersample no matter what, the resolution is otherwise too poor to produce correct result
  39034. if (superSample || signedDistanceField) {
  39035. var sfont = this.getSuperSampleFont(font);
  39036. if (sfont) {
  39037. this._superSample = true;
  39038. font = sfont;
  39039. }
  39040. }
  39041. // First canvas creation to determine the size of the texture to create
  39042. this._canvas = document.createElement("canvas");
  39043. this._context = this._canvas.getContext("2d");
  39044. this._context.font = font;
  39045. this._context.fillStyle = "white";
  39046. this._context.textBaseline = "top";
  39047. this._cachedFontId = null;
  39048. var res = this.getFontHeight(font);
  39049. this._lineHeightSuper = res.height + 4;
  39050. this._lineHeight = this._superSample ? (Math.ceil(this._lineHeightSuper / 2)) : this._lineHeightSuper;
  39051. this._offset = res.offset - 1;
  39052. this._xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  39053. this._yMargin = this._xMargin;
  39054. var maxCharWidth = this._context.measureText("W").width;
  39055. this._spaceWidthSuper = this._context.measureText(" ").width;
  39056. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  39057. // This is an approximate size, but should always be able to fit at least the maxCharCount
  39058. var totalEstSurface = (this._lineHeightSuper + this._yMargin) * (maxCharWidth + this._xMargin) * maxCharCount;
  39059. var edge = Math.sqrt(totalEstSurface);
  39060. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  39061. // Create the texture that will store the font characters
  39062. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  39063. var textureSize = this.getSize();
  39064. this.hasAlpha = this._signedDistanceField === false;
  39065. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  39066. this._canvas = document.createElement("canvas");
  39067. this._canvas.width = textureSize.width;
  39068. this._canvas.height = textureSize.height;
  39069. this._context = this._canvas.getContext("2d");
  39070. this._context.textBaseline = "top";
  39071. this._context.font = font;
  39072. this._context.fillStyle = "white";
  39073. this._context.imageSmoothingEnabled = false;
  39074. this._context.clearRect(0, 0, textureSize.width, textureSize.height);
  39075. // 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
  39076. // 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)
  39077. // So you can see this context as an intermediate one, because it is.
  39078. if (this._signedDistanceField) {
  39079. var sdfC = document.createElement("canvas");
  39080. var s = this._sdfScale;
  39081. sdfC.width = maxCharWidth * s;
  39082. sdfC.height = this._lineHeightSuper * s;
  39083. var sdfCtx = sdfC.getContext("2d");
  39084. sdfCtx.scale(s, s);
  39085. sdfCtx.textBaseline = "top";
  39086. sdfCtx.font = font;
  39087. sdfCtx.fillStyle = "white";
  39088. sdfCtx.imageSmoothingEnabled = false;
  39089. this._sdfCanvas = sdfC;
  39090. this._sdfContext = sdfCtx;
  39091. }
  39092. this._currentFreePosition = BABYLON.Vector2.Zero();
  39093. // Add the basic ASCII based characters
  39094. for (var i = 0x20; i < 0x7F; i++) {
  39095. var c = String.fromCharCode(i);
  39096. this.getChar(c);
  39097. }
  39098. this.update();
  39099. }
  39100. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  39101. get: function () {
  39102. return this._superSample;
  39103. },
  39104. enumerable: true,
  39105. configurable: true
  39106. });
  39107. Object.defineProperty(FontTexture.prototype, "isSignedDistanceField", {
  39108. get: function () {
  39109. return this._signedDistanceField;
  39110. },
  39111. enumerable: true,
  39112. configurable: true
  39113. });
  39114. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  39115. get: function () {
  39116. return this._spaceWidth;
  39117. },
  39118. enumerable: true,
  39119. configurable: true
  39120. });
  39121. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  39122. get: function () {
  39123. return this._lineHeight;
  39124. },
  39125. enumerable: true,
  39126. configurable: true
  39127. });
  39128. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  39129. if (supersample === void 0) { supersample = false; }
  39130. if (signedDistanceField === void 0) { signedDistanceField = false; }
  39131. var s = scene;
  39132. if (!s.__fontTextureCache__) {
  39133. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  39134. }
  39135. var dic = s.__fontTextureCache__;
  39136. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  39137. var ft = dic.get(lfn);
  39138. if (ft) {
  39139. ++ft._usedCounter;
  39140. return ft;
  39141. }
  39142. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample, signedDistanceField);
  39143. ft._cachedFontId = lfn;
  39144. dic.add(lfn, ft);
  39145. return ft;
  39146. };
  39147. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  39148. if (supersample === void 0) { supersample = false; }
  39149. if (signedDistanceField === void 0) { signedDistanceField = false; }
  39150. var s = scene;
  39151. var dic = s.__fontTextureCache__;
  39152. if (!dic) {
  39153. return;
  39154. }
  39155. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  39156. var font = dic.get(lfn);
  39157. if (--font._usedCounter === 0) {
  39158. dic.remove(lfn);
  39159. font.dispose();
  39160. }
  39161. };
  39162. /**
  39163. * Make sure the given char is present in the font map.
  39164. * @param char the character to get or add
  39165. * @return the CharInfo instance corresponding to the given character
  39166. */
  39167. FontTexture.prototype.getChar = function (char) {
  39168. if (char.length !== 1) {
  39169. return null;
  39170. }
  39171. var info = this._charInfos[char];
  39172. if (info) {
  39173. return info;
  39174. }
  39175. info = new CharInfo();
  39176. var measure = this._context.measureText(char);
  39177. var textureSize = this.getSize();
  39178. // we reached the end of the current line?
  39179. var width = Math.round(measure.width);
  39180. if (this._currentFreePosition.x + width + this._xMargin > textureSize.width) {
  39181. this._currentFreePosition.x = 0;
  39182. this._currentFreePosition.y += this._lineHeightSuper + this._yMargin;
  39183. // No more room?
  39184. if (this._currentFreePosition.y > textureSize.height) {
  39185. return this.getChar("!");
  39186. }
  39187. }
  39188. // 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)
  39189. if (this._signedDistanceField) {
  39190. this._sdfContext.clearRect(0, 0, this._sdfCanvas.width, this._sdfCanvas.height);
  39191. this._sdfContext.fillText(char, 0, -this._offset);
  39192. var data = this._sdfContext.getImageData(0, 0, width * this._sdfScale, this._sdfCanvas.height);
  39193. var res = this._computeSDFChar(data);
  39194. this._context.putImageData(res, this._currentFreePosition.x, this._currentFreePosition.y);
  39195. }
  39196. else {
  39197. // Draw the character in the HTML canvas
  39198. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  39199. }
  39200. // Fill the CharInfo object
  39201. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  39202. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  39203. if (this._signedDistanceField) {
  39204. var off = 1 / textureSize.width;
  39205. info.topLeftUV.addInPlace(new BABYLON.Vector2(off, off));
  39206. info.bottomRightUV.addInPlace(new BABYLON.Vector2(off, off));
  39207. }
  39208. info.charWidth = this._superSample ? (width / 2) : width;
  39209. // Add the info structure
  39210. this._charInfos[char] = info;
  39211. this._curCharCount++;
  39212. // Set the next position
  39213. this._currentFreePosition.x += width + this._xMargin;
  39214. return info;
  39215. };
  39216. FontTexture.prototype._computeSDFChar = function (source) {
  39217. var scl = this._sdfScale;
  39218. var sw = source.width;
  39219. var sh = source.height;
  39220. var dw = sw / scl;
  39221. var dh = sh / scl;
  39222. var roffx = 0;
  39223. var roffy = 0;
  39224. // We shouldn't look beyond half of the biggest between width and height
  39225. var radius = scl;
  39226. var br = radius - 1;
  39227. var lookupSrc = function (dx, dy, offX, offY, lookVis) {
  39228. var sx = dx * scl;
  39229. var sy = dy * scl;
  39230. // Looking out of the area? return true to make the test going on
  39231. if (((sx + offX) < 0) || ((sx + offX) >= sw) || ((sy + offY) < 0) || ((sy + offY) >= sh)) {
  39232. return true;
  39233. }
  39234. // Get the pixel we want
  39235. var val = source.data[(((sy + offY) * sw) + (sx + offX)) * 4];
  39236. var res = (val > 0) === lookVis;
  39237. if (!res) {
  39238. roffx = offX;
  39239. roffy = offY;
  39240. }
  39241. return res;
  39242. };
  39243. var lookupArea = function (dx, dy, lookVis) {
  39244. // 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
  39245. if (lookupSrc(dx, dy, 0, br, lookVis) &&
  39246. lookupSrc(dx, dy, 0, -br, lookVis) &&
  39247. lookupSrc(dx, dy, -br, 0, lookVis) &&
  39248. lookupSrc(dx, dy, br, 0, lookVis)) {
  39249. return 0;
  39250. }
  39251. for (var i = 1; i <= radius; i++) {
  39252. // Quick test N, S, W, E
  39253. 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)) {
  39254. return i * i; // Squared Distance is simple to compute in this case
  39255. }
  39256. // Test the frame area (except the N, S, W, E spots) from the nearest point from the center to the further one
  39257. for (var j = 1; j <= i; j++) {
  39258. if (!lookupSrc(dx, dy, -j, i, lookVis) || !lookupSrc(dx, dy, j, i, lookVis) ||
  39259. !lookupSrc(dx, dy, i, -j, lookVis) || !lookupSrc(dx, dy, i, j, lookVis) ||
  39260. !lookupSrc(dx, dy, -j, -i, lookVis) || !lookupSrc(dx, dy, j, -i, lookVis) ||
  39261. !lookupSrc(dx, dy, -i, -j, lookVis) || !lookupSrc(dx, dy, -i, j, lookVis)) {
  39262. // We found the nearest texel having and opposite state, store the squared length
  39263. var res_1 = (i * i) + (j * j);
  39264. var count = 1;
  39265. // 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
  39266. if (!lookupSrc(dx, dy, roffx - 1, roffy, lookVis)) {
  39267. res_1 += (roffx - 1) * (roffx - 1) + roffy * roffy;
  39268. ++count;
  39269. }
  39270. if (!lookupSrc(dx, dy, roffx + 1, roffy, lookVis)) {
  39271. res_1 += (roffx + 1) * (roffx + 1) + roffy * roffy;
  39272. ++count;
  39273. }
  39274. if (!lookupSrc(dx, dy, roffx, roffy - 1, lookVis)) {
  39275. res_1 += roffx * roffx + (roffy - 1) * (roffy - 1);
  39276. ++count;
  39277. }
  39278. if (!lookupSrc(dx, dy, roffx, roffy + 1, lookVis)) {
  39279. res_1 += roffx * roffx + (roffy + 1) * (roffy + 1);
  39280. ++count;
  39281. }
  39282. if (!lookupSrc(dx, dy, roffx - 1, roffy - 1, lookVis)) {
  39283. res_1 += (roffx - 1) * (roffx - 1) + (roffy - 1) * (roffy - 1);
  39284. ++count;
  39285. }
  39286. if (!lookupSrc(dx, dy, roffx + 1, roffy + 1, lookVis)) {
  39287. res_1 += (roffx + 1) * (roffx + 1) + (roffy + 1) * (roffy + 1);
  39288. ++count;
  39289. }
  39290. if (!lookupSrc(dx, dy, roffx + 1, roffy - 1, lookVis)) {
  39291. res_1 += (roffx + 1) * (roffx + 1) + (roffy - 1) * (roffy - 1);
  39292. ++count;
  39293. }
  39294. if (!lookupSrc(dx, dy, roffx - 1, roffy + 1, lookVis)) {
  39295. res_1 += (roffx - 1) * (roffx - 1) + (roffy + 1) * (roffy + 1);
  39296. ++count;
  39297. }
  39298. // Compute the average based on the accumulated distance
  39299. return res_1 / count;
  39300. }
  39301. }
  39302. }
  39303. return 0;
  39304. };
  39305. var tmp = new Array(dw * dh);
  39306. for (var y = 0; y < dh; y++) {
  39307. for (var x = 0; x < dw; x++) {
  39308. var curState = lookupSrc(x, y, 0, 0, true);
  39309. var d = lookupArea(x, y, curState);
  39310. if (d === 0) {
  39311. d = radius * radius * 2;
  39312. }
  39313. tmp[(y * dw) + x] = curState ? d : -d;
  39314. }
  39315. }
  39316. var res = this._context.createImageData(dw, dh);
  39317. var size = dw * dh;
  39318. for (var j = 0; j < size; j++) {
  39319. var d = tmp[j];
  39320. var sign = (d < 0) ? -1 : 1;
  39321. d = Math.sqrt(Math.abs(d)) * sign;
  39322. d *= 127.5 / radius;
  39323. d += 127.5;
  39324. if (d < 0) {
  39325. d = 0;
  39326. }
  39327. else if (d > 255) {
  39328. d = 255;
  39329. }
  39330. d += 0.5;
  39331. res.data[j * 4 + 0] = d;
  39332. res.data[j * 4 + 1] = d;
  39333. res.data[j * 4 + 2] = d;
  39334. res.data[j * 4 + 3] = 255;
  39335. }
  39336. return res;
  39337. };
  39338. FontTexture.prototype.measureText = function (text, tabulationSize) {
  39339. if (tabulationSize === void 0) { tabulationSize = 4; }
  39340. var maxWidth = 0;
  39341. var curWidth = 0;
  39342. var lineCount = 1;
  39343. var charxpos = 0;
  39344. // Parse each char of the string
  39345. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  39346. var char = text_1[_i];
  39347. // Next line feed?
  39348. if (char === "\n") {
  39349. maxWidth = Math.max(maxWidth, curWidth);
  39350. charxpos = 0;
  39351. curWidth = 0;
  39352. ++lineCount;
  39353. continue;
  39354. }
  39355. // Tabulation ?
  39356. if (char === "\t") {
  39357. var nextPos = charxpos + tabulationSize;
  39358. nextPos = nextPos - (nextPos % tabulationSize);
  39359. curWidth += (nextPos - charxpos) * this.spaceWidth;
  39360. charxpos = nextPos;
  39361. continue;
  39362. }
  39363. if (char < " ") {
  39364. continue;
  39365. }
  39366. curWidth += this.getChar(char).charWidth;
  39367. ++charxpos;
  39368. }
  39369. maxWidth = Math.max(maxWidth, curWidth);
  39370. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  39371. };
  39372. FontTexture.prototype.getSuperSampleFont = function (font) {
  39373. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  39374. 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*$/;
  39375. var res = font.toLocaleLowerCase().match(regex);
  39376. if (res == null) {
  39377. return null;
  39378. }
  39379. var size = parseInt(res[4]);
  39380. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  39381. var newFont = "";
  39382. for (var j = 1; j < res.length; j++) {
  39383. if (res[j] != null) {
  39384. newFont += res[j] + " ";
  39385. }
  39386. }
  39387. return newFont;
  39388. };
  39389. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  39390. FontTexture.prototype.getFontHeight = function (font) {
  39391. var fontDraw = document.createElement("canvas");
  39392. var ctx = fontDraw.getContext('2d');
  39393. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  39394. ctx.textBaseline = 'top';
  39395. ctx.fillStyle = 'white';
  39396. ctx.font = font;
  39397. ctx.fillText('jH|', 0, 0);
  39398. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  39399. var start = -1;
  39400. var end = -1;
  39401. for (var row = 0; row < fontDraw.height; row++) {
  39402. for (var column = 0; column < fontDraw.width; column++) {
  39403. var index = (row * fontDraw.width + column) * 4;
  39404. if (pixels[index] === 0) {
  39405. if (column === fontDraw.width - 1 && start !== -1) {
  39406. end = row;
  39407. row = fontDraw.height;
  39408. break;
  39409. }
  39410. continue;
  39411. }
  39412. else {
  39413. if (start === -1) {
  39414. start = row;
  39415. }
  39416. break;
  39417. }
  39418. }
  39419. }
  39420. return { height: (end - start) + 1, offset: start - 1 };
  39421. };
  39422. Object.defineProperty(FontTexture.prototype, "canRescale", {
  39423. get: function () {
  39424. return false;
  39425. },
  39426. enumerable: true,
  39427. configurable: true
  39428. });
  39429. FontTexture.prototype.getContext = function () {
  39430. return this._context;
  39431. };
  39432. /**
  39433. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  39434. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  39435. */
  39436. FontTexture.prototype.update = function () {
  39437. // Update only if there's new char added since the previous update
  39438. if (this._lastUpdateCharCount < this._curCharCount) {
  39439. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  39440. this._lastUpdateCharCount = this._curCharCount;
  39441. }
  39442. };
  39443. // cloning should be prohibited, there's no point to duplicate this texture at all
  39444. FontTexture.prototype.clone = function () {
  39445. return null;
  39446. };
  39447. /**
  39448. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  39449. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  39450. */
  39451. FontTexture.prototype.incCachedFontTextureCounter = function () {
  39452. ++this._usedCounter;
  39453. };
  39454. /**
  39455. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  39456. */
  39457. FontTexture.prototype.decCachedFontTextureCounter = function () {
  39458. var s = this.getScene();
  39459. var dic = s.__fontTextureCache__;
  39460. if (!dic) {
  39461. return;
  39462. }
  39463. if (--this._usedCounter === 0) {
  39464. dic.remove(this._cachedFontId);
  39465. this.dispose();
  39466. }
  39467. };
  39468. return FontTexture;
  39469. }(BABYLON.Texture));
  39470. BABYLON.FontTexture = FontTexture;
  39471. })(BABYLON || (BABYLON = {}));
  39472. var BABYLON;
  39473. (function (BABYLON) {
  39474. var MapTexture = (function (_super) {
  39475. __extends(MapTexture, _super);
  39476. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  39477. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39478. if (useMipMap === void 0) { useMipMap = false; }
  39479. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  39480. this.name = name;
  39481. this._size = size;
  39482. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39483. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39484. // Create the rectPackMap that will allocate portion of the texture
  39485. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  39486. // Create the texture that will store the content
  39487. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  39488. }
  39489. /**
  39490. * Allocate a rectangle of a given size in the texture map
  39491. * @param size the size of the rectangle to allocation
  39492. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  39493. */
  39494. MapTexture.prototype.allocateRect = function (size) {
  39495. return this._rectPackingMap.addRect(size);
  39496. };
  39497. /**
  39498. * Free a given rectangle from the texture map
  39499. * @param rectInfo the instance corresponding to the rect to free.
  39500. */
  39501. MapTexture.prototype.freeRect = function (rectInfo) {
  39502. if (rectInfo) {
  39503. rectInfo.freeContent();
  39504. }
  39505. };
  39506. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  39507. /**
  39508. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  39509. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  39510. * @returns {}
  39511. */
  39512. get: function () {
  39513. return this._rectPackingMap.freeSpace;
  39514. },
  39515. enumerable: true,
  39516. configurable: true
  39517. });
  39518. /**
  39519. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  39520. * 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.
  39521. * Don't forget to call unbindTexture when you're done rendering
  39522. * @param rect the zone to render to
  39523. * @param clear true to clear the portion's color/depth data
  39524. */
  39525. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  39526. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  39527. };
  39528. /**
  39529. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  39530. * 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.
  39531. * Don't forget to call unbindTexture when you're done rendering
  39532. * @param pos the position into the texture
  39533. * @param size the portion to fit the clip space to
  39534. * @param clear true to clear the portion's color/depth data
  39535. */
  39536. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  39537. var engine = this.getScene().getEngine();
  39538. engine.bindFramebuffer(this._texture);
  39539. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  39540. if (clear) {
  39541. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  39542. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  39543. }
  39544. };
  39545. /**
  39546. * Unbind the texture map from the rendering engine.
  39547. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  39548. * @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.
  39549. */
  39550. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  39551. // Dump ?
  39552. if (dumpForDebug) {
  39553. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  39554. }
  39555. var engine = this.getScene().getEngine();
  39556. if (this._replacedViewport) {
  39557. engine.setViewport(this._replacedViewport);
  39558. this._replacedViewport = null;
  39559. }
  39560. engine.unBindFramebuffer(this._texture);
  39561. };
  39562. Object.defineProperty(MapTexture.prototype, "canRescale", {
  39563. get: function () {
  39564. return false;
  39565. },
  39566. enumerable: true,
  39567. configurable: true
  39568. });
  39569. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  39570. // Anyway, there's not much point to use this method for this kind of texture I guess
  39571. MapTexture.prototype.clone = function () {
  39572. return null;
  39573. };
  39574. return MapTexture;
  39575. }(BABYLON.Texture));
  39576. BABYLON.MapTexture = MapTexture;
  39577. })(BABYLON || (BABYLON = {}));
  39578. var BABYLON;
  39579. (function (BABYLON) {
  39580. var ShaderMaterial = (function (_super) {
  39581. __extends(ShaderMaterial, _super);
  39582. function ShaderMaterial(name, scene, shaderPath, options) {
  39583. _super.call(this, name, scene);
  39584. this._textures = {};
  39585. this._textureArrays = {};
  39586. this._floats = {};
  39587. this._floatsArrays = {};
  39588. this._colors3 = {};
  39589. this._colors4 = {};
  39590. this._vectors2 = {};
  39591. this._vectors3 = {};
  39592. this._vectors4 = {};
  39593. this._matrices = {};
  39594. this._matrices3x3 = {};
  39595. this._matrices2x2 = {};
  39596. this._vectors3Arrays = {};
  39597. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  39598. this._shaderPath = shaderPath;
  39599. options.needAlphaBlending = options.needAlphaBlending || false;
  39600. options.needAlphaTesting = options.needAlphaTesting || false;
  39601. options.attributes = options.attributes || ["position", "normal", "uv"];
  39602. options.uniforms = options.uniforms || ["worldViewProjection"];
  39603. options.samplers = options.samplers || [];
  39604. options.defines = options.defines || [];
  39605. this._options = options;
  39606. }
  39607. ShaderMaterial.prototype.needAlphaBlending = function () {
  39608. return this._options.needAlphaBlending;
  39609. };
  39610. ShaderMaterial.prototype.needAlphaTesting = function () {
  39611. return this._options.needAlphaTesting;
  39612. };
  39613. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  39614. if (this._options.uniforms.indexOf(uniformName) === -1) {
  39615. this._options.uniforms.push(uniformName);
  39616. }
  39617. };
  39618. ShaderMaterial.prototype.setTexture = function (name, texture) {
  39619. if (this._options.samplers.indexOf(name) === -1) {
  39620. this._options.samplers.push(name);
  39621. }
  39622. this._textures[name] = texture;
  39623. return this;
  39624. };
  39625. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  39626. if (this._options.samplers.indexOf(name) === -1) {
  39627. this._options.samplers.push(name);
  39628. }
  39629. this._checkUniform(name);
  39630. this._textureArrays[name] = textures;
  39631. return this;
  39632. };
  39633. ShaderMaterial.prototype.setFloat = function (name, value) {
  39634. this._checkUniform(name);
  39635. this._floats[name] = value;
  39636. return this;
  39637. };
  39638. ShaderMaterial.prototype.setFloats = function (name, value) {
  39639. this._checkUniform(name);
  39640. this._floatsArrays[name] = value;
  39641. return this;
  39642. };
  39643. ShaderMaterial.prototype.setColor3 = function (name, value) {
  39644. this._checkUniform(name);
  39645. this._colors3[name] = value;
  39646. return this;
  39647. };
  39648. ShaderMaterial.prototype.setColor4 = function (name, value) {
  39649. this._checkUniform(name);
  39650. this._colors4[name] = value;
  39651. return this;
  39652. };
  39653. ShaderMaterial.prototype.setVector2 = function (name, value) {
  39654. this._checkUniform(name);
  39655. this._vectors2[name] = value;
  39656. return this;
  39657. };
  39658. ShaderMaterial.prototype.setVector3 = function (name, value) {
  39659. this._checkUniform(name);
  39660. this._vectors3[name] = value;
  39661. return this;
  39662. };
  39663. ShaderMaterial.prototype.setVector4 = function (name, value) {
  39664. this._checkUniform(name);
  39665. this._vectors4[name] = value;
  39666. return this;
  39667. };
  39668. ShaderMaterial.prototype.setMatrix = function (name, value) {
  39669. this._checkUniform(name);
  39670. this._matrices[name] = value;
  39671. return this;
  39672. };
  39673. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  39674. this._checkUniform(name);
  39675. this._matrices3x3[name] = value;
  39676. return this;
  39677. };
  39678. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  39679. this._checkUniform(name);
  39680. this._matrices2x2[name] = value;
  39681. return this;
  39682. };
  39683. ShaderMaterial.prototype.setArray3 = function (name, value) {
  39684. this._checkUniform(name);
  39685. this._vectors3Arrays[name] = value;
  39686. return this;
  39687. };
  39688. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  39689. var scene = this.getScene();
  39690. var engine = scene.getEngine();
  39691. if (!this.checkReadyOnEveryCall) {
  39692. if (this._renderId === scene.getRenderId()) {
  39693. return true;
  39694. }
  39695. }
  39696. // Instances
  39697. var defines = [];
  39698. var fallbacks = new BABYLON.EffectFallbacks();
  39699. if (useInstances) {
  39700. defines.push("#define INSTANCES");
  39701. }
  39702. for (var index = 0; index < this._options.defines.length; index++) {
  39703. defines.push(this._options.defines[index]);
  39704. }
  39705. // Bones
  39706. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  39707. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39708. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39709. fallbacks.addCPUSkinningFallback(0, mesh);
  39710. }
  39711. // Alpha test
  39712. if (engine.getAlphaTesting()) {
  39713. defines.push("#define ALPHATEST");
  39714. }
  39715. var previousEffect = this._effect;
  39716. var join = defines.join("\n");
  39717. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  39718. if (!this._effect.isReady()) {
  39719. return false;
  39720. }
  39721. if (previousEffect !== this._effect) {
  39722. scene.resetCachedMaterial();
  39723. }
  39724. this._renderId = scene.getRenderId();
  39725. return true;
  39726. };
  39727. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39728. var scene = this.getScene();
  39729. if (this._options.uniforms.indexOf("world") !== -1) {
  39730. this._effect.setMatrix("world", world);
  39731. }
  39732. if (this._options.uniforms.indexOf("worldView") !== -1) {
  39733. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  39734. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  39735. }
  39736. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  39737. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  39738. }
  39739. };
  39740. ShaderMaterial.prototype.bind = function (world, mesh) {
  39741. // Std values
  39742. this.bindOnlyWorldMatrix(world);
  39743. if (this.getScene().getCachedMaterial() !== this) {
  39744. if (this._options.uniforms.indexOf("view") !== -1) {
  39745. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  39746. }
  39747. if (this._options.uniforms.indexOf("projection") !== -1) {
  39748. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  39749. }
  39750. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  39751. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  39752. }
  39753. // Bones
  39754. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  39755. var name;
  39756. // Texture
  39757. for (name in this._textures) {
  39758. this._effect.setTexture(name, this._textures[name]);
  39759. }
  39760. // Texture arrays
  39761. for (name in this._textureArrays) {
  39762. this._effect.setTextureArray(name, this._textureArrays[name]);
  39763. }
  39764. // Float
  39765. for (name in this._floats) {
  39766. this._effect.setFloat(name, this._floats[name]);
  39767. }
  39768. // Float s
  39769. for (name in this._floatsArrays) {
  39770. this._effect.setArray(name, this._floatsArrays[name]);
  39771. }
  39772. // Color3
  39773. for (name in this._colors3) {
  39774. this._effect.setColor3(name, this._colors3[name]);
  39775. }
  39776. // Color4
  39777. for (name in this._colors4) {
  39778. var color = this._colors4[name];
  39779. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  39780. }
  39781. // Vector2
  39782. for (name in this._vectors2) {
  39783. this._effect.setVector2(name, this._vectors2[name]);
  39784. }
  39785. // Vector3
  39786. for (name in this._vectors3) {
  39787. this._effect.setVector3(name, this._vectors3[name]);
  39788. }
  39789. // Vector4
  39790. for (name in this._vectors4) {
  39791. this._effect.setVector4(name, this._vectors4[name]);
  39792. }
  39793. // Matrix
  39794. for (name in this._matrices) {
  39795. this._effect.setMatrix(name, this._matrices[name]);
  39796. }
  39797. // Matrix 3x3
  39798. for (name in this._matrices3x3) {
  39799. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  39800. }
  39801. // Matrix 2x2
  39802. for (name in this._matrices2x2) {
  39803. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  39804. }
  39805. // Vector3Array
  39806. for (name in this._vectors3Arrays) {
  39807. this._effect.setArray3(name, this._vectors3Arrays[name]);
  39808. }
  39809. }
  39810. _super.prototype.bind.call(this, world, mesh);
  39811. };
  39812. ShaderMaterial.prototype.clone = function (name) {
  39813. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  39814. return newShaderMaterial;
  39815. };
  39816. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39817. if (forceDisposeTextures) {
  39818. var name;
  39819. for (name in this._textures) {
  39820. this._textures[name].dispose();
  39821. }
  39822. for (name in this._textureArrays) {
  39823. var array = this._textureArrays[name];
  39824. for (var index = 0; index < array.length; index++) {
  39825. array[index].dispose();
  39826. }
  39827. }
  39828. }
  39829. this._textures = {};
  39830. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39831. };
  39832. ShaderMaterial.prototype.serialize = function () {
  39833. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39834. serializationObject.customType = "BABYLON.ShaderMaterial";
  39835. serializationObject.options = this._options;
  39836. serializationObject.shaderPath = this._shaderPath;
  39837. var name;
  39838. // Texture
  39839. serializationObject.textures = {};
  39840. for (name in this._textures) {
  39841. serializationObject.textures[name] = this._textures[name].serialize();
  39842. }
  39843. // Texture arrays
  39844. serializationObject.textureArrays = {};
  39845. for (name in this._textureArrays) {
  39846. serializationObject.textureArrays[name] = [];
  39847. var array = this._textureArrays[name];
  39848. for (var index = 0; index < array.length; index++) {
  39849. serializationObject.textureArrays[name].push(array[index].serialize());
  39850. }
  39851. }
  39852. // Float
  39853. serializationObject.floats = {};
  39854. for (name in this._floats) {
  39855. serializationObject.floats[name] = this._floats[name];
  39856. }
  39857. // Float s
  39858. serializationObject.floatArrays = {};
  39859. for (name in this._floatsArrays) {
  39860. serializationObject.floatArrays[name] = this._floatsArrays[name];
  39861. }
  39862. // Color3
  39863. serializationObject.colors3 = {};
  39864. for (name in this._colors3) {
  39865. serializationObject.colors3[name] = this._colors3[name].asArray();
  39866. }
  39867. // Color4
  39868. serializationObject.colors4 = {};
  39869. for (name in this._colors4) {
  39870. serializationObject.colors4[name] = this._colors4[name].asArray();
  39871. }
  39872. // Vector2
  39873. serializationObject.vectors2 = {};
  39874. for (name in this._vectors2) {
  39875. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  39876. }
  39877. // Vector3
  39878. serializationObject.vectors3 = {};
  39879. for (name in this._vectors3) {
  39880. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  39881. }
  39882. // Vector4
  39883. serializationObject.vectors4 = {};
  39884. for (name in this._vectors4) {
  39885. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  39886. }
  39887. // Matrix
  39888. serializationObject.matrices = {};
  39889. for (name in this._matrices) {
  39890. serializationObject.matrices[name] = this._matrices[name].asArray();
  39891. }
  39892. // Matrix 3x3
  39893. serializationObject.matrices3x3 = {};
  39894. for (name in this._matrices3x3) {
  39895. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  39896. }
  39897. // Matrix 2x2
  39898. serializationObject.matrices2x2 = {};
  39899. for (name in this._matrices2x2) {
  39900. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  39901. }
  39902. // Vector3Array
  39903. serializationObject.vectors3Arrays = {};
  39904. for (name in this._vectors3Arrays) {
  39905. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  39906. }
  39907. return serializationObject;
  39908. };
  39909. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  39910. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  39911. var name;
  39912. // Texture
  39913. for (name in source.textures) {
  39914. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  39915. }
  39916. // Texture arrays
  39917. for (name in source.textureArrays) {
  39918. var array = source.textureArrays[name];
  39919. var textureArray = new Array();
  39920. for (var index = 0; index < array.length; index++) {
  39921. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  39922. }
  39923. material.setTextureArray(name, textureArray);
  39924. }
  39925. // Float
  39926. for (name in source.floats) {
  39927. material.setFloat(name, source.floats[name]);
  39928. }
  39929. // Float s
  39930. for (name in source.floatsArrays) {
  39931. material.setFloats(name, source.floatsArrays[name]);
  39932. }
  39933. // Color3
  39934. for (name in source.colors3) {
  39935. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  39936. }
  39937. // Color4
  39938. for (name in source.colors4) {
  39939. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  39940. }
  39941. // Vector2
  39942. for (name in source.vectors2) {
  39943. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  39944. }
  39945. // Vector3
  39946. for (name in source.vectors3) {
  39947. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  39948. }
  39949. // Vector4
  39950. for (name in source.vectors4) {
  39951. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  39952. }
  39953. // Matrix
  39954. for (name in source.matrices) {
  39955. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  39956. }
  39957. // Matrix 3x3
  39958. for (name in source.matrices3x3) {
  39959. material.setMatrix3x3(name, source.matrices3x3[name]);
  39960. }
  39961. // Matrix 2x2
  39962. for (name in source.matrices2x2) {
  39963. material.setMatrix2x2(name, source.matrices2x2[name]);
  39964. }
  39965. // Vector3Array
  39966. for (name in source.vectors3Arrays) {
  39967. material.setArray3(name, source.vectors3Arrays[name]);
  39968. }
  39969. return material;
  39970. };
  39971. return ShaderMaterial;
  39972. }(BABYLON.Material));
  39973. BABYLON.ShaderMaterial = ShaderMaterial;
  39974. })(BABYLON || (BABYLON = {}));
  39975. var BABYLON;
  39976. (function (BABYLON) {
  39977. var Internals;
  39978. (function (Internals) {
  39979. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  39980. // All values and structures referenced from:
  39981. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  39982. var DDS_MAGIC = 0x20534444;
  39983. 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;
  39984. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  39985. 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;
  39986. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  39987. function FourCCToInt32(value) {
  39988. return value.charCodeAt(0) +
  39989. (value.charCodeAt(1) << 8) +
  39990. (value.charCodeAt(2) << 16) +
  39991. (value.charCodeAt(3) << 24);
  39992. }
  39993. function Int32ToFourCC(value) {
  39994. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  39995. }
  39996. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  39997. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  39998. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  39999. var headerLengthInt = 31; // The header length in 32 bit ints
  40000. // Offsets into the header array
  40001. var off_magic = 0;
  40002. var off_size = 1;
  40003. var off_flags = 2;
  40004. var off_height = 3;
  40005. var off_width = 4;
  40006. var off_mipmapCount = 7;
  40007. var off_pfFlags = 20;
  40008. var off_pfFourCC = 21;
  40009. var off_RGBbpp = 22;
  40010. var off_RMask = 23;
  40011. var off_GMask = 24;
  40012. var off_BMask = 25;
  40013. var off_AMask = 26;
  40014. var off_caps1 = 27;
  40015. var off_caps2 = 28;
  40016. ;
  40017. var DDSTools = (function () {
  40018. function DDSTools() {
  40019. }
  40020. DDSTools.GetDDSInfo = function (arrayBuffer) {
  40021. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  40022. var mipmapCount = 1;
  40023. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  40024. mipmapCount = Math.max(1, header[off_mipmapCount]);
  40025. }
  40026. return {
  40027. width: header[off_width],
  40028. height: header[off_height],
  40029. mipmapCount: mipmapCount,
  40030. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  40031. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  40032. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  40033. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  40034. };
  40035. };
  40036. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  40037. var byteArray = new Uint8Array(dataLength);
  40038. var srcData = new Uint8Array(arrayBuffer);
  40039. var index = 0;
  40040. for (var y = height - 1; y >= 0; y--) {
  40041. for (var x = 0; x < width; x++) {
  40042. var srcPos = dataOffset + (x + y * width) * 4;
  40043. byteArray[index + 2] = srcData[srcPos];
  40044. byteArray[index + 1] = srcData[srcPos + 1];
  40045. byteArray[index] = srcData[srcPos + 2];
  40046. byteArray[index + 3] = srcData[srcPos + 3];
  40047. index += 4;
  40048. }
  40049. }
  40050. return byteArray;
  40051. };
  40052. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  40053. var byteArray = new Uint8Array(dataLength);
  40054. var srcData = new Uint8Array(arrayBuffer);
  40055. var index = 0;
  40056. for (var y = height - 1; y >= 0; y--) {
  40057. for (var x = 0; x < width; x++) {
  40058. var srcPos = dataOffset + (x + y * width) * 3;
  40059. byteArray[index + 2] = srcData[srcPos];
  40060. byteArray[index + 1] = srcData[srcPos + 1];
  40061. byteArray[index] = srcData[srcPos + 2];
  40062. index += 3;
  40063. }
  40064. }
  40065. return byteArray;
  40066. };
  40067. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  40068. var byteArray = new Uint8Array(dataLength);
  40069. var srcData = new Uint8Array(arrayBuffer);
  40070. var index = 0;
  40071. for (var y = height - 1; y >= 0; y--) {
  40072. for (var x = 0; x < width; x++) {
  40073. var srcPos = dataOffset + (x + y * width);
  40074. byteArray[index] = srcData[srcPos];
  40075. index++;
  40076. }
  40077. }
  40078. return byteArray;
  40079. };
  40080. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  40081. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  40082. if (header[off_magic] != DDS_MAGIC) {
  40083. BABYLON.Tools.Error("Invalid magic number in DDS header");
  40084. return;
  40085. }
  40086. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  40087. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  40088. return;
  40089. }
  40090. if (info.isFourCC) {
  40091. fourCC = header[off_pfFourCC];
  40092. switch (fourCC) {
  40093. case FOURCC_DXT1:
  40094. blockBytes = 8;
  40095. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  40096. break;
  40097. case FOURCC_DXT3:
  40098. blockBytes = 16;
  40099. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  40100. break;
  40101. case FOURCC_DXT5:
  40102. blockBytes = 16;
  40103. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  40104. break;
  40105. default:
  40106. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  40107. return;
  40108. }
  40109. }
  40110. mipmapCount = 1;
  40111. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  40112. mipmapCount = Math.max(1, header[off_mipmapCount]);
  40113. }
  40114. var bpp = header[off_RGBbpp];
  40115. for (var face = 0; face < faces; face++) {
  40116. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  40117. width = header[off_width];
  40118. height = header[off_height];
  40119. dataOffset = header[off_size] + 4;
  40120. for (i = 0; i < mipmapCount; ++i) {
  40121. if (info.isRGB) {
  40122. if (bpp === 24) {
  40123. dataLength = width * height * 3;
  40124. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  40125. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  40126. }
  40127. else {
  40128. dataLength = width * height * 4;
  40129. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  40130. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  40131. }
  40132. }
  40133. else if (info.isLuminance) {
  40134. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  40135. var unpaddedRowSize = width;
  40136. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  40137. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  40138. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  40139. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  40140. }
  40141. else {
  40142. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  40143. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  40144. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  40145. }
  40146. dataOffset += dataLength;
  40147. width *= 0.5;
  40148. height *= 0.5;
  40149. width = Math.max(1.0, width);
  40150. height = Math.max(1.0, height);
  40151. }
  40152. }
  40153. };
  40154. return DDSTools;
  40155. }());
  40156. Internals.DDSTools = DDSTools;
  40157. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40158. })(BABYLON || (BABYLON = {}));
  40159. var BABYLON;
  40160. (function (BABYLON) {
  40161. var CannonJSPlugin = (function () {
  40162. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  40163. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  40164. if (iterations === void 0) { iterations = 10; }
  40165. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  40166. this.name = "CannonJSPlugin";
  40167. this._physicsMaterials = [];
  40168. this._fixedTimeStep = 1 / 60;
  40169. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  40170. this._currentCollisionGroup = 2;
  40171. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  40172. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  40173. this._tmpPosition = BABYLON.Vector3.Zero();
  40174. this._tmpQuaternion = new BABYLON.Quaternion();
  40175. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  40176. this._tmpDeltaRotation = new BABYLON.Quaternion();
  40177. this._tmpUnityRotation = new BABYLON.Quaternion();
  40178. if (!this.isSupported()) {
  40179. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  40180. return;
  40181. }
  40182. this.world = new CANNON.World();
  40183. this.world.broadphase = new CANNON.NaiveBroadphase();
  40184. this.world.solver.iterations = iterations;
  40185. }
  40186. CannonJSPlugin.prototype.setGravity = function (gravity) {
  40187. this.world.gravity.copy(gravity);
  40188. };
  40189. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  40190. this._fixedTimeStep = timeStep;
  40191. };
  40192. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  40193. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  40194. };
  40195. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  40196. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  40197. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  40198. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  40199. };
  40200. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  40201. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  40202. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  40203. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  40204. };
  40205. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  40206. //parent-child relationship. Does this impostor has a parent impostor?
  40207. if (impostor.parent) {
  40208. if (impostor.physicsBody) {
  40209. this.removePhysicsBody(impostor);
  40210. //TODO is that needed?
  40211. impostor.forceUpdate();
  40212. }
  40213. return;
  40214. }
  40215. //should a new body be created for this impostor?
  40216. if (impostor.isBodyInitRequired()) {
  40217. var shape = this._createShape(impostor);
  40218. //unregister events, if body is being changed
  40219. var oldBody = impostor.physicsBody;
  40220. if (oldBody) {
  40221. this.removePhysicsBody(impostor);
  40222. }
  40223. //create the body and material
  40224. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  40225. var bodyCreationObject = {
  40226. mass: impostor.getParam("mass"),
  40227. material: material
  40228. };
  40229. // A simple extend, in case native options were used.
  40230. var nativeOptions = impostor.getParam("nativeOptions");
  40231. for (var key in nativeOptions) {
  40232. if (nativeOptions.hasOwnProperty(key)) {
  40233. bodyCreationObject[key] = nativeOptions[key];
  40234. }
  40235. }
  40236. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  40237. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  40238. this.world.addEventListener("preStep", impostor.beforeStep);
  40239. this.world.addEventListener("postStep", impostor.afterStep);
  40240. impostor.physicsBody.addShape(shape);
  40241. this.world.add(impostor.physicsBody);
  40242. //try to keep the body moving in the right direction by taking old properties.
  40243. //Should be tested!
  40244. if (oldBody) {
  40245. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  40246. impostor.physicsBody[param].copy(oldBody[param]);
  40247. });
  40248. }
  40249. this._processChildMeshes(impostor);
  40250. }
  40251. //now update the body's transformation
  40252. this._updatePhysicsBodyTransformation(impostor);
  40253. };
  40254. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  40255. var _this = this;
  40256. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  40257. if (meshChildren.length) {
  40258. var processMesh = function (localPosition, mesh) {
  40259. var childImpostor = mesh.getPhysicsImpostor();
  40260. if (childImpostor) {
  40261. var parent = childImpostor.parent;
  40262. if (parent !== mainImpostor) {
  40263. var localPosition = mesh.position;
  40264. if (childImpostor.physicsBody) {
  40265. _this.removePhysicsBody(childImpostor);
  40266. childImpostor.physicsBody = null;
  40267. }
  40268. childImpostor.parent = mainImpostor;
  40269. childImpostor.resetUpdateFlags();
  40270. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  40271. //Add the mass of the children.
  40272. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  40273. }
  40274. }
  40275. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  40276. };
  40277. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  40278. }
  40279. };
  40280. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  40281. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  40282. this.world.removeEventListener("preStep", impostor.beforeStep);
  40283. this.world.removeEventListener("postStep", impostor.afterStep);
  40284. this.world.remove(impostor.physicsBody);
  40285. };
  40286. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  40287. var mainBody = impostorJoint.mainImpostor.physicsBody;
  40288. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  40289. if (!mainBody || !connectedBody) {
  40290. return;
  40291. }
  40292. var constraint;
  40293. var jointData = impostorJoint.joint.jointData;
  40294. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  40295. var constraintData = {
  40296. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  40297. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  40298. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  40299. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  40300. maxForce: jointData.nativeParams.maxForce,
  40301. collideConnected: !!jointData.collision
  40302. };
  40303. //Not needed, Cannon has a collideConnected flag
  40304. /*if (!jointData.collision) {
  40305. //add 1st body to a collision group of its own, if it is not in 1
  40306. if (mainBody.collisionFilterGroup === 1) {
  40307. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  40308. this._currentCollisionGroup <<= 1;
  40309. }
  40310. if (connectedBody.collisionFilterGroup === 1) {
  40311. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  40312. this._currentCollisionGroup <<= 1;
  40313. }
  40314. //add their mask to the collisionFilterMask of each other:
  40315. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  40316. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  40317. }*/
  40318. switch (impostorJoint.joint.type) {
  40319. case BABYLON.PhysicsJoint.HingeJoint:
  40320. case BABYLON.PhysicsJoint.Hinge2Joint:
  40321. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  40322. break;
  40323. case BABYLON.PhysicsJoint.DistanceJoint:
  40324. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  40325. break;
  40326. case BABYLON.PhysicsJoint.SpringJoint:
  40327. var springData = jointData;
  40328. constraint = new CANNON.Spring(mainBody, connectedBody, {
  40329. restLength: springData.length,
  40330. stiffness: springData.stiffness,
  40331. damping: springData.damping,
  40332. localAnchorA: constraintData.pivotA,
  40333. localAnchorB: constraintData.pivotB
  40334. });
  40335. break;
  40336. case BABYLON.PhysicsJoint.LockJoint:
  40337. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  40338. break;
  40339. case BABYLON.PhysicsJoint.PointToPointJoint:
  40340. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  40341. default:
  40342. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  40343. break;
  40344. }
  40345. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  40346. constraint.collideConnected = !!jointData.collision;
  40347. impostorJoint.joint.physicsJoint = constraint;
  40348. //don't add spring as constraint, as it is not one.
  40349. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  40350. this.world.addConstraint(constraint);
  40351. }
  40352. else {
  40353. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  40354. constraint.applyForce();
  40355. });
  40356. }
  40357. };
  40358. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  40359. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  40360. };
  40361. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  40362. var index;
  40363. var mat;
  40364. for (index = 0; index < this._physicsMaterials.length; index++) {
  40365. mat = this._physicsMaterials[index];
  40366. if (mat.friction === friction && mat.restitution === restitution) {
  40367. return mat;
  40368. }
  40369. }
  40370. var currentMat = new CANNON.Material(name);
  40371. currentMat.friction = friction;
  40372. currentMat.restitution = restitution;
  40373. this._physicsMaterials.push(currentMat);
  40374. return currentMat;
  40375. };
  40376. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  40377. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  40378. };
  40379. CannonJSPlugin.prototype._createShape = function (impostor) {
  40380. var object = impostor.object;
  40381. var returnValue;
  40382. var extendSize = impostor.getObjectExtendSize();
  40383. switch (impostor.type) {
  40384. case BABYLON.PhysicsEngine.SphereImpostor:
  40385. var radiusX = extendSize.x;
  40386. var radiusY = extendSize.y;
  40387. var radiusZ = extendSize.z;
  40388. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  40389. break;
  40390. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  40391. case BABYLON.PhysicsImpostor.CylinderImpostor:
  40392. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  40393. break;
  40394. case BABYLON.PhysicsImpostor.BoxImpostor:
  40395. var box = extendSize.scale(0.5);
  40396. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  40397. break;
  40398. case BABYLON.PhysicsImpostor.PlaneImpostor:
  40399. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  40400. returnValue = new CANNON.Plane();
  40401. break;
  40402. case BABYLON.PhysicsImpostor.MeshImpostor:
  40403. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  40404. var rawFaces = object.getIndices ? object.getIndices() : [];
  40405. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  40406. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  40407. break;
  40408. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  40409. returnValue = this._createHeightmap(object);
  40410. break;
  40411. case BABYLON.PhysicsImpostor.ParticleImpostor:
  40412. returnValue = new CANNON.Particle();
  40413. break;
  40414. }
  40415. return returnValue;
  40416. };
  40417. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  40418. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40419. var matrix = [];
  40420. //For now pointDepth will not be used and will be automatically calculated.
  40421. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  40422. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  40423. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  40424. var elementSize = dim * 2 / arraySize;
  40425. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  40426. for (var i = 0; i < pos.length; i = i + 3) {
  40427. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  40428. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  40429. var y = pos[i + 1] + minY;
  40430. if (!matrix[x]) {
  40431. matrix[x] = [];
  40432. }
  40433. if (!matrix[x][z]) {
  40434. matrix[x][z] = y;
  40435. }
  40436. matrix[x][z] = Math.max(y, matrix[x][z]);
  40437. }
  40438. for (var x = 0; x <= arraySize; ++x) {
  40439. if (!matrix[x]) {
  40440. var loc = 1;
  40441. while (!matrix[(x + loc) % arraySize]) {
  40442. loc++;
  40443. }
  40444. matrix[x] = matrix[(x + loc) % arraySize].slice();
  40445. }
  40446. for (var z = 0; z <= arraySize; ++z) {
  40447. if (!matrix[x][z]) {
  40448. var loc = 1;
  40449. var newValue;
  40450. while (newValue === undefined) {
  40451. newValue = matrix[x][(z + loc++) % arraySize];
  40452. }
  40453. matrix[x][z] = newValue;
  40454. }
  40455. }
  40456. }
  40457. var shape = new CANNON.Heightfield(matrix, {
  40458. elementSize: elementSize
  40459. });
  40460. //For future reference, needed for body transformation
  40461. shape.minY = minY;
  40462. return shape;
  40463. };
  40464. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  40465. var object = impostor.object;
  40466. //make sure it is updated...
  40467. object.computeWorldMatrix && object.computeWorldMatrix(true);
  40468. // The delta between the mesh position and the mesh bounding box center
  40469. var center = impostor.getObjectCenter();
  40470. var extendSize = impostor.getObjectExtendSize();
  40471. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  40472. this._tmpPosition.copyFrom(center);
  40473. var quaternion = object.rotationQuaternion;
  40474. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  40475. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  40476. //-90 DEG in X, precalculated
  40477. quaternion = quaternion.multiply(this._minus90X);
  40478. //Invert! (Precalculated, 90 deg in X)
  40479. //No need to clone. this will never change.
  40480. impostor.setDeltaRotation(this._plus90X);
  40481. }
  40482. //If it is a heightfield, if should be centered.
  40483. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  40484. var mesh = object;
  40485. //calculate the correct body position:
  40486. var rotationQuaternion = mesh.rotationQuaternion;
  40487. mesh.rotationQuaternion = this._tmpUnityRotation;
  40488. mesh.computeWorldMatrix(true);
  40489. //get original center with no rotation
  40490. var c = center.clone();
  40491. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  40492. //rotation is back
  40493. mesh.rotationQuaternion = rotationQuaternion;
  40494. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  40495. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  40496. mesh.setPivotMatrix(p);
  40497. mesh.computeWorldMatrix(true);
  40498. //calculate the translation
  40499. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  40500. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  40501. //add it inverted to the delta
  40502. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  40503. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  40504. mesh.setPivotMatrix(oldPivot);
  40505. mesh.computeWorldMatrix(true);
  40506. }
  40507. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  40508. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  40509. this._tmpPosition.copyFrom(object.position);
  40510. }
  40511. impostor.setDeltaPosition(this._tmpDeltaPosition);
  40512. //Now update the impostor object
  40513. impostor.physicsBody.position.copy(this._tmpPosition);
  40514. impostor.physicsBody.quaternion.copy(quaternion);
  40515. };
  40516. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  40517. impostor.object.position.copyFrom(impostor.physicsBody.position);
  40518. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  40519. };
  40520. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  40521. impostor.physicsBody.position.copy(newPosition);
  40522. impostor.physicsBody.quaternion.copy(newRotation);
  40523. };
  40524. CannonJSPlugin.prototype.isSupported = function () {
  40525. return window.CANNON !== undefined;
  40526. };
  40527. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  40528. impostor.physicsBody.velocity.copy(velocity);
  40529. };
  40530. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  40531. impostor.physicsBody.angularVelocity.copy(velocity);
  40532. };
  40533. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  40534. var v = impostor.physicsBody.velocity;
  40535. if (!v)
  40536. return null;
  40537. return new BABYLON.Vector3(v.x, v.y, v.z);
  40538. };
  40539. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  40540. var v = impostor.physicsBody.angularVelocity;
  40541. if (!v)
  40542. return null;
  40543. return new BABYLON.Vector3(v.x, v.y, v.z);
  40544. };
  40545. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  40546. impostor.physicsBody.mass = mass;
  40547. impostor.physicsBody.updateMassProperties();
  40548. };
  40549. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  40550. impostor.physicsBody.sleep();
  40551. };
  40552. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  40553. impostor.physicsBody.wakeUp();
  40554. };
  40555. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  40556. joint.physicsJoint.distance = maxDistance;
  40557. };
  40558. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  40559. if (!motorIndex) {
  40560. joint.physicsJoint.enableMotor();
  40561. }
  40562. };
  40563. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  40564. if (!motorIndex) {
  40565. joint.physicsJoint.disableMotor();
  40566. }
  40567. };
  40568. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  40569. if (!motorIndex) {
  40570. joint.physicsJoint.enableMotor();
  40571. joint.physicsJoint.setMotorSpeed(speed);
  40572. if (maxForce) {
  40573. this.setLimit(joint, maxForce);
  40574. }
  40575. }
  40576. };
  40577. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  40578. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  40579. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  40580. };
  40581. CannonJSPlugin.prototype.dispose = function () {
  40582. //nothing to do, actually.
  40583. };
  40584. return CannonJSPlugin;
  40585. }());
  40586. BABYLON.CannonJSPlugin = CannonJSPlugin;
  40587. })(BABYLON || (BABYLON = {}));
  40588. var BABYLON;
  40589. (function (BABYLON) {
  40590. var OimoJSPlugin = (function () {
  40591. function OimoJSPlugin(iterations) {
  40592. this.name = "OimoJSPlugin";
  40593. this._tmpImpostorsArray = [];
  40594. this._tmpPositionVector = BABYLON.Vector3.Zero();
  40595. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  40596. this.world.worldscale(1);
  40597. this.world.clear();
  40598. //making sure no stats are calculated
  40599. this.world.isNoStat = true;
  40600. }
  40601. OimoJSPlugin.prototype.setGravity = function (gravity) {
  40602. this.world.gravity.copy(gravity);
  40603. };
  40604. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  40605. this.world.timeStep = timeStep;
  40606. };
  40607. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  40608. var _this = this;
  40609. impostors.forEach(function (impostor) {
  40610. impostor.beforeStep();
  40611. });
  40612. this.world.step();
  40613. impostors.forEach(function (impostor) {
  40614. impostor.afterStep();
  40615. //update the ordered impostors array
  40616. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  40617. });
  40618. //check for collisions
  40619. var contact = this.world.contacts;
  40620. while (contact !== null) {
  40621. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  40622. contact = contact.next;
  40623. continue;
  40624. }
  40625. //is this body colliding with any other? get the impostor
  40626. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  40627. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  40628. if (!mainImpostor || !collidingImpostor) {
  40629. contact = contact.next;
  40630. continue;
  40631. }
  40632. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  40633. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  40634. contact = contact.next;
  40635. }
  40636. };
  40637. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  40638. var mass = impostor.physicsBody.massInfo.mass;
  40639. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  40640. };
  40641. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  40642. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  40643. this.applyImpulse(impostor, force, contactPoint);
  40644. };
  40645. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  40646. var _this = this;
  40647. //parent-child relationship. Does this impostor has a parent impostor?
  40648. if (impostor.parent) {
  40649. if (impostor.physicsBody) {
  40650. this.removePhysicsBody(impostor);
  40651. //TODO is that needed?
  40652. impostor.forceUpdate();
  40653. }
  40654. return;
  40655. }
  40656. if (impostor.isBodyInitRequired()) {
  40657. var bodyConfig = {
  40658. name: impostor.uniqueId,
  40659. //Oimo must have mass, also for static objects.
  40660. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  40661. size: [],
  40662. type: [],
  40663. pos: [],
  40664. rot: [],
  40665. move: impostor.getParam("mass") !== 0,
  40666. //Supporting older versions of Oimo
  40667. world: this.world
  40668. };
  40669. var impostors = [impostor];
  40670. var addToArray = function (parent) {
  40671. if (!parent.getChildMeshes)
  40672. return;
  40673. parent.getChildMeshes().forEach(function (m) {
  40674. if (m.physicsImpostor) {
  40675. impostors.push(m.physicsImpostor);
  40676. m.physicsImpostor._init();
  40677. }
  40678. });
  40679. };
  40680. addToArray(impostor.object);
  40681. var checkWithEpsilon_1 = function (value) {
  40682. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  40683. };
  40684. impostors.forEach(function (i) {
  40685. //get the correct bounding box
  40686. var oldQuaternion = i.object.rotationQuaternion;
  40687. var rot = new OIMO.Euler().setFromQuaternion({
  40688. x: impostor.object.rotationQuaternion.x,
  40689. y: impostor.object.rotationQuaternion.y,
  40690. z: impostor.object.rotationQuaternion.z,
  40691. s: impostor.object.rotationQuaternion.w
  40692. });
  40693. var extendSize = i.getObjectExtendSize();
  40694. if (i === impostor) {
  40695. var center = impostor.getObjectCenter();
  40696. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  40697. //Can also use Array.prototype.push.apply
  40698. bodyConfig.pos.push(center.x);
  40699. bodyConfig.pos.push(center.y);
  40700. bodyConfig.pos.push(center.z);
  40701. //tmp solution
  40702. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  40703. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  40704. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  40705. }
  40706. else {
  40707. bodyConfig.pos.push(i.object.position.x);
  40708. bodyConfig.pos.push(i.object.position.y);
  40709. bodyConfig.pos.push(i.object.position.z);
  40710. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  40711. bodyConfig.rot.push(0);
  40712. bodyConfig.rot.push(0);
  40713. bodyConfig.rot.push(0);
  40714. }
  40715. // register mesh
  40716. switch (i.type) {
  40717. case BABYLON.PhysicsImpostor.ParticleImpostor:
  40718. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  40719. case BABYLON.PhysicsImpostor.SphereImpostor:
  40720. var radiusX = extendSize.x;
  40721. var radiusY = extendSize.y;
  40722. var radiusZ = extendSize.z;
  40723. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  40724. bodyConfig.type.push('sphere');
  40725. //due to the way oimo works with compounds, add 3 times
  40726. bodyConfig.size.push(size);
  40727. bodyConfig.size.push(size);
  40728. bodyConfig.size.push(size);
  40729. break;
  40730. case BABYLON.PhysicsImpostor.CylinderImpostor:
  40731. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  40732. var sizeY = checkWithEpsilon_1(extendSize.y);
  40733. bodyConfig.type.push('cylinder');
  40734. bodyConfig.size.push(sizeX);
  40735. bodyConfig.size.push(sizeY);
  40736. //due to the way oimo works with compounds, add one more value.
  40737. bodyConfig.size.push(sizeY);
  40738. break;
  40739. case BABYLON.PhysicsImpostor.PlaneImpostor:
  40740. case BABYLON.PhysicsImpostor.BoxImpostor:
  40741. default:
  40742. var sizeX = checkWithEpsilon_1(extendSize.x);
  40743. var sizeY = checkWithEpsilon_1(extendSize.y);
  40744. var sizeZ = checkWithEpsilon_1(extendSize.z);
  40745. bodyConfig.type.push('box');
  40746. bodyConfig.size.push(sizeX);
  40747. bodyConfig.size.push(sizeY);
  40748. bodyConfig.size.push(sizeZ);
  40749. break;
  40750. }
  40751. //actually not needed, but hey...
  40752. i.object.rotationQuaternion = oldQuaternion;
  40753. });
  40754. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  40755. }
  40756. else {
  40757. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  40758. }
  40759. impostor.setDeltaPosition(this._tmpPositionVector);
  40760. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  40761. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  40762. };
  40763. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  40764. //impostor.physicsBody.dispose();
  40765. //Same as : (older oimo versions)
  40766. this.world.removeRigidBody(impostor.physicsBody);
  40767. };
  40768. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  40769. var mainBody = impostorJoint.mainImpostor.physicsBody;
  40770. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  40771. if (!mainBody || !connectedBody) {
  40772. return;
  40773. }
  40774. var jointData = impostorJoint.joint.jointData;
  40775. var options = jointData.nativeParams || {};
  40776. var type;
  40777. var nativeJointData = {
  40778. body1: mainBody,
  40779. body2: connectedBody,
  40780. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  40781. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  40782. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  40783. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  40784. min: options.min,
  40785. max: options.max,
  40786. collision: options.collision || jointData.collision,
  40787. spring: options.spring,
  40788. //supporting older version of Oimo
  40789. world: this.world
  40790. };
  40791. switch (impostorJoint.joint.type) {
  40792. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  40793. type = "jointBall";
  40794. break;
  40795. case BABYLON.PhysicsJoint.SpringJoint:
  40796. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  40797. var springData = jointData;
  40798. nativeJointData.min = springData.length || nativeJointData.min;
  40799. //Max should also be set, just make sure it is at least min
  40800. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  40801. case BABYLON.PhysicsJoint.DistanceJoint:
  40802. type = "jointDistance";
  40803. nativeJointData.max = jointData.maxDistance;
  40804. break;
  40805. case BABYLON.PhysicsJoint.PrismaticJoint:
  40806. type = "jointPrisme";
  40807. break;
  40808. case BABYLON.PhysicsJoint.SliderJoint:
  40809. type = "jointSlide";
  40810. break;
  40811. case BABYLON.PhysicsJoint.WheelJoint:
  40812. type = "jointWheel";
  40813. break;
  40814. case BABYLON.PhysicsJoint.HingeJoint:
  40815. default:
  40816. type = "jointHinge";
  40817. break;
  40818. }
  40819. nativeJointData.type = type;
  40820. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  40821. };
  40822. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  40823. //Bug in Oimo prevents us from disposing a joint in the playground
  40824. //joint.joint.physicsJoint.dispose();
  40825. //So we will bruteforce it!
  40826. try {
  40827. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  40828. }
  40829. catch (e) {
  40830. BABYLON.Tools.Warn(e);
  40831. }
  40832. };
  40833. OimoJSPlugin.prototype.isSupported = function () {
  40834. return OIMO !== undefined;
  40835. };
  40836. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  40837. if (!impostor.physicsBody.sleeping) {
  40838. //TODO check that
  40839. if (impostor.physicsBody.shapes.next) {
  40840. var parentShape = this._getLastShape(impostor.physicsBody);
  40841. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  40842. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  40843. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  40844. }
  40845. else {
  40846. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  40847. }
  40848. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  40849. impostor.object.rotationQuaternion.normalize();
  40850. }
  40851. };
  40852. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  40853. var body = impostor.physicsBody;
  40854. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  40855. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  40856. body.syncShapes();
  40857. body.awake();
  40858. };
  40859. OimoJSPlugin.prototype._getLastShape = function (body) {
  40860. var lastShape = body.shapes;
  40861. while (lastShape.next) {
  40862. lastShape = lastShape.next;
  40863. }
  40864. return lastShape;
  40865. };
  40866. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  40867. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  40868. };
  40869. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  40870. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  40871. };
  40872. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  40873. var v = impostor.physicsBody.linearVelocity;
  40874. if (!v)
  40875. return null;
  40876. return new BABYLON.Vector3(v.x, v.y, v.z);
  40877. };
  40878. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  40879. var v = impostor.physicsBody.angularVelocity;
  40880. if (!v)
  40881. return null;
  40882. return new BABYLON.Vector3(v.x, v.y, v.z);
  40883. };
  40884. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  40885. var staticBody = mass === 0;
  40886. //this will actually set the body's density and not its mass.
  40887. //But this is how oimo treats the mass variable.
  40888. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  40889. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  40890. };
  40891. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  40892. impostor.physicsBody.sleep();
  40893. };
  40894. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  40895. impostor.physicsBody.awake();
  40896. };
  40897. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  40898. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  40899. if (minDistance !== void 0) {
  40900. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  40901. }
  40902. };
  40903. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  40904. //TODO separate rotational and transational motors.
  40905. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  40906. if (motor) {
  40907. motor.setMotor(speed, maxForce);
  40908. }
  40909. };
  40910. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  40911. //TODO separate rotational and transational motors.
  40912. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  40913. if (motor) {
  40914. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  40915. }
  40916. };
  40917. OimoJSPlugin.prototype.dispose = function () {
  40918. this.world.clear();
  40919. };
  40920. return OimoJSPlugin;
  40921. }());
  40922. BABYLON.OimoJSPlugin = OimoJSPlugin;
  40923. })(BABYLON || (BABYLON = {}));
  40924. var BABYLON;
  40925. (function (BABYLON) {
  40926. var DisplayPassPostProcess = (function (_super) {
  40927. __extends(DisplayPassPostProcess, _super);
  40928. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  40929. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  40930. }
  40931. return DisplayPassPostProcess;
  40932. }(BABYLON.PostProcess));
  40933. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  40934. })(BABYLON || (BABYLON = {}));
  40935. var BABYLON;
  40936. (function (BABYLON) {
  40937. var SimplificationSettings = (function () {
  40938. function SimplificationSettings(quality, distance, optimizeMesh) {
  40939. this.quality = quality;
  40940. this.distance = distance;
  40941. this.optimizeMesh = optimizeMesh;
  40942. }
  40943. return SimplificationSettings;
  40944. }());
  40945. BABYLON.SimplificationSettings = SimplificationSettings;
  40946. var SimplificationQueue = (function () {
  40947. function SimplificationQueue() {
  40948. this.running = false;
  40949. this._simplificationArray = [];
  40950. }
  40951. SimplificationQueue.prototype.addTask = function (task) {
  40952. this._simplificationArray.push(task);
  40953. };
  40954. SimplificationQueue.prototype.executeNext = function () {
  40955. var task = this._simplificationArray.pop();
  40956. if (task) {
  40957. this.running = true;
  40958. this.runSimplification(task);
  40959. }
  40960. else {
  40961. this.running = false;
  40962. }
  40963. };
  40964. SimplificationQueue.prototype.runSimplification = function (task) {
  40965. var _this = this;
  40966. if (task.parallelProcessing) {
  40967. //parallel simplifier
  40968. task.settings.forEach(function (setting) {
  40969. var simplifier = _this.getSimplifier(task);
  40970. simplifier.simplify(setting, function (newMesh) {
  40971. task.mesh.addLODLevel(setting.distance, newMesh);
  40972. newMesh.isVisible = true;
  40973. //check if it is the last
  40974. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  40975. //all done, run the success callback.
  40976. task.successCallback();
  40977. }
  40978. _this.executeNext();
  40979. });
  40980. });
  40981. }
  40982. else {
  40983. //single simplifier.
  40984. var simplifier = this.getSimplifier(task);
  40985. var runDecimation = function (setting, callback) {
  40986. simplifier.simplify(setting, function (newMesh) {
  40987. task.mesh.addLODLevel(setting.distance, newMesh);
  40988. newMesh.isVisible = true;
  40989. //run the next quality level
  40990. callback();
  40991. });
  40992. };
  40993. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  40994. runDecimation(task.settings[loop.index], function () {
  40995. loop.executeNext();
  40996. });
  40997. }, function () {
  40998. //execution ended, run the success callback.
  40999. if (task.successCallback) {
  41000. task.successCallback();
  41001. }
  41002. _this.executeNext();
  41003. });
  41004. }
  41005. };
  41006. SimplificationQueue.prototype.getSimplifier = function (task) {
  41007. switch (task.simplificationType) {
  41008. case SimplificationType.QUADRATIC:
  41009. default:
  41010. return new QuadraticErrorSimplification(task.mesh);
  41011. }
  41012. };
  41013. return SimplificationQueue;
  41014. }());
  41015. BABYLON.SimplificationQueue = SimplificationQueue;
  41016. /**
  41017. * The implemented types of simplification.
  41018. * At the moment only Quadratic Error Decimation is implemented.
  41019. */
  41020. (function (SimplificationType) {
  41021. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  41022. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  41023. var SimplificationType = BABYLON.SimplificationType;
  41024. var DecimationTriangle = (function () {
  41025. function DecimationTriangle(vertices) {
  41026. this.vertices = vertices;
  41027. this.error = new Array(4);
  41028. this.deleted = false;
  41029. this.isDirty = false;
  41030. this.deletePending = false;
  41031. this.borderFactor = 0;
  41032. }
  41033. return DecimationTriangle;
  41034. }());
  41035. BABYLON.DecimationTriangle = DecimationTriangle;
  41036. var DecimationVertex = (function () {
  41037. function DecimationVertex(position, id) {
  41038. this.position = position;
  41039. this.id = id;
  41040. this.isBorder = true;
  41041. this.q = new QuadraticMatrix();
  41042. this.triangleCount = 0;
  41043. this.triangleStart = 0;
  41044. this.originalOffsets = [];
  41045. }
  41046. DecimationVertex.prototype.updatePosition = function (newPosition) {
  41047. this.position.copyFrom(newPosition);
  41048. };
  41049. return DecimationVertex;
  41050. }());
  41051. BABYLON.DecimationVertex = DecimationVertex;
  41052. var QuadraticMatrix = (function () {
  41053. function QuadraticMatrix(data) {
  41054. this.data = new Array(10);
  41055. for (var i = 0; i < 10; ++i) {
  41056. if (data && data[i]) {
  41057. this.data[i] = data[i];
  41058. }
  41059. else {
  41060. this.data[i] = 0;
  41061. }
  41062. }
  41063. }
  41064. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  41065. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  41066. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  41067. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  41068. return det;
  41069. };
  41070. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  41071. for (var i = 0; i < 10; ++i) {
  41072. this.data[i] += matrix.data[i];
  41073. }
  41074. };
  41075. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  41076. for (var i = 0; i < 10; ++i) {
  41077. this.data[i] += data[i];
  41078. }
  41079. };
  41080. QuadraticMatrix.prototype.add = function (matrix) {
  41081. var m = new QuadraticMatrix();
  41082. for (var i = 0; i < 10; ++i) {
  41083. m.data[i] = this.data[i] + matrix.data[i];
  41084. }
  41085. return m;
  41086. };
  41087. QuadraticMatrix.FromData = function (a, b, c, d) {
  41088. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  41089. };
  41090. //returning an array to avoid garbage collection
  41091. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  41092. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  41093. };
  41094. return QuadraticMatrix;
  41095. }());
  41096. BABYLON.QuadraticMatrix = QuadraticMatrix;
  41097. var Reference = (function () {
  41098. function Reference(vertexId, triangleId) {
  41099. this.vertexId = vertexId;
  41100. this.triangleId = triangleId;
  41101. }
  41102. return Reference;
  41103. }());
  41104. BABYLON.Reference = Reference;
  41105. /**
  41106. * An implementation of the Quadratic Error simplification algorithm.
  41107. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  41108. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  41109. * @author RaananW
  41110. */
  41111. var QuadraticErrorSimplification = (function () {
  41112. function QuadraticErrorSimplification(_mesh) {
  41113. this._mesh = _mesh;
  41114. this.initialized = false;
  41115. this.syncIterations = 5000;
  41116. this.aggressiveness = 7;
  41117. this.decimationIterations = 100;
  41118. this.boundingBoxEpsilon = BABYLON.Epsilon;
  41119. }
  41120. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  41121. var _this = this;
  41122. this.initDecimatedMesh();
  41123. //iterating through the submeshes array, one after the other.
  41124. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  41125. _this.initWithMesh(loop.index, function () {
  41126. _this.runDecimation(settings, loop.index, function () {
  41127. loop.executeNext();
  41128. });
  41129. }, settings.optimizeMesh);
  41130. }, function () {
  41131. setTimeout(function () {
  41132. successCallback(_this._reconstructedMesh);
  41133. }, 0);
  41134. });
  41135. };
  41136. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  41137. var _this = this;
  41138. var gCount = 0;
  41139. triangle.vertices.forEach(function (vertex) {
  41140. var count = 0;
  41141. var vPos = vertex.position;
  41142. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  41143. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  41144. ++count;
  41145. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  41146. ++count;
  41147. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  41148. ++count;
  41149. if (count > 1) {
  41150. ++gCount;
  41151. }
  41152. ;
  41153. });
  41154. if (gCount > 1) {
  41155. console.log(triangle, gCount);
  41156. }
  41157. return gCount > 1;
  41158. };
  41159. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  41160. var _this = this;
  41161. var targetCount = ~~(this.triangles.length * settings.quality);
  41162. var deletedTriangles = 0;
  41163. var triangleCount = this.triangles.length;
  41164. var iterationFunction = function (iteration, callback) {
  41165. setTimeout(function () {
  41166. if (iteration % 5 === 0) {
  41167. _this.updateMesh(iteration === 0);
  41168. }
  41169. for (var i = 0; i < _this.triangles.length; ++i) {
  41170. _this.triangles[i].isDirty = false;
  41171. }
  41172. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  41173. var trianglesIterator = function (i) {
  41174. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  41175. var t = _this.triangles[tIdx];
  41176. if (!t)
  41177. return;
  41178. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  41179. return;
  41180. }
  41181. for (var j = 0; j < 3; ++j) {
  41182. if (t.error[j] < threshold) {
  41183. var deleted0 = [];
  41184. var deleted1 = [];
  41185. var v0 = t.vertices[j];
  41186. var v1 = t.vertices[(j + 1) % 3];
  41187. if (v0.isBorder || v1.isBorder)
  41188. continue;
  41189. var p = BABYLON.Vector3.Zero();
  41190. var n = BABYLON.Vector3.Zero();
  41191. var uv = BABYLON.Vector2.Zero();
  41192. var color = new BABYLON.Color4(0, 0, 0, 1);
  41193. _this.calculateError(v0, v1, p, n, uv, color);
  41194. var delTr = [];
  41195. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  41196. continue;
  41197. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  41198. continue;
  41199. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  41200. continue;
  41201. var uniqueArray = [];
  41202. delTr.forEach(function (deletedT) {
  41203. if (uniqueArray.indexOf(deletedT) === -1) {
  41204. deletedT.deletePending = true;
  41205. uniqueArray.push(deletedT);
  41206. }
  41207. });
  41208. if (uniqueArray.length % 2 !== 0) {
  41209. continue;
  41210. }
  41211. v0.q = v1.q.add(v0.q);
  41212. v0.updatePosition(p);
  41213. var tStart = _this.references.length;
  41214. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  41215. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  41216. var tCount = _this.references.length - tStart;
  41217. if (tCount <= v0.triangleCount) {
  41218. if (tCount) {
  41219. for (var c = 0; c < tCount; c++) {
  41220. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  41221. }
  41222. }
  41223. }
  41224. else {
  41225. v0.triangleStart = tStart;
  41226. }
  41227. v0.triangleCount = tCount;
  41228. break;
  41229. }
  41230. }
  41231. };
  41232. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  41233. }, 0);
  41234. };
  41235. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  41236. if (triangleCount - deletedTriangles <= targetCount)
  41237. loop.breakLoop();
  41238. else {
  41239. iterationFunction(loop.index, function () {
  41240. loop.executeNext();
  41241. });
  41242. }
  41243. }, function () {
  41244. setTimeout(function () {
  41245. //reconstruct this part of the mesh
  41246. _this.reconstructMesh(submeshIndex);
  41247. successCallback();
  41248. }, 0);
  41249. });
  41250. };
  41251. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  41252. var _this = this;
  41253. this.vertices = [];
  41254. this.triangles = [];
  41255. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41256. var indices = this._mesh.getIndices();
  41257. var submesh = this._mesh.subMeshes[submeshIndex];
  41258. var findInVertices = function (positionToSearch) {
  41259. if (optimizeMesh) {
  41260. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  41261. if (_this.vertices[ii].position.equals(positionToSearch)) {
  41262. return _this.vertices[ii];
  41263. }
  41264. }
  41265. }
  41266. return null;
  41267. };
  41268. var vertexReferences = [];
  41269. var vertexInit = function (i) {
  41270. var offset = i + submesh.verticesStart;
  41271. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  41272. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  41273. vertex.originalOffsets.push(offset);
  41274. if (vertex.id === _this.vertices.length) {
  41275. _this.vertices.push(vertex);
  41276. }
  41277. vertexReferences.push(vertex.id);
  41278. };
  41279. //var totalVertices = mesh.getTotalVertices();
  41280. var totalVertices = submesh.verticesCount;
  41281. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  41282. var indicesInit = function (i) {
  41283. var offset = (submesh.indexStart / 3) + i;
  41284. var pos = (offset * 3);
  41285. var i0 = indices[pos + 0];
  41286. var i1 = indices[pos + 1];
  41287. var i2 = indices[pos + 2];
  41288. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  41289. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  41290. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  41291. var triangle = new DecimationTriangle([v0, v1, v2]);
  41292. triangle.originalOffset = pos;
  41293. _this.triangles.push(triangle);
  41294. };
  41295. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  41296. _this.init(callback);
  41297. });
  41298. });
  41299. };
  41300. QuadraticErrorSimplification.prototype.init = function (callback) {
  41301. var _this = this;
  41302. var triangleInit1 = function (i) {
  41303. var t = _this.triangles[i];
  41304. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  41305. for (var j = 0; j < 3; j++) {
  41306. 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))));
  41307. }
  41308. };
  41309. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  41310. var triangleInit2 = function (i) {
  41311. var t = _this.triangles[i];
  41312. for (var j = 0; j < 3; ++j) {
  41313. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  41314. }
  41315. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  41316. };
  41317. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  41318. _this.initialized = true;
  41319. callback();
  41320. });
  41321. });
  41322. };
  41323. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  41324. var newTriangles = [];
  41325. var i;
  41326. for (i = 0; i < this.vertices.length; ++i) {
  41327. this.vertices[i].triangleCount = 0;
  41328. }
  41329. var t;
  41330. var j;
  41331. for (i = 0; i < this.triangles.length; ++i) {
  41332. if (!this.triangles[i].deleted) {
  41333. t = this.triangles[i];
  41334. for (j = 0; j < 3; ++j) {
  41335. t.vertices[j].triangleCount = 1;
  41336. }
  41337. newTriangles.push(t);
  41338. }
  41339. }
  41340. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  41341. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  41342. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  41343. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  41344. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41345. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41346. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41347. var vertexCount = 0;
  41348. for (i = 0; i < this.vertices.length; ++i) {
  41349. var vertex = this.vertices[i];
  41350. vertex.id = vertexCount;
  41351. if (vertex.triangleCount) {
  41352. vertex.originalOffsets.forEach(function (originalOffset) {
  41353. newPositionData.push(vertex.position.x);
  41354. newPositionData.push(vertex.position.y);
  41355. newPositionData.push(vertex.position.z);
  41356. newNormalData.push(normalData[originalOffset * 3]);
  41357. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  41358. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  41359. if (uvs && uvs.length) {
  41360. newUVsData.push(uvs[(originalOffset * 2)]);
  41361. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  41362. }
  41363. else if (colorsData && colorsData.length) {
  41364. newColorsData.push(colorsData[(originalOffset * 4)]);
  41365. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  41366. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  41367. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  41368. }
  41369. ++vertexCount;
  41370. });
  41371. }
  41372. }
  41373. var startingIndex = this._reconstructedMesh.getTotalIndices();
  41374. var startingVertex = this._reconstructedMesh.getTotalVertices();
  41375. var submeshesArray = this._reconstructedMesh.subMeshes;
  41376. this._reconstructedMesh.subMeshes = [];
  41377. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  41378. var originalIndices = this._mesh.getIndices();
  41379. for (i = 0; i < newTriangles.length; ++i) {
  41380. t = newTriangles[i]; //now get the new referencing point for each vertex
  41381. [0, 1, 2].forEach(function (idx) {
  41382. var id = originalIndices[t.originalOffset + idx];
  41383. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  41384. if (offset < 0)
  41385. offset = 0;
  41386. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  41387. });
  41388. }
  41389. //overwriting the old vertex buffers and indices.
  41390. this._reconstructedMesh.setIndices(newIndicesArray);
  41391. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  41392. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  41393. if (newUVsData.length > 0)
  41394. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  41395. if (newColorsData.length > 0)
  41396. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  41397. //create submesh
  41398. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  41399. if (submeshIndex > 0) {
  41400. this._reconstructedMesh.subMeshes = [];
  41401. submeshesArray.forEach(function (submesh) {
  41402. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  41403. });
  41404. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  41405. }
  41406. };
  41407. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  41408. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  41409. this._reconstructedMesh.material = this._mesh.material;
  41410. this._reconstructedMesh.parent = this._mesh.parent;
  41411. this._reconstructedMesh.isVisible = false;
  41412. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  41413. };
  41414. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  41415. for (var i = 0; i < vertex1.triangleCount; ++i) {
  41416. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  41417. if (t.deleted)
  41418. continue;
  41419. var s = this.references[vertex1.triangleStart + i].vertexId;
  41420. var v1 = t.vertices[(s + 1) % 3];
  41421. var v2 = t.vertices[(s + 2) % 3];
  41422. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  41423. deletedArray[i] = true;
  41424. delTr.push(t);
  41425. continue;
  41426. }
  41427. var d1 = v1.position.subtract(point);
  41428. d1 = d1.normalize();
  41429. var d2 = v2.position.subtract(point);
  41430. d2 = d2.normalize();
  41431. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  41432. return true;
  41433. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  41434. deletedArray[i] = false;
  41435. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  41436. return true;
  41437. }
  41438. return false;
  41439. };
  41440. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  41441. var newDeleted = deletedTriangles;
  41442. for (var i = 0; i < vertex.triangleCount; ++i) {
  41443. var ref = this.references[vertex.triangleStart + i];
  41444. var t = this.triangles[ref.triangleId];
  41445. if (t.deleted)
  41446. continue;
  41447. if (deletedArray[i] && t.deletePending) {
  41448. t.deleted = true;
  41449. newDeleted++;
  41450. continue;
  41451. }
  41452. t.vertices[ref.vertexId] = origVertex;
  41453. t.isDirty = true;
  41454. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  41455. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  41456. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  41457. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  41458. this.references.push(ref);
  41459. }
  41460. return newDeleted;
  41461. };
  41462. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  41463. for (var i = 0; i < this.vertices.length; ++i) {
  41464. var vCount = [];
  41465. var vId = [];
  41466. var v = this.vertices[i];
  41467. var j;
  41468. for (j = 0; j < v.triangleCount; ++j) {
  41469. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  41470. for (var ii = 0; ii < 3; ii++) {
  41471. var ofs = 0;
  41472. var vv = triangle.vertices[ii];
  41473. while (ofs < vCount.length) {
  41474. if (vId[ofs] === vv.id)
  41475. break;
  41476. ++ofs;
  41477. }
  41478. if (ofs === vCount.length) {
  41479. vCount.push(1);
  41480. vId.push(vv.id);
  41481. }
  41482. else {
  41483. vCount[ofs]++;
  41484. }
  41485. }
  41486. }
  41487. for (j = 0; j < vCount.length; ++j) {
  41488. if (vCount[j] === 1) {
  41489. this.vertices[vId[j]].isBorder = true;
  41490. }
  41491. else {
  41492. this.vertices[vId[j]].isBorder = false;
  41493. }
  41494. }
  41495. }
  41496. };
  41497. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  41498. if (identifyBorders === void 0) { identifyBorders = false; }
  41499. var i;
  41500. if (!identifyBorders) {
  41501. var newTrianglesVector = [];
  41502. for (i = 0; i < this.triangles.length; ++i) {
  41503. if (!this.triangles[i].deleted) {
  41504. newTrianglesVector.push(this.triangles[i]);
  41505. }
  41506. }
  41507. this.triangles = newTrianglesVector;
  41508. }
  41509. for (i = 0; i < this.vertices.length; ++i) {
  41510. this.vertices[i].triangleCount = 0;
  41511. this.vertices[i].triangleStart = 0;
  41512. }
  41513. var t;
  41514. var j;
  41515. var v;
  41516. for (i = 0; i < this.triangles.length; ++i) {
  41517. t = this.triangles[i];
  41518. for (j = 0; j < 3; ++j) {
  41519. v = t.vertices[j];
  41520. v.triangleCount++;
  41521. }
  41522. }
  41523. var tStart = 0;
  41524. for (i = 0; i < this.vertices.length; ++i) {
  41525. this.vertices[i].triangleStart = tStart;
  41526. tStart += this.vertices[i].triangleCount;
  41527. this.vertices[i].triangleCount = 0;
  41528. }
  41529. var newReferences = new Array(this.triangles.length * 3);
  41530. for (i = 0; i < this.triangles.length; ++i) {
  41531. t = this.triangles[i];
  41532. for (j = 0; j < 3; ++j) {
  41533. v = t.vertices[j];
  41534. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  41535. v.triangleCount++;
  41536. }
  41537. }
  41538. this.references = newReferences;
  41539. if (identifyBorders) {
  41540. this.identifyBorder();
  41541. }
  41542. };
  41543. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  41544. var x = point.x;
  41545. var y = point.y;
  41546. var z = point.z;
  41547. 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
  41548. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  41549. };
  41550. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  41551. var q = vertex1.q.add(vertex2.q);
  41552. var border = vertex1.isBorder && vertex2.isBorder;
  41553. var error = 0;
  41554. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  41555. if (qDet !== 0 && !border) {
  41556. if (!pointResult) {
  41557. pointResult = BABYLON.Vector3.Zero();
  41558. }
  41559. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  41560. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  41561. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  41562. error = this.vertexError(q, pointResult);
  41563. }
  41564. else {
  41565. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  41566. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  41567. var error1 = this.vertexError(q, vertex1.position);
  41568. var error2 = this.vertexError(q, vertex2.position);
  41569. var error3 = this.vertexError(q, p3);
  41570. error = Math.min(error1, error2, error3);
  41571. if (error === error1) {
  41572. if (pointResult) {
  41573. pointResult.copyFrom(vertex1.position);
  41574. }
  41575. }
  41576. else if (error === error2) {
  41577. if (pointResult) {
  41578. pointResult.copyFrom(vertex2.position);
  41579. }
  41580. }
  41581. else {
  41582. if (pointResult) {
  41583. pointResult.copyFrom(p3);
  41584. }
  41585. }
  41586. }
  41587. return error;
  41588. };
  41589. return QuadraticErrorSimplification;
  41590. }());
  41591. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  41592. })(BABYLON || (BABYLON = {}));
  41593. var BABYLON;
  41594. (function (BABYLON) {
  41595. var serializedGeometries = [];
  41596. var serializeGeometry = function (geometry, serializationGeometries) {
  41597. if (serializedGeometries[geometry.id]) {
  41598. return;
  41599. }
  41600. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  41601. serializationGeometries.boxes.push(geometry.serialize());
  41602. }
  41603. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  41604. serializationGeometries.spheres.push(geometry.serialize());
  41605. }
  41606. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  41607. serializationGeometries.cylinders.push(geometry.serialize());
  41608. }
  41609. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  41610. serializationGeometries.toruses.push(geometry.serialize());
  41611. }
  41612. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  41613. serializationGeometries.grounds.push(geometry.serialize());
  41614. }
  41615. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  41616. serializationGeometries.planes.push(geometry.serialize());
  41617. }
  41618. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  41619. serializationGeometries.torusKnots.push(geometry.serialize());
  41620. }
  41621. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  41622. throw new Error("Unknown primitive type");
  41623. }
  41624. else {
  41625. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  41626. }
  41627. serializedGeometries[geometry.id] = true;
  41628. };
  41629. var serializeMesh = function (mesh, serializationScene) {
  41630. var serializationObject = {};
  41631. serializationObject.name = mesh.name;
  41632. serializationObject.id = mesh.id;
  41633. if (BABYLON.Tags.HasTags(mesh)) {
  41634. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  41635. }
  41636. serializationObject.position = mesh.position.asArray();
  41637. if (mesh.rotationQuaternion) {
  41638. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  41639. }
  41640. else if (mesh.rotation) {
  41641. serializationObject.rotation = mesh.rotation.asArray();
  41642. }
  41643. serializationObject.scaling = mesh.scaling.asArray();
  41644. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  41645. serializationObject.isEnabled = mesh.isEnabled();
  41646. serializationObject.isVisible = mesh.isVisible;
  41647. serializationObject.infiniteDistance = mesh.infiniteDistance;
  41648. serializationObject.pickable = mesh.isPickable;
  41649. serializationObject.receiveShadows = mesh.receiveShadows;
  41650. serializationObject.billboardMode = mesh.billboardMode;
  41651. serializationObject.visibility = mesh.visibility;
  41652. serializationObject.checkCollisions = mesh.checkCollisions;
  41653. // Parent
  41654. if (mesh.parent) {
  41655. serializationObject.parentId = mesh.parent.id;
  41656. }
  41657. // Geometry
  41658. var geometry = mesh._geometry;
  41659. if (geometry) {
  41660. var geometryId = geometry.id;
  41661. serializationObject.geometryId = geometryId;
  41662. if (!mesh.getScene().getGeometryByID(geometryId)) {
  41663. // 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
  41664. serializeGeometry(geometry, serializationScene.geometries);
  41665. }
  41666. // SubMeshes
  41667. serializationObject.subMeshes = [];
  41668. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  41669. var subMesh = mesh.subMeshes[subIndex];
  41670. serializationObject.subMeshes.push({
  41671. materialIndex: subMesh.materialIndex,
  41672. verticesStart: subMesh.verticesStart,
  41673. verticesCount: subMesh.verticesCount,
  41674. indexStart: subMesh.indexStart,
  41675. indexCount: subMesh.indexCount
  41676. });
  41677. }
  41678. }
  41679. // Material
  41680. if (mesh.material) {
  41681. serializationObject.materialId = mesh.material.id;
  41682. }
  41683. else {
  41684. mesh.material = null;
  41685. }
  41686. // Skeleton
  41687. if (mesh.skeleton) {
  41688. serializationObject.skeletonId = mesh.skeleton.id;
  41689. }
  41690. // Physics
  41691. //TODO implement correct serialization for physics impostors.
  41692. if (mesh.getPhysicsImpostor()) {
  41693. serializationObject.physicsMass = mesh.getPhysicsMass();
  41694. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  41695. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  41696. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  41697. }
  41698. // Metadata
  41699. if (mesh.metadata) {
  41700. serializationObject.metadata = mesh.metadata;
  41701. }
  41702. // Instances
  41703. serializationObject.instances = [];
  41704. for (var index = 0; index < mesh.instances.length; index++) {
  41705. var instance = mesh.instances[index];
  41706. var serializationInstance = {
  41707. name: instance.name,
  41708. position: instance.position.asArray(),
  41709. scaling: instance.scaling.asArray()
  41710. };
  41711. if (instance.rotationQuaternion) {
  41712. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  41713. }
  41714. else if (instance.rotation) {
  41715. serializationInstance.rotation = instance.rotation.asArray();
  41716. }
  41717. serializationObject.instances.push(serializationInstance);
  41718. // Animations
  41719. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  41720. serializationInstance.ranges = instance.serializeAnimationRanges();
  41721. }
  41722. // Animations
  41723. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  41724. serializationObject.ranges = mesh.serializeAnimationRanges();
  41725. // Layer mask
  41726. serializationObject.layerMask = mesh.layerMask;
  41727. // Action Manager
  41728. if (mesh.actionManager) {
  41729. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  41730. }
  41731. return serializationObject;
  41732. };
  41733. var finalizeSingleMesh = function (mesh, serializationObject) {
  41734. //only works if the mesh is already loaded
  41735. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  41736. //serialize material
  41737. if (mesh.material) {
  41738. if (mesh.material instanceof BABYLON.StandardMaterial) {
  41739. serializationObject.materials = serializationObject.materials || [];
  41740. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  41741. serializationObject.materials.push(mesh.material.serialize());
  41742. }
  41743. }
  41744. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  41745. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  41746. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  41747. serializationObject.multiMaterials.push(mesh.material.serialize());
  41748. }
  41749. }
  41750. }
  41751. //serialize geometry
  41752. var geometry = mesh._geometry;
  41753. if (geometry) {
  41754. if (!serializationObject.geometries) {
  41755. serializationObject.geometries = {};
  41756. serializationObject.geometries.boxes = [];
  41757. serializationObject.geometries.spheres = [];
  41758. serializationObject.geometries.cylinders = [];
  41759. serializationObject.geometries.toruses = [];
  41760. serializationObject.geometries.grounds = [];
  41761. serializationObject.geometries.planes = [];
  41762. serializationObject.geometries.torusKnots = [];
  41763. serializationObject.geometries.vertexData = [];
  41764. }
  41765. serializeGeometry(geometry, serializationObject.geometries);
  41766. }
  41767. // Skeletons
  41768. if (mesh.skeleton) {
  41769. serializationObject.skeletons = serializationObject.skeletons || [];
  41770. serializationObject.skeletons.push(mesh.skeleton.serialize());
  41771. }
  41772. //serialize the actual mesh
  41773. serializationObject.meshes = serializationObject.meshes || [];
  41774. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  41775. }
  41776. };
  41777. var SceneSerializer = (function () {
  41778. function SceneSerializer() {
  41779. }
  41780. SceneSerializer.ClearCache = function () {
  41781. serializedGeometries = [];
  41782. };
  41783. SceneSerializer.Serialize = function (scene) {
  41784. var serializationObject = {};
  41785. // Scene
  41786. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  41787. serializationObject.autoClear = scene.autoClear;
  41788. serializationObject.clearColor = scene.clearColor.asArray();
  41789. serializationObject.ambientColor = scene.ambientColor.asArray();
  41790. serializationObject.gravity = scene.gravity.asArray();
  41791. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  41792. serializationObject.workerCollisions = scene.workerCollisions;
  41793. // Fog
  41794. if (scene.fogMode && scene.fogMode !== 0) {
  41795. serializationObject.fogMode = scene.fogMode;
  41796. serializationObject.fogColor = scene.fogColor.asArray();
  41797. serializationObject.fogStart = scene.fogStart;
  41798. serializationObject.fogEnd = scene.fogEnd;
  41799. serializationObject.fogDensity = scene.fogDensity;
  41800. }
  41801. //Physics
  41802. if (scene.isPhysicsEnabled()) {
  41803. serializationObject.physicsEnabled = true;
  41804. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  41805. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  41806. }
  41807. // Metadata
  41808. if (scene.metadata) {
  41809. serializationObject.metadata = scene.metadata;
  41810. }
  41811. // Lights
  41812. serializationObject.lights = [];
  41813. var index;
  41814. var light;
  41815. for (index = 0; index < scene.lights.length; index++) {
  41816. light = scene.lights[index];
  41817. serializationObject.lights.push(light.serialize());
  41818. }
  41819. // Cameras
  41820. serializationObject.cameras = [];
  41821. for (index = 0; index < scene.cameras.length; index++) {
  41822. var camera = scene.cameras[index];
  41823. serializationObject.cameras.push(camera.serialize());
  41824. }
  41825. if (scene.activeCamera) {
  41826. serializationObject.activeCameraID = scene.activeCamera.id;
  41827. }
  41828. // Animations
  41829. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  41830. // Materials
  41831. serializationObject.materials = [];
  41832. serializationObject.multiMaterials = [];
  41833. var material;
  41834. for (index = 0; index < scene.materials.length; index++) {
  41835. material = scene.materials[index];
  41836. serializationObject.materials.push(material.serialize());
  41837. }
  41838. // MultiMaterials
  41839. serializationObject.multiMaterials = [];
  41840. for (index = 0; index < scene.multiMaterials.length; index++) {
  41841. var multiMaterial = scene.multiMaterials[index];
  41842. serializationObject.multiMaterials.push(multiMaterial.serialize());
  41843. }
  41844. // Skeletons
  41845. serializationObject.skeletons = [];
  41846. for (index = 0; index < scene.skeletons.length; index++) {
  41847. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  41848. }
  41849. // Geometries
  41850. serializationObject.geometries = {};
  41851. serializationObject.geometries.boxes = [];
  41852. serializationObject.geometries.spheres = [];
  41853. serializationObject.geometries.cylinders = [];
  41854. serializationObject.geometries.toruses = [];
  41855. serializationObject.geometries.grounds = [];
  41856. serializationObject.geometries.planes = [];
  41857. serializationObject.geometries.torusKnots = [];
  41858. serializationObject.geometries.vertexData = [];
  41859. serializedGeometries = [];
  41860. var geometries = scene.getGeometries();
  41861. for (index = 0; index < geometries.length; index++) {
  41862. var geometry = geometries[index];
  41863. if (geometry.isReady()) {
  41864. serializeGeometry(geometry, serializationObject.geometries);
  41865. }
  41866. }
  41867. // Meshes
  41868. serializationObject.meshes = [];
  41869. for (index = 0; index < scene.meshes.length; index++) {
  41870. var abstractMesh = scene.meshes[index];
  41871. if (abstractMesh instanceof BABYLON.Mesh) {
  41872. var mesh = abstractMesh;
  41873. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  41874. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  41875. }
  41876. }
  41877. }
  41878. // Particles Systems
  41879. serializationObject.particleSystems = [];
  41880. for (index = 0; index < scene.particleSystems.length; index++) {
  41881. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  41882. }
  41883. // Lens flares
  41884. serializationObject.lensFlareSystems = [];
  41885. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  41886. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  41887. }
  41888. // Shadows
  41889. serializationObject.shadowGenerators = [];
  41890. for (index = 0; index < scene.lights.length; index++) {
  41891. light = scene.lights[index];
  41892. var shadowGenerator = light.getShadowGenerator();
  41893. // Only support serialization for official generator so far.
  41894. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  41895. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  41896. }
  41897. }
  41898. // Action Manager
  41899. if (scene.actionManager) {
  41900. serializationObject.actions = scene.actionManager.serialize("scene");
  41901. }
  41902. // Audio
  41903. serializationObject.sounds = [];
  41904. for (index = 0; index < scene.soundTracks.length; index++) {
  41905. var soundtrack = scene.soundTracks[index];
  41906. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  41907. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  41908. }
  41909. }
  41910. return serializationObject;
  41911. };
  41912. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  41913. if (withParents === void 0) { withParents = false; }
  41914. if (withChildren === void 0) { withChildren = false; }
  41915. var serializationObject = {};
  41916. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  41917. if (withParents || withChildren) {
  41918. //deliberate for loop! not for each, appended should be processed as well.
  41919. for (var i = 0; i < toSerialize.length; ++i) {
  41920. if (withChildren) {
  41921. toSerialize[i].getDescendants().forEach(function (node) {
  41922. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  41923. toSerialize.push(node);
  41924. }
  41925. });
  41926. }
  41927. //make sure the array doesn't contain the object already
  41928. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  41929. toSerialize.push(toSerialize[i].parent);
  41930. }
  41931. }
  41932. }
  41933. toSerialize.forEach(function (mesh) {
  41934. finalizeSingleMesh(mesh, serializationObject);
  41935. });
  41936. return serializationObject;
  41937. };
  41938. return SceneSerializer;
  41939. }());
  41940. BABYLON.SceneSerializer = SceneSerializer;
  41941. })(BABYLON || (BABYLON = {}));
  41942. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  41943. // Huge respect for a such great lib.
  41944. // Earcut license:
  41945. // Copyright (c) 2016, Mapbox
  41946. //
  41947. // Permission to use, copy, modify, and/or distribute this software for any purpose
  41948. // with or without fee is hereby granted, provided that the above copyright notice
  41949. // and this permission notice appear in all copies.
  41950. //
  41951. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  41952. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  41953. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  41954. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  41955. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  41956. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  41957. // THIS SOFTWARE.
  41958. var Earcut;
  41959. (function (Earcut) {
  41960. /**
  41961. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  41962. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  41963. * @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).
  41964. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  41965. */
  41966. function earcut(data, holeIndices, dim) {
  41967. dim = dim || 2;
  41968. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  41969. if (!outerNode)
  41970. return triangles;
  41971. var minX, minY, maxX, maxY, x, y, size;
  41972. if (hasHoles)
  41973. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  41974. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  41975. if (data.length > 80 * dim) {
  41976. minX = maxX = data[0];
  41977. minY = maxY = data[1];
  41978. for (var i = dim; i < outerLen; i += dim) {
  41979. x = data[i];
  41980. y = data[i + 1];
  41981. if (x < minX)
  41982. minX = x;
  41983. if (y < minY)
  41984. minY = y;
  41985. if (x > maxX)
  41986. maxX = x;
  41987. if (y > maxY)
  41988. maxY = y;
  41989. }
  41990. // minX, minY and size are later used to transform coords into integers for z-order calculation
  41991. size = Math.max(maxX - minX, maxY - minY);
  41992. }
  41993. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  41994. return triangles;
  41995. }
  41996. Earcut.earcut = earcut;
  41997. // create a circular doubly linked list from polygon points in the specified winding order
  41998. function linkedList(data, start, end, dim, clockwise) {
  41999. var i, last;
  42000. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  42001. for (i = start; i < end; i += dim)
  42002. last = insertNode(i, data[i], data[i + 1], last);
  42003. }
  42004. else {
  42005. for (i = end - dim; i >= start; i -= dim)
  42006. last = insertNode(i, data[i], data[i + 1], last);
  42007. }
  42008. if (last && equals(last, last.next)) {
  42009. removeNode(last);
  42010. last = last.next;
  42011. }
  42012. return last;
  42013. }
  42014. // eliminate colinear or duplicate points
  42015. function filterPoints(start, end) {
  42016. if (!start)
  42017. return start;
  42018. if (!end)
  42019. end = start;
  42020. var p = start, again;
  42021. do {
  42022. again = false;
  42023. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  42024. removeNode(p);
  42025. p = end = p.prev;
  42026. if (p === p.next)
  42027. return null;
  42028. again = true;
  42029. }
  42030. else {
  42031. p = p.next;
  42032. }
  42033. } while (again || p !== end);
  42034. return end;
  42035. }
  42036. // main ear slicing loop which triangulates a polygon (given as a linked list)
  42037. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  42038. if (!ear)
  42039. return;
  42040. // interlink polygon nodes in z-order
  42041. if (!pass && size)
  42042. indexCurve(ear, minX, minY, size);
  42043. var stop = ear, prev, next;
  42044. // iterate through ears, slicing them one by one
  42045. while (ear.prev !== ear.next) {
  42046. prev = ear.prev;
  42047. next = ear.next;
  42048. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  42049. // cut off the triangle
  42050. triangles.push(prev.i / dim);
  42051. triangles.push(ear.i / dim);
  42052. triangles.push(next.i / dim);
  42053. removeNode(ear);
  42054. // skipping the next vertice leads to less sliver triangles
  42055. ear = next.next;
  42056. stop = next.next;
  42057. continue;
  42058. }
  42059. ear = next;
  42060. // if we looped through the whole remaining polygon and can't find any more ears
  42061. if (ear === stop) {
  42062. // try filtering points and slicing again
  42063. if (!pass) {
  42064. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  42065. }
  42066. else if (pass === 1) {
  42067. ear = cureLocalIntersections(ear, triangles, dim);
  42068. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  42069. }
  42070. else if (pass === 2) {
  42071. splitEarcut(ear, triangles, dim, minX, minY, size);
  42072. }
  42073. break;
  42074. }
  42075. }
  42076. }
  42077. // check whether a polygon node forms a valid ear with adjacent nodes
  42078. function isEar(ear) {
  42079. var a = ear.prev, b = ear, c = ear.next;
  42080. if (area(a, b, c) >= 0)
  42081. return false; // reflex, can't be an ear
  42082. // now make sure we don't have other points inside the potential ear
  42083. var p = ear.next.next;
  42084. while (p !== ear.prev) {
  42085. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  42086. area(p.prev, p, p.next) >= 0)
  42087. return false;
  42088. p = p.next;
  42089. }
  42090. return true;
  42091. }
  42092. function isEarHashed(ear, minX, minY, size) {
  42093. var a = ear.prev, b = ear, c = ear.next;
  42094. if (area(a, b, c) >= 0)
  42095. return false; // reflex, can't be an ear
  42096. // triangle bbox; min & max are calculated like this for speed
  42097. 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);
  42098. // z-order range for the current triangle bbox;
  42099. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  42100. // first look for points inside the triangle in increasing z-order
  42101. var p = ear.nextZ;
  42102. while (p && p.z <= maxZ) {
  42103. if (p !== ear.prev &&
  42104. p !== ear.next &&
  42105. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  42106. area(p.prev, p, p.next) >= 0)
  42107. return false;
  42108. p = p.nextZ;
  42109. }
  42110. // then look for points in decreasing z-order
  42111. p = ear.prevZ;
  42112. while (p && p.z >= minZ) {
  42113. if (p !== ear.prev &&
  42114. p !== ear.next &&
  42115. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  42116. area(p.prev, p, p.next) >= 0)
  42117. return false;
  42118. p = p.prevZ;
  42119. }
  42120. return true;
  42121. }
  42122. // go through all polygon nodes and cure small local self-intersections
  42123. function cureLocalIntersections(start, triangles, dim) {
  42124. var p = start;
  42125. do {
  42126. var a = p.prev, b = p.next.next;
  42127. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  42128. triangles.push(a.i / dim);
  42129. triangles.push(p.i / dim);
  42130. triangles.push(b.i / dim);
  42131. // remove two nodes involved
  42132. removeNode(p);
  42133. removeNode(p.next);
  42134. p = start = b;
  42135. }
  42136. p = p.next;
  42137. } while (p !== start);
  42138. return p;
  42139. }
  42140. // try splitting polygon into two and triangulate them independently
  42141. function splitEarcut(start, triangles, dim, minX, minY, size) {
  42142. // look for a valid diagonal that divides the polygon into two
  42143. var a = start;
  42144. do {
  42145. var b = a.next.next;
  42146. while (b !== a.prev) {
  42147. if (a.i !== b.i && isValidDiagonal(a, b)) {
  42148. // split the polygon in two by the diagonal
  42149. var c = splitPolygon(a, b);
  42150. // filter colinear points around the cuts
  42151. a = filterPoints(a, a.next);
  42152. c = filterPoints(c, c.next);
  42153. // run earcut on each half
  42154. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  42155. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  42156. return;
  42157. }
  42158. b = b.next;
  42159. }
  42160. a = a.next;
  42161. } while (a !== start);
  42162. }
  42163. // link every hole into the outer loop, producing a single-ring polygon without holes
  42164. function eliminateHoles(data, holeIndices, outerNode, dim) {
  42165. var queue = [], i, len, start, end, list;
  42166. for (i = 0, len = holeIndices.length; i < len; i++) {
  42167. start = holeIndices[i] * dim;
  42168. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  42169. list = linkedList(data, start, end, dim, false);
  42170. if (list === list.next)
  42171. list.steiner = true;
  42172. queue.push(getLeftmost(list));
  42173. }
  42174. queue.sort(compareX);
  42175. // process holes from left to right
  42176. for (i = 0; i < queue.length; i++) {
  42177. eliminateHole(queue[i], outerNode);
  42178. outerNode = filterPoints(outerNode, outerNode.next);
  42179. }
  42180. return outerNode;
  42181. }
  42182. function compareX(a, b) {
  42183. return a.x - b.x;
  42184. }
  42185. // find a bridge between vertices that connects hole with an outer ring and and link it
  42186. function eliminateHole(hole, outerNode) {
  42187. outerNode = findHoleBridge(hole, outerNode);
  42188. if (outerNode) {
  42189. var b = splitPolygon(outerNode, hole);
  42190. filterPoints(b, b.next);
  42191. }
  42192. }
  42193. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  42194. function findHoleBridge(hole, outerNode) {
  42195. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  42196. // find a segment intersected by a ray from the hole's leftmost point to the left;
  42197. // segment's endpoint with lesser x will be potential connection point
  42198. do {
  42199. if (hy <= p.y && hy >= p.next.y) {
  42200. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  42201. if (x <= hx && x > qx) {
  42202. qx = x;
  42203. if (x === hx) {
  42204. if (hy === p.y)
  42205. return p;
  42206. if (hy === p.next.y)
  42207. return p.next;
  42208. }
  42209. m = p.x < p.next.x ? p : p.next;
  42210. }
  42211. }
  42212. p = p.next;
  42213. } while (p !== outerNode);
  42214. if (!m)
  42215. return null;
  42216. if (hx === qx)
  42217. return m.prev; // hole touches outer segment; pick lower endpoint
  42218. // look for points inside the triangle of hole point, segment intersection and endpoint;
  42219. // if there are no points found, we have a valid connection;
  42220. // otherwise choose the point of the minimum angle with the ray as connection point
  42221. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  42222. p = m.next;
  42223. while (p !== stop) {
  42224. if (hx >= p.x &&
  42225. p.x >= mx &&
  42226. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  42227. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  42228. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  42229. m = p;
  42230. tanMin = tan;
  42231. }
  42232. }
  42233. p = p.next;
  42234. }
  42235. return m;
  42236. }
  42237. // interlink polygon nodes in z-order
  42238. function indexCurve(start, minX, minY, size) {
  42239. var p = start;
  42240. do {
  42241. if (p.z === null)
  42242. p.z = zOrder(p.x, p.y, minX, minY, size);
  42243. p.prevZ = p.prev;
  42244. p.nextZ = p.next;
  42245. p = p.next;
  42246. } while (p !== start);
  42247. p.prevZ.nextZ = null;
  42248. p.prevZ = null;
  42249. sortLinked(p);
  42250. }
  42251. // Simon Tatham's linked list merge sort algorithm
  42252. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  42253. function sortLinked(list) {
  42254. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  42255. do {
  42256. p = list;
  42257. list = null;
  42258. tail = null;
  42259. numMerges = 0;
  42260. while (p) {
  42261. numMerges++;
  42262. q = p;
  42263. pSize = 0;
  42264. for (i = 0; i < inSize; i++) {
  42265. pSize++;
  42266. q = q.nextZ;
  42267. if (!q)
  42268. break;
  42269. }
  42270. qSize = inSize;
  42271. while (pSize > 0 || (qSize > 0 && q)) {
  42272. if (pSize === 0) {
  42273. e = q;
  42274. q = q.nextZ;
  42275. qSize--;
  42276. }
  42277. else if (qSize === 0 || !q) {
  42278. e = p;
  42279. p = p.nextZ;
  42280. pSize--;
  42281. }
  42282. else if (p.z <= q.z) {
  42283. e = p;
  42284. p = p.nextZ;
  42285. pSize--;
  42286. }
  42287. else {
  42288. e = q;
  42289. q = q.nextZ;
  42290. qSize--;
  42291. }
  42292. if (tail)
  42293. tail.nextZ = e;
  42294. else
  42295. list = e;
  42296. e.prevZ = tail;
  42297. tail = e;
  42298. }
  42299. p = q;
  42300. }
  42301. tail.nextZ = null;
  42302. inSize *= 2;
  42303. } while (numMerges > 1);
  42304. return list;
  42305. }
  42306. // z-order of a point given coords and size of the data bounding box
  42307. function zOrder(x, y, minX, minY, size) {
  42308. // coords are transformed into non-negative 15-bit integer range
  42309. x = 32767 * (x - minX) / size;
  42310. y = 32767 * (y - minY) / size;
  42311. x = (x | (x << 8)) & 0x00FF00FF;
  42312. x = (x | (x << 4)) & 0x0F0F0F0F;
  42313. x = (x | (x << 2)) & 0x33333333;
  42314. x = (x | (x << 1)) & 0x55555555;
  42315. y = (y | (y << 8)) & 0x00FF00FF;
  42316. y = (y | (y << 4)) & 0x0F0F0F0F;
  42317. y = (y | (y << 2)) & 0x33333333;
  42318. y = (y | (y << 1)) & 0x55555555;
  42319. return x | (y << 1);
  42320. }
  42321. // find the leftmost node of a polygon ring
  42322. function getLeftmost(start) {
  42323. var p = start, leftmost = start;
  42324. do {
  42325. if (p.x < leftmost.x)
  42326. leftmost = p;
  42327. p = p.next;
  42328. } while (p !== start);
  42329. return leftmost;
  42330. }
  42331. // check if a point lies within a convex triangle
  42332. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  42333. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  42334. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  42335. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  42336. }
  42337. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  42338. function isValidDiagonal(a, b) {
  42339. return a.next.i !== b.i &&
  42340. a.prev.i !== b.i &&
  42341. !intersectsPolygon(a, b) &&
  42342. locallyInside(a, b) &&
  42343. locallyInside(b, a) &&
  42344. middleInside(a, b);
  42345. }
  42346. // signed area of a triangle
  42347. function area(p, q, r) {
  42348. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  42349. }
  42350. // check if two points are equal
  42351. function equals(p1, p2) {
  42352. return p1.x === p2.x && p1.y === p2.y;
  42353. }
  42354. // check if two segments intersect
  42355. function intersects(p1, q1, p2, q2) {
  42356. if ((equals(p1, q1) && equals(p2, q2)) ||
  42357. (equals(p1, q2) && equals(p2, q1)))
  42358. return true;
  42359. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  42360. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  42361. }
  42362. // check if a polygon diagonal intersects any polygon segments
  42363. function intersectsPolygon(a, b) {
  42364. var p = a;
  42365. do {
  42366. if (p.i !== a.i &&
  42367. p.next.i !== a.i &&
  42368. p.i !== b.i &&
  42369. p.next.i !== b.i &&
  42370. intersects(p, p.next, a, b))
  42371. return true;
  42372. p = p.next;
  42373. } while (p !== a);
  42374. return false;
  42375. }
  42376. // check if a polygon diagonal is locally inside the polygon
  42377. function locallyInside(a, b) {
  42378. return area(a.prev, a, a.next) < 0
  42379. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  42380. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  42381. }
  42382. // check if the middle point of a polygon diagonal is inside the polygon
  42383. function middleInside(a, b) {
  42384. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  42385. do {
  42386. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  42387. inside = !inside;
  42388. p = p.next;
  42389. } while (p !== a);
  42390. return inside;
  42391. }
  42392. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  42393. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  42394. function splitPolygon(a, b) {
  42395. 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;
  42396. a.next = b;
  42397. b.prev = a;
  42398. a2.next = an;
  42399. an.prev = a2;
  42400. b2.next = a2;
  42401. a2.prev = b2;
  42402. bp.next = b2;
  42403. b2.prev = bp;
  42404. return b2;
  42405. }
  42406. // create a node and optionally link it with previous one (in a circular doubly linked list)
  42407. function insertNode(i, x, y, last) {
  42408. var p = new Node(i, x, y);
  42409. if (!last) {
  42410. p.prev = p;
  42411. p.next = p;
  42412. }
  42413. else {
  42414. p.next = last.next;
  42415. p.prev = last;
  42416. last.next.prev = p;
  42417. last.next = p;
  42418. }
  42419. return p;
  42420. }
  42421. function removeNode(p) {
  42422. p.next.prev = p.prev;
  42423. p.prev.next = p.next;
  42424. if (p.prevZ)
  42425. p.prevZ.nextZ = p.nextZ;
  42426. if (p.nextZ)
  42427. p.nextZ.prevZ = p.prevZ;
  42428. }
  42429. function Node(i, x, y) {
  42430. // vertice index in coordinates array
  42431. this.i = i;
  42432. // vertex coordinates
  42433. this.x = x;
  42434. this.y = y;
  42435. // previous and next vertice nodes in a polygon ring
  42436. this.prev = null;
  42437. this.next = null;
  42438. // z-order curve value
  42439. this.z = null;
  42440. // previous and next nodes in z-order
  42441. this.prevZ = null;
  42442. this.nextZ = null;
  42443. // indicates whether this is a steiner point
  42444. this.steiner = false;
  42445. }
  42446. /**
  42447. * return a percentage difference between the polygon area and its triangulation area;
  42448. * used to verify correctness of triangulation
  42449. */
  42450. function deviation(data, holeIndices, dim, triangles) {
  42451. var hasHoles = holeIndices && holeIndices.length;
  42452. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  42453. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  42454. if (hasHoles) {
  42455. for (var i = 0, len = holeIndices.length; i < len; i++) {
  42456. var start = holeIndices[i] * dim;
  42457. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  42458. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  42459. }
  42460. }
  42461. var trianglesArea = 0;
  42462. for (i = 0; i < triangles.length; i += 3) {
  42463. var a = triangles[i] * dim;
  42464. var b = triangles[i + 1] * dim;
  42465. var c = triangles[i + 2] * dim;
  42466. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  42467. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  42468. }
  42469. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  42470. }
  42471. Earcut.deviation = deviation;
  42472. ;
  42473. function signedArea(data, start, end, dim) {
  42474. var sum = 0;
  42475. for (var i = start, j = end - dim; i < end; i += dim) {
  42476. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  42477. j = i;
  42478. }
  42479. return sum;
  42480. }
  42481. /**
  42482. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  42483. */
  42484. function flatten(data) {
  42485. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  42486. for (var i = 0; i < data.length; i++) {
  42487. for (var j = 0; j < data[i].length; j++) {
  42488. for (var d = 0; d < dim; d++)
  42489. result.vertices.push(data[i][j][d]);
  42490. }
  42491. if (i > 0) {
  42492. holeIndex += data[i - 1].length;
  42493. result.holes.push(holeIndex);
  42494. }
  42495. }
  42496. return result;
  42497. }
  42498. Earcut.flatten = flatten;
  42499. ;
  42500. })(Earcut || (Earcut = {}));
  42501. var BABYLON;
  42502. (function (BABYLON) {
  42503. // Unique ID when we import meshes from Babylon to CSG
  42504. var currentCSGMeshId = 0;
  42505. // # class Vertex
  42506. // Represents a vertex of a polygon. Use your own vertex class instead of this
  42507. // one to provide additional features like texture coordinates and vertex
  42508. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  42509. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  42510. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  42511. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  42512. // is not used anywhere else.
  42513. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  42514. var Vertex = (function () {
  42515. function Vertex(pos, normal, uv) {
  42516. this.pos = pos;
  42517. this.normal = normal;
  42518. this.uv = uv;
  42519. }
  42520. Vertex.prototype.clone = function () {
  42521. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  42522. };
  42523. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  42524. // orientation of a polygon is flipped.
  42525. Vertex.prototype.flip = function () {
  42526. this.normal = this.normal.scale(-1);
  42527. };
  42528. // Create a new vertex between this vertex and `other` by linearly
  42529. // interpolating all properties using a parameter of `t`. Subclasses should
  42530. // override this to interpolate additional properties.
  42531. Vertex.prototype.interpolate = function (other, t) {
  42532. 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));
  42533. };
  42534. return Vertex;
  42535. }());
  42536. // # class Plane
  42537. // Represents a plane in 3D space.
  42538. var Plane = (function () {
  42539. function Plane(normal, w) {
  42540. this.normal = normal;
  42541. this.w = w;
  42542. }
  42543. Plane.FromPoints = function (a, b, c) {
  42544. var v0 = c.subtract(a);
  42545. var v1 = b.subtract(a);
  42546. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  42547. return null;
  42548. }
  42549. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  42550. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  42551. };
  42552. Plane.prototype.clone = function () {
  42553. return new Plane(this.normal.clone(), this.w);
  42554. };
  42555. Plane.prototype.flip = function () {
  42556. this.normal.scaleInPlace(-1);
  42557. this.w = -this.w;
  42558. };
  42559. // Split `polygon` by this plane if needed, then put the polygon or polygon
  42560. // fragments in the appropriate lists. Coplanar polygons go into either
  42561. // `coplanarFront` or `coplanarBack` depending on their orientation with
  42562. // respect to this plane. Polygons in front or in back of this plane go into
  42563. // either `front` or `back`.
  42564. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  42565. var COPLANAR = 0;
  42566. var FRONT = 1;
  42567. var BACK = 2;
  42568. var SPANNING = 3;
  42569. // Classify each point as well as the entire polygon into one of the above
  42570. // four classes.
  42571. var polygonType = 0;
  42572. var types = [];
  42573. var i;
  42574. var t;
  42575. for (i = 0; i < polygon.vertices.length; i++) {
  42576. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  42577. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  42578. polygonType |= type;
  42579. types.push(type);
  42580. }
  42581. // Put the polygon in the correct list, splitting it when necessary.
  42582. switch (polygonType) {
  42583. case COPLANAR:
  42584. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  42585. break;
  42586. case FRONT:
  42587. front.push(polygon);
  42588. break;
  42589. case BACK:
  42590. back.push(polygon);
  42591. break;
  42592. case SPANNING:
  42593. var f = [], b = [];
  42594. for (i = 0; i < polygon.vertices.length; i++) {
  42595. var j = (i + 1) % polygon.vertices.length;
  42596. var ti = types[i], tj = types[j];
  42597. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  42598. if (ti !== BACK)
  42599. f.push(vi);
  42600. if (ti !== FRONT)
  42601. b.push(ti !== BACK ? vi.clone() : vi);
  42602. if ((ti | tj) === SPANNING) {
  42603. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  42604. var v = vi.interpolate(vj, t);
  42605. f.push(v);
  42606. b.push(v.clone());
  42607. }
  42608. }
  42609. var poly;
  42610. if (f.length >= 3) {
  42611. poly = new Polygon(f, polygon.shared);
  42612. if (poly.plane)
  42613. front.push(poly);
  42614. }
  42615. if (b.length >= 3) {
  42616. poly = new Polygon(b, polygon.shared);
  42617. if (poly.plane)
  42618. back.push(poly);
  42619. }
  42620. break;
  42621. }
  42622. };
  42623. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  42624. // point is on the plane.
  42625. Plane.EPSILON = 1e-5;
  42626. return Plane;
  42627. }());
  42628. // # class Polygon
  42629. // Represents a convex polygon. The vertices used to initialize a polygon must
  42630. // be coplanar and form a convex loop.
  42631. //
  42632. // Each convex polygon has a `shared` property, which is shared between all
  42633. // polygons that are clones of each other or were split from the same polygon.
  42634. // This can be used to define per-polygon properties (such as surface color).
  42635. var Polygon = (function () {
  42636. function Polygon(vertices, shared) {
  42637. this.vertices = vertices;
  42638. this.shared = shared;
  42639. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  42640. }
  42641. Polygon.prototype.clone = function () {
  42642. var vertices = this.vertices.map(function (v) { return v.clone(); });
  42643. return new Polygon(vertices, this.shared);
  42644. };
  42645. Polygon.prototype.flip = function () {
  42646. this.vertices.reverse().map(function (v) { v.flip(); });
  42647. this.plane.flip();
  42648. };
  42649. return Polygon;
  42650. }());
  42651. // # class Node
  42652. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  42653. // by picking a polygon to split along. That polygon (and all other coplanar
  42654. // polygons) are added directly to that node and the other polygons are added to
  42655. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  42656. // no distinction between internal and leaf nodes.
  42657. var Node = (function () {
  42658. function Node(polygons) {
  42659. this.plane = null;
  42660. this.front = null;
  42661. this.back = null;
  42662. this.polygons = [];
  42663. if (polygons) {
  42664. this.build(polygons);
  42665. }
  42666. }
  42667. Node.prototype.clone = function () {
  42668. var node = new Node();
  42669. node.plane = this.plane && this.plane.clone();
  42670. node.front = this.front && this.front.clone();
  42671. node.back = this.back && this.back.clone();
  42672. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  42673. return node;
  42674. };
  42675. // Convert solid space to empty space and empty space to solid space.
  42676. Node.prototype.invert = function () {
  42677. for (var i = 0; i < this.polygons.length; i++) {
  42678. this.polygons[i].flip();
  42679. }
  42680. if (this.plane) {
  42681. this.plane.flip();
  42682. }
  42683. if (this.front) {
  42684. this.front.invert();
  42685. }
  42686. if (this.back) {
  42687. this.back.invert();
  42688. }
  42689. var temp = this.front;
  42690. this.front = this.back;
  42691. this.back = temp;
  42692. };
  42693. // Recursively remove all polygons in `polygons` that are inside this BSP
  42694. // tree.
  42695. Node.prototype.clipPolygons = function (polygons) {
  42696. if (!this.plane)
  42697. return polygons.slice();
  42698. var front = [], back = [];
  42699. for (var i = 0; i < polygons.length; i++) {
  42700. this.plane.splitPolygon(polygons[i], front, back, front, back);
  42701. }
  42702. if (this.front) {
  42703. front = this.front.clipPolygons(front);
  42704. }
  42705. if (this.back) {
  42706. back = this.back.clipPolygons(back);
  42707. }
  42708. else {
  42709. back = [];
  42710. }
  42711. return front.concat(back);
  42712. };
  42713. // Remove all polygons in this BSP tree that are inside the other BSP tree
  42714. // `bsp`.
  42715. Node.prototype.clipTo = function (bsp) {
  42716. this.polygons = bsp.clipPolygons(this.polygons);
  42717. if (this.front)
  42718. this.front.clipTo(bsp);
  42719. if (this.back)
  42720. this.back.clipTo(bsp);
  42721. };
  42722. // Return a list of all polygons in this BSP tree.
  42723. Node.prototype.allPolygons = function () {
  42724. var polygons = this.polygons.slice();
  42725. if (this.front)
  42726. polygons = polygons.concat(this.front.allPolygons());
  42727. if (this.back)
  42728. polygons = polygons.concat(this.back.allPolygons());
  42729. return polygons;
  42730. };
  42731. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  42732. // new polygons are filtered down to the bottom of the tree and become new
  42733. // nodes there. Each set of polygons is partitioned using the first polygon
  42734. // (no heuristic is used to pick a good split).
  42735. Node.prototype.build = function (polygons) {
  42736. if (!polygons.length)
  42737. return;
  42738. if (!this.plane)
  42739. this.plane = polygons[0].plane.clone();
  42740. var front = [], back = [];
  42741. for (var i = 0; i < polygons.length; i++) {
  42742. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  42743. }
  42744. if (front.length) {
  42745. if (!this.front)
  42746. this.front = new Node();
  42747. this.front.build(front);
  42748. }
  42749. if (back.length) {
  42750. if (!this.back)
  42751. this.back = new Node();
  42752. this.back.build(back);
  42753. }
  42754. };
  42755. return Node;
  42756. }());
  42757. var CSG = (function () {
  42758. function CSG() {
  42759. this.polygons = new Array();
  42760. }
  42761. // Convert BABYLON.Mesh to BABYLON.CSG
  42762. CSG.FromMesh = function (mesh) {
  42763. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  42764. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  42765. if (mesh instanceof BABYLON.Mesh) {
  42766. mesh.computeWorldMatrix(true);
  42767. matrix = mesh.getWorldMatrix();
  42768. meshPosition = mesh.position.clone();
  42769. meshRotation = mesh.rotation.clone();
  42770. if (mesh.rotationQuaternion) {
  42771. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  42772. }
  42773. meshScaling = mesh.scaling.clone();
  42774. }
  42775. else {
  42776. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  42777. }
  42778. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42779. var subMeshes = mesh.subMeshes;
  42780. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  42781. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  42782. vertices = [];
  42783. for (var j = 0; j < 3; j++) {
  42784. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  42785. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  42786. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  42787. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  42788. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  42789. vertex = new Vertex(position, normal, uv);
  42790. vertices.push(vertex);
  42791. }
  42792. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  42793. // To handle the case of degenerated triangle
  42794. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  42795. if (polygon.plane)
  42796. polygons.push(polygon);
  42797. }
  42798. }
  42799. var csg = CSG.FromPolygons(polygons);
  42800. csg.matrix = matrix;
  42801. csg.position = meshPosition;
  42802. csg.rotation = meshRotation;
  42803. csg.scaling = meshScaling;
  42804. csg.rotationQuaternion = meshRotationQuaternion;
  42805. currentCSGMeshId++;
  42806. return csg;
  42807. };
  42808. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  42809. CSG.FromPolygons = function (polygons) {
  42810. var csg = new CSG();
  42811. csg.polygons = polygons;
  42812. return csg;
  42813. };
  42814. CSG.prototype.clone = function () {
  42815. var csg = new CSG();
  42816. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  42817. csg.copyTransformAttributes(this);
  42818. return csg;
  42819. };
  42820. CSG.prototype.toPolygons = function () {
  42821. return this.polygons;
  42822. };
  42823. CSG.prototype.union = function (csg) {
  42824. var a = new Node(this.clone().polygons);
  42825. var b = new Node(csg.clone().polygons);
  42826. a.clipTo(b);
  42827. b.clipTo(a);
  42828. b.invert();
  42829. b.clipTo(a);
  42830. b.invert();
  42831. a.build(b.allPolygons());
  42832. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  42833. };
  42834. CSG.prototype.unionInPlace = function (csg) {
  42835. var a = new Node(this.polygons);
  42836. var b = new Node(csg.polygons);
  42837. a.clipTo(b);
  42838. b.clipTo(a);
  42839. b.invert();
  42840. b.clipTo(a);
  42841. b.invert();
  42842. a.build(b.allPolygons());
  42843. this.polygons = a.allPolygons();
  42844. };
  42845. CSG.prototype.subtract = function (csg) {
  42846. var a = new Node(this.clone().polygons);
  42847. var b = new Node(csg.clone().polygons);
  42848. a.invert();
  42849. a.clipTo(b);
  42850. b.clipTo(a);
  42851. b.invert();
  42852. b.clipTo(a);
  42853. b.invert();
  42854. a.build(b.allPolygons());
  42855. a.invert();
  42856. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  42857. };
  42858. CSG.prototype.subtractInPlace = function (csg) {
  42859. var a = new Node(this.polygons);
  42860. var b = new Node(csg.polygons);
  42861. a.invert();
  42862. a.clipTo(b);
  42863. b.clipTo(a);
  42864. b.invert();
  42865. b.clipTo(a);
  42866. b.invert();
  42867. a.build(b.allPolygons());
  42868. a.invert();
  42869. this.polygons = a.allPolygons();
  42870. };
  42871. CSG.prototype.intersect = function (csg) {
  42872. var a = new Node(this.clone().polygons);
  42873. var b = new Node(csg.clone().polygons);
  42874. a.invert();
  42875. b.clipTo(a);
  42876. b.invert();
  42877. a.clipTo(b);
  42878. b.clipTo(a);
  42879. a.build(b.allPolygons());
  42880. a.invert();
  42881. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  42882. };
  42883. CSG.prototype.intersectInPlace = function (csg) {
  42884. var a = new Node(this.polygons);
  42885. var b = new Node(csg.polygons);
  42886. a.invert();
  42887. b.clipTo(a);
  42888. b.invert();
  42889. a.clipTo(b);
  42890. b.clipTo(a);
  42891. a.build(b.allPolygons());
  42892. a.invert();
  42893. this.polygons = a.allPolygons();
  42894. };
  42895. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  42896. // not modified.
  42897. CSG.prototype.inverse = function () {
  42898. var csg = this.clone();
  42899. csg.inverseInPlace();
  42900. return csg;
  42901. };
  42902. CSG.prototype.inverseInPlace = function () {
  42903. this.polygons.map(function (p) { p.flip(); });
  42904. };
  42905. // This is used to keep meshes transformations so they can be restored
  42906. // when we build back a Babylon Mesh
  42907. // NB : All CSG operations are performed in world coordinates
  42908. CSG.prototype.copyTransformAttributes = function (csg) {
  42909. this.matrix = csg.matrix;
  42910. this.position = csg.position;
  42911. this.rotation = csg.rotation;
  42912. this.scaling = csg.scaling;
  42913. this.rotationQuaternion = csg.rotationQuaternion;
  42914. return this;
  42915. };
  42916. // Build Raw mesh from CSG
  42917. // Coordinates here are in world space
  42918. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  42919. var matrix = this.matrix.clone();
  42920. matrix.invert();
  42921. 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;
  42922. if (keepSubMeshes) {
  42923. // Sort Polygons, since subMeshes are indices range
  42924. polygons.sort(function (a, b) {
  42925. if (a.shared.meshId === b.shared.meshId) {
  42926. return a.shared.subMeshId - b.shared.subMeshId;
  42927. }
  42928. else {
  42929. return a.shared.meshId - b.shared.meshId;
  42930. }
  42931. });
  42932. }
  42933. for (var i = 0, il = polygons.length; i < il; i++) {
  42934. polygon = polygons[i];
  42935. // Building SubMeshes
  42936. if (!subMesh_dict[polygon.shared.meshId]) {
  42937. subMesh_dict[polygon.shared.meshId] = {};
  42938. }
  42939. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  42940. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  42941. indexStart: +Infinity,
  42942. indexEnd: -Infinity,
  42943. materialIndex: polygon.shared.materialIndex
  42944. };
  42945. }
  42946. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  42947. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  42948. polygonIndices[0] = 0;
  42949. polygonIndices[1] = j - 1;
  42950. polygonIndices[2] = j;
  42951. for (var k = 0; k < 3; k++) {
  42952. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  42953. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  42954. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  42955. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  42956. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  42957. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  42958. // Check if 2 points can be merged
  42959. if (!(typeof vertex_idx !== 'undefined' &&
  42960. normals[vertex_idx * 3] === localNormal.x &&
  42961. normals[vertex_idx * 3 + 1] === localNormal.y &&
  42962. normals[vertex_idx * 3 + 2] === localNormal.z &&
  42963. uvs[vertex_idx * 2] === uv.x &&
  42964. uvs[vertex_idx * 2 + 1] === uv.y)) {
  42965. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  42966. uvs.push(uv.x, uv.y);
  42967. normals.push(normal.x, normal.y, normal.z);
  42968. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  42969. }
  42970. indices.push(vertex_idx);
  42971. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  42972. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  42973. currentIndex++;
  42974. }
  42975. }
  42976. }
  42977. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  42978. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  42979. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  42980. mesh.setIndices(indices);
  42981. if (keepSubMeshes) {
  42982. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  42983. var materialIndexOffset = 0, materialMaxIndex;
  42984. mesh.subMeshes = new Array();
  42985. for (var m in subMesh_dict) {
  42986. materialMaxIndex = -1;
  42987. for (var sm in subMesh_dict[m]) {
  42988. subMesh_obj = subMesh_dict[m][sm];
  42989. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  42990. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  42991. }
  42992. materialIndexOffset += ++materialMaxIndex;
  42993. }
  42994. }
  42995. return mesh;
  42996. };
  42997. // Build Mesh from CSG taking material and transforms into account
  42998. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  42999. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  43000. mesh.material = material;
  43001. mesh.position.copyFrom(this.position);
  43002. mesh.rotation.copyFrom(this.rotation);
  43003. if (this.rotationQuaternion) {
  43004. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  43005. }
  43006. mesh.scaling.copyFrom(this.scaling);
  43007. mesh.computeWorldMatrix(true);
  43008. return mesh;
  43009. };
  43010. return CSG;
  43011. }());
  43012. BABYLON.CSG = CSG;
  43013. })(BABYLON || (BABYLON = {}));
  43014. var BABYLON;
  43015. (function (BABYLON) {
  43016. var VRDistortionCorrectionPostProcess = (function (_super) {
  43017. __extends(VRDistortionCorrectionPostProcess, _super);
  43018. //ANY
  43019. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  43020. var _this = this;
  43021. _super.call(this, name, "vrDistortionCorrection", [
  43022. 'LensCenter',
  43023. 'Scale',
  43024. 'ScaleIn',
  43025. 'HmdWarpParam'
  43026. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  43027. this._isRightEye = isRightEye;
  43028. this._distortionFactors = vrMetrics.distortionK;
  43029. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  43030. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  43031. this.onSizeChangedObservable.add(function () {
  43032. _this.aspectRatio = _this.width * .5 / _this.height;
  43033. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  43034. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  43035. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  43036. });
  43037. this.onApplyObservable.add(function (effect) {
  43038. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  43039. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  43040. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  43041. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  43042. });
  43043. }
  43044. return VRDistortionCorrectionPostProcess;
  43045. }(BABYLON.PostProcess));
  43046. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  43047. })(BABYLON || (BABYLON = {}));
  43048. // Mainly based on these 2 articles :
  43049. // 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
  43050. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  43051. var BABYLON;
  43052. (function (BABYLON) {
  43053. (function (JoystickAxis) {
  43054. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  43055. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  43056. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  43057. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  43058. var JoystickAxis = BABYLON.JoystickAxis;
  43059. var VirtualJoystick = (function () {
  43060. function VirtualJoystick(leftJoystick) {
  43061. var _this = this;
  43062. if (leftJoystick) {
  43063. this._leftJoystick = true;
  43064. }
  43065. else {
  43066. this._leftJoystick = false;
  43067. }
  43068. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  43069. VirtualJoystick._globalJoystickIndex++;
  43070. // By default left & right arrow keys are moving the X
  43071. // and up & down keys are moving the Y
  43072. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  43073. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  43074. this.reverseLeftRight = false;
  43075. this.reverseUpDown = false;
  43076. // collections of pointers
  43077. this._touches = new BABYLON.StringDictionary();
  43078. this.deltaPosition = BABYLON.Vector3.Zero();
  43079. this._joystickSensibility = 25;
  43080. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  43081. this._rotationSpeed = 25;
  43082. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  43083. this._rotateOnAxisRelativeToMesh = false;
  43084. this._onResize = function (evt) {
  43085. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  43086. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  43087. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  43088. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  43089. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  43090. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  43091. };
  43092. // injecting a canvas element on top of the canvas 3D game
  43093. if (!VirtualJoystick.vjCanvas) {
  43094. window.addEventListener("resize", this._onResize, false);
  43095. VirtualJoystick.vjCanvas = document.createElement("canvas");
  43096. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  43097. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  43098. VirtualJoystick.vjCanvas.width = window.innerWidth;
  43099. VirtualJoystick.vjCanvas.height = window.innerHeight;
  43100. VirtualJoystick.vjCanvas.style.width = "100%";
  43101. VirtualJoystick.vjCanvas.style.height = "100%";
  43102. VirtualJoystick.vjCanvas.style.position = "absolute";
  43103. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  43104. VirtualJoystick.vjCanvas.style.top = "0px";
  43105. VirtualJoystick.vjCanvas.style.left = "0px";
  43106. VirtualJoystick.vjCanvas.style.zIndex = "5";
  43107. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  43108. // Support for jQuery PEP polyfill
  43109. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  43110. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  43111. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  43112. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  43113. document.body.appendChild(VirtualJoystick.vjCanvas);
  43114. }
  43115. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  43116. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  43117. this.pressed = false;
  43118. // default joystick color
  43119. this._joystickColor = "cyan";
  43120. this._joystickPointerID = -1;
  43121. // current joystick position
  43122. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  43123. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  43124. // origin joystick position
  43125. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  43126. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  43127. this._onPointerDownHandlerRef = function (evt) {
  43128. _this._onPointerDown(evt);
  43129. };
  43130. this._onPointerMoveHandlerRef = function (evt) {
  43131. _this._onPointerMove(evt);
  43132. };
  43133. this._onPointerOutHandlerRef = function (evt) {
  43134. _this._onPointerUp(evt);
  43135. };
  43136. this._onPointerUpHandlerRef = function (evt) {
  43137. _this._onPointerUp(evt);
  43138. };
  43139. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  43140. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  43141. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  43142. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  43143. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  43144. evt.preventDefault(); // Disables system menu
  43145. }, false);
  43146. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  43147. }
  43148. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  43149. this._joystickSensibility = newJoystickSensibility;
  43150. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  43151. };
  43152. VirtualJoystick.prototype._onPointerDown = function (e) {
  43153. var positionOnScreenCondition;
  43154. e.preventDefault();
  43155. if (this._leftJoystick === true) {
  43156. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  43157. }
  43158. else {
  43159. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  43160. }
  43161. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  43162. // First contact will be dedicated to the virtual joystick
  43163. this._joystickPointerID = e.pointerId;
  43164. this._joystickPointerStartPos.x = e.clientX;
  43165. this._joystickPointerStartPos.y = e.clientY;
  43166. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  43167. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  43168. this._deltaJoystickVector.x = 0;
  43169. this._deltaJoystickVector.y = 0;
  43170. this.pressed = true;
  43171. this._touches.add(e.pointerId.toString(), e);
  43172. }
  43173. else {
  43174. // You can only trigger the action buttons with a joystick declared
  43175. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  43176. this._action();
  43177. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  43178. }
  43179. }
  43180. };
  43181. VirtualJoystick.prototype._onPointerMove = function (e) {
  43182. // If the current pointer is the one associated to the joystick (first touch contact)
  43183. if (this._joystickPointerID == e.pointerId) {
  43184. this._joystickPointerPos.x = e.clientX;
  43185. this._joystickPointerPos.y = e.clientY;
  43186. this._deltaJoystickVector = this._joystickPointerPos.clone();
  43187. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  43188. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  43189. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  43190. switch (this._axisTargetedByLeftAndRight) {
  43191. case JoystickAxis.X:
  43192. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  43193. break;
  43194. case JoystickAxis.Y:
  43195. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  43196. break;
  43197. case JoystickAxis.Z:
  43198. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  43199. break;
  43200. }
  43201. var directionUpDown = this.reverseUpDown ? 1 : -1;
  43202. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  43203. switch (this._axisTargetedByUpAndDown) {
  43204. case JoystickAxis.X:
  43205. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  43206. break;
  43207. case JoystickAxis.Y:
  43208. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  43209. break;
  43210. case JoystickAxis.Z:
  43211. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  43212. break;
  43213. }
  43214. }
  43215. else {
  43216. var data = this._touches.get(e.pointerId.toString());
  43217. if (data) {
  43218. data.x = e.clientX;
  43219. data.y = e.clientY;
  43220. }
  43221. }
  43222. };
  43223. VirtualJoystick.prototype._onPointerUp = function (e) {
  43224. if (this._joystickPointerID == e.pointerId) {
  43225. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  43226. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  43227. this._joystickPointerID = -1;
  43228. this.pressed = false;
  43229. }
  43230. else {
  43231. var touch = this._touches.get(e.pointerId.toString());
  43232. if (touch) {
  43233. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  43234. }
  43235. }
  43236. this._deltaJoystickVector.x = 0;
  43237. this._deltaJoystickVector.y = 0;
  43238. this._touches.remove(e.pointerId.toString());
  43239. };
  43240. /**
  43241. * Change the color of the virtual joystick
  43242. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  43243. */
  43244. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  43245. this._joystickColor = newColor;
  43246. };
  43247. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  43248. this._action = action;
  43249. };
  43250. // Define which axis you'd like to control for left & right
  43251. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  43252. switch (axis) {
  43253. case JoystickAxis.X:
  43254. case JoystickAxis.Y:
  43255. case JoystickAxis.Z:
  43256. this._axisTargetedByLeftAndRight = axis;
  43257. break;
  43258. default:
  43259. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  43260. break;
  43261. }
  43262. };
  43263. // Define which axis you'd like to control for up & down
  43264. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  43265. switch (axis) {
  43266. case JoystickAxis.X:
  43267. case JoystickAxis.Y:
  43268. case JoystickAxis.Z:
  43269. this._axisTargetedByUpAndDown = axis;
  43270. break;
  43271. default:
  43272. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  43273. break;
  43274. }
  43275. };
  43276. VirtualJoystick.prototype._clearCanvas = function () {
  43277. if (this._leftJoystick) {
  43278. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  43279. }
  43280. else {
  43281. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  43282. }
  43283. };
  43284. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  43285. var _this = this;
  43286. if (this.pressed) {
  43287. this._touches.forEach(function (touch) {
  43288. if (touch.pointerId === _this._joystickPointerID) {
  43289. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  43290. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  43291. VirtualJoystick.vjCanvasContext.beginPath();
  43292. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  43293. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  43294. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  43295. VirtualJoystick.vjCanvasContext.stroke();
  43296. VirtualJoystick.vjCanvasContext.closePath();
  43297. VirtualJoystick.vjCanvasContext.beginPath();
  43298. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  43299. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  43300. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  43301. VirtualJoystick.vjCanvasContext.stroke();
  43302. VirtualJoystick.vjCanvasContext.closePath();
  43303. VirtualJoystick.vjCanvasContext.beginPath();
  43304. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  43305. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  43306. VirtualJoystick.vjCanvasContext.stroke();
  43307. VirtualJoystick.vjCanvasContext.closePath();
  43308. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  43309. }
  43310. else {
  43311. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  43312. VirtualJoystick.vjCanvasContext.beginPath();
  43313. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  43314. VirtualJoystick.vjCanvasContext.beginPath();
  43315. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  43316. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  43317. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  43318. VirtualJoystick.vjCanvasContext.stroke();
  43319. VirtualJoystick.vjCanvasContext.closePath();
  43320. touch.prevX = touch.x;
  43321. touch.prevY = touch.y;
  43322. }
  43323. ;
  43324. });
  43325. }
  43326. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  43327. };
  43328. VirtualJoystick.prototype.releaseCanvas = function () {
  43329. if (VirtualJoystick.vjCanvas) {
  43330. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  43331. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  43332. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  43333. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  43334. window.removeEventListener("resize", this._onResize);
  43335. document.body.removeChild(VirtualJoystick.vjCanvas);
  43336. VirtualJoystick.vjCanvas = null;
  43337. }
  43338. };
  43339. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  43340. VirtualJoystick._globalJoystickIndex = 0;
  43341. return VirtualJoystick;
  43342. }());
  43343. BABYLON.VirtualJoystick = VirtualJoystick;
  43344. })(BABYLON || (BABYLON = {}));
  43345. var BABYLON;
  43346. (function (BABYLON) {
  43347. // We're mainly based on the logic defined into the FreeCamera code
  43348. var VirtualJoysticksCamera = (function (_super) {
  43349. __extends(VirtualJoysticksCamera, _super);
  43350. function VirtualJoysticksCamera(name, position, scene) {
  43351. _super.call(this, name, position, scene);
  43352. this.inputs.addVirtualJoystick();
  43353. }
  43354. return VirtualJoysticksCamera;
  43355. }(BABYLON.FreeCamera));
  43356. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  43357. })(BABYLON || (BABYLON = {}));
  43358. var BABYLON;
  43359. (function (BABYLON) {
  43360. var FreeCameraVirtualJoystickInput = (function () {
  43361. function FreeCameraVirtualJoystickInput() {
  43362. }
  43363. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  43364. return this._leftjoystick;
  43365. };
  43366. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  43367. return this._rightjoystick;
  43368. };
  43369. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  43370. if (this._leftjoystick) {
  43371. var camera = this.camera;
  43372. var speed = camera._computeLocalCameraSpeed() * 50;
  43373. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  43374. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  43375. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  43376. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  43377. if (!this._leftjoystick.pressed) {
  43378. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  43379. }
  43380. if (!this._rightjoystick.pressed) {
  43381. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  43382. }
  43383. }
  43384. };
  43385. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  43386. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  43387. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  43388. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  43389. this._leftjoystick.setJoystickSensibility(0.15);
  43390. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  43391. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  43392. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  43393. this._rightjoystick.reverseUpDown = true;
  43394. this._rightjoystick.setJoystickSensibility(0.05);
  43395. this._rightjoystick.setJoystickColor("yellow");
  43396. };
  43397. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  43398. this._leftjoystick.releaseCanvas();
  43399. this._rightjoystick.releaseCanvas();
  43400. };
  43401. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  43402. return "FreeCameraVirtualJoystickInput";
  43403. };
  43404. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  43405. return "virtualJoystick";
  43406. };
  43407. return FreeCameraVirtualJoystickInput;
  43408. }());
  43409. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  43410. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  43411. })(BABYLON || (BABYLON = {}));
  43412. var BABYLON;
  43413. (function (BABYLON) {
  43414. var AnaglyphPostProcess = (function (_super) {
  43415. __extends(AnaglyphPostProcess, _super);
  43416. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  43417. var _this = this;
  43418. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  43419. this._passedProcess = rigCameras[0]._rigPostProcess;
  43420. this.onApplyObservable.add(function (effect) {
  43421. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  43422. });
  43423. }
  43424. return AnaglyphPostProcess;
  43425. }(BABYLON.PostProcess));
  43426. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  43427. })(BABYLON || (BABYLON = {}));
  43428. var BABYLON;
  43429. (function (BABYLON) {
  43430. var OutlineRenderer = (function () {
  43431. function OutlineRenderer(scene) {
  43432. this._scene = scene;
  43433. }
  43434. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  43435. var _this = this;
  43436. if (useOverlay === void 0) { useOverlay = false; }
  43437. var scene = this._scene;
  43438. var engine = this._scene.getEngine();
  43439. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  43440. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  43441. return;
  43442. }
  43443. var mesh = subMesh.getRenderingMesh();
  43444. var material = subMesh.getMaterial();
  43445. engine.enableEffect(this._effect);
  43446. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  43447. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  43448. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  43449. // Bones
  43450. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43451. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  43452. }
  43453. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  43454. // Alpha test
  43455. if (material && material.needAlphaTesting()) {
  43456. var alphaTexture = material.getAlphaTestTexture();
  43457. this._effect.setTexture("diffuseSampler", alphaTexture);
  43458. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  43459. }
  43460. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  43461. };
  43462. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  43463. var defines = [];
  43464. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  43465. var mesh = subMesh.getMesh();
  43466. var material = subMesh.getMaterial();
  43467. // Alpha test
  43468. if (material && material.needAlphaTesting()) {
  43469. defines.push("#define ALPHATEST");
  43470. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43471. attribs.push(BABYLON.VertexBuffer.UVKind);
  43472. defines.push("#define UV1");
  43473. }
  43474. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  43475. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43476. defines.push("#define UV2");
  43477. }
  43478. }
  43479. // Bones
  43480. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43481. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43482. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43483. if (mesh.numBoneInfluencers > 4) {
  43484. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43485. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43486. }
  43487. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  43488. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  43489. }
  43490. else {
  43491. defines.push("#define NUM_BONE_INFLUENCERS 0");
  43492. }
  43493. // Instances
  43494. if (useInstances) {
  43495. defines.push("#define INSTANCES");
  43496. attribs.push("world0");
  43497. attribs.push("world1");
  43498. attribs.push("world2");
  43499. attribs.push("world3");
  43500. }
  43501. // Get correct effect
  43502. var join = defines.join("\n");
  43503. if (this._cachedDefines !== join) {
  43504. this._cachedDefines = join;
  43505. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  43506. }
  43507. return this._effect.isReady();
  43508. };
  43509. return OutlineRenderer;
  43510. }());
  43511. BABYLON.OutlineRenderer = OutlineRenderer;
  43512. })(BABYLON || (BABYLON = {}));
  43513. var BABYLON;
  43514. (function (BABYLON) {
  43515. var MeshAssetTask = (function () {
  43516. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  43517. this.name = name;
  43518. this.meshesNames = meshesNames;
  43519. this.rootUrl = rootUrl;
  43520. this.sceneFilename = sceneFilename;
  43521. this.isCompleted = false;
  43522. }
  43523. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43524. var _this = this;
  43525. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  43526. _this.loadedMeshes = meshes;
  43527. _this.loadedParticleSystems = particleSystems;
  43528. _this.loadedSkeletons = skeletons;
  43529. _this.isCompleted = true;
  43530. if (_this.onSuccess) {
  43531. _this.onSuccess(_this);
  43532. }
  43533. onSuccess();
  43534. }, null, function () {
  43535. if (_this.onError) {
  43536. _this.onError(_this);
  43537. }
  43538. onError();
  43539. });
  43540. };
  43541. return MeshAssetTask;
  43542. }());
  43543. BABYLON.MeshAssetTask = MeshAssetTask;
  43544. var TextFileAssetTask = (function () {
  43545. function TextFileAssetTask(name, url) {
  43546. this.name = name;
  43547. this.url = url;
  43548. this.isCompleted = false;
  43549. }
  43550. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43551. var _this = this;
  43552. BABYLON.Tools.LoadFile(this.url, function (data) {
  43553. _this.text = data;
  43554. _this.isCompleted = true;
  43555. if (_this.onSuccess) {
  43556. _this.onSuccess(_this);
  43557. }
  43558. onSuccess();
  43559. }, null, scene.database, false, function () {
  43560. if (_this.onError) {
  43561. _this.onError(_this);
  43562. }
  43563. onError();
  43564. });
  43565. };
  43566. return TextFileAssetTask;
  43567. }());
  43568. BABYLON.TextFileAssetTask = TextFileAssetTask;
  43569. var BinaryFileAssetTask = (function () {
  43570. function BinaryFileAssetTask(name, url) {
  43571. this.name = name;
  43572. this.url = url;
  43573. this.isCompleted = false;
  43574. }
  43575. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43576. var _this = this;
  43577. BABYLON.Tools.LoadFile(this.url, function (data) {
  43578. _this.data = data;
  43579. _this.isCompleted = true;
  43580. if (_this.onSuccess) {
  43581. _this.onSuccess(_this);
  43582. }
  43583. onSuccess();
  43584. }, null, scene.database, true, function () {
  43585. if (_this.onError) {
  43586. _this.onError(_this);
  43587. }
  43588. onError();
  43589. });
  43590. };
  43591. return BinaryFileAssetTask;
  43592. }());
  43593. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  43594. var ImageAssetTask = (function () {
  43595. function ImageAssetTask(name, url) {
  43596. this.name = name;
  43597. this.url = url;
  43598. this.isCompleted = false;
  43599. }
  43600. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43601. var _this = this;
  43602. var img = new Image();
  43603. BABYLON.Tools.SetCorsBehavior(this.url, img);
  43604. img.onload = function () {
  43605. _this.image = img;
  43606. _this.isCompleted = true;
  43607. if (_this.onSuccess) {
  43608. _this.onSuccess(_this);
  43609. }
  43610. onSuccess();
  43611. };
  43612. img.onerror = function () {
  43613. if (_this.onError) {
  43614. _this.onError(_this);
  43615. }
  43616. onError();
  43617. };
  43618. img.src = this.url;
  43619. };
  43620. return ImageAssetTask;
  43621. }());
  43622. BABYLON.ImageAssetTask = ImageAssetTask;
  43623. var TextureAssetTask = (function () {
  43624. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  43625. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43626. this.name = name;
  43627. this.url = url;
  43628. this.noMipmap = noMipmap;
  43629. this.invertY = invertY;
  43630. this.samplingMode = samplingMode;
  43631. this.isCompleted = false;
  43632. }
  43633. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43634. var _this = this;
  43635. var onload = function () {
  43636. _this.isCompleted = true;
  43637. if (_this.onSuccess) {
  43638. _this.onSuccess(_this);
  43639. }
  43640. onSuccess();
  43641. };
  43642. var onerror = function () {
  43643. if (_this.onError) {
  43644. _this.onError(_this);
  43645. }
  43646. onError();
  43647. };
  43648. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  43649. };
  43650. return TextureAssetTask;
  43651. }());
  43652. BABYLON.TextureAssetTask = TextureAssetTask;
  43653. var CubeTextureAssetTask = (function () {
  43654. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  43655. this.name = name;
  43656. this.url = url;
  43657. this.extensions = extensions;
  43658. this.noMipmap = noMipmap;
  43659. this.files = files;
  43660. this.isCompleted = false;
  43661. }
  43662. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43663. var _this = this;
  43664. var onload = function () {
  43665. _this.isCompleted = true;
  43666. if (_this.onSuccess) {
  43667. _this.onSuccess(_this);
  43668. }
  43669. onSuccess();
  43670. };
  43671. var onerror = function () {
  43672. if (_this.onError) {
  43673. _this.onError(_this);
  43674. }
  43675. onError();
  43676. };
  43677. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  43678. };
  43679. return CubeTextureAssetTask;
  43680. }());
  43681. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  43682. var AssetsManager = (function () {
  43683. function AssetsManager(scene) {
  43684. this.tasks = new Array();
  43685. this.waitingTasksCount = 0;
  43686. this.useDefaultLoadingScreen = true;
  43687. this._scene = scene;
  43688. }
  43689. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  43690. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  43691. this.tasks.push(task);
  43692. return task;
  43693. };
  43694. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  43695. var task = new TextFileAssetTask(taskName, url);
  43696. this.tasks.push(task);
  43697. return task;
  43698. };
  43699. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  43700. var task = new BinaryFileAssetTask(taskName, url);
  43701. this.tasks.push(task);
  43702. return task;
  43703. };
  43704. AssetsManager.prototype.addImageTask = function (taskName, url) {
  43705. var task = new ImageAssetTask(taskName, url);
  43706. this.tasks.push(task);
  43707. return task;
  43708. };
  43709. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  43710. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43711. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  43712. this.tasks.push(task);
  43713. return task;
  43714. };
  43715. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  43716. this.waitingTasksCount--;
  43717. if (this.waitingTasksCount === 0) {
  43718. if (this.onFinish) {
  43719. this.onFinish(this.tasks);
  43720. }
  43721. this._scene.getEngine().hideLoadingUI();
  43722. }
  43723. };
  43724. AssetsManager.prototype._runTask = function (task) {
  43725. var _this = this;
  43726. task.run(this._scene, function () {
  43727. if (_this.onTaskSuccess) {
  43728. _this.onTaskSuccess(task);
  43729. }
  43730. _this._decreaseWaitingTasksCount();
  43731. }, function () {
  43732. if (_this.onTaskError) {
  43733. _this.onTaskError(task);
  43734. }
  43735. _this._decreaseWaitingTasksCount();
  43736. });
  43737. };
  43738. AssetsManager.prototype.reset = function () {
  43739. this.tasks = new Array();
  43740. return this;
  43741. };
  43742. AssetsManager.prototype.load = function () {
  43743. this.waitingTasksCount = this.tasks.length;
  43744. if (this.waitingTasksCount === 0) {
  43745. if (this.onFinish) {
  43746. this.onFinish(this.tasks);
  43747. }
  43748. return this;
  43749. }
  43750. if (this.useDefaultLoadingScreen) {
  43751. this._scene.getEngine().displayLoadingUI();
  43752. }
  43753. for (var index = 0; index < this.tasks.length; index++) {
  43754. var task = this.tasks[index];
  43755. this._runTask(task);
  43756. }
  43757. return this;
  43758. };
  43759. return AssetsManager;
  43760. }());
  43761. BABYLON.AssetsManager = AssetsManager;
  43762. })(BABYLON || (BABYLON = {}));
  43763. var BABYLON;
  43764. (function (BABYLON) {
  43765. var VRCameraMetrics = (function () {
  43766. function VRCameraMetrics() {
  43767. this.compensateDistortion = true;
  43768. }
  43769. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  43770. get: function () {
  43771. return this.hResolution / (2 * this.vResolution);
  43772. },
  43773. enumerable: true,
  43774. configurable: true
  43775. });
  43776. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  43777. get: function () {
  43778. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  43779. },
  43780. enumerable: true,
  43781. configurable: true
  43782. });
  43783. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  43784. get: function () {
  43785. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  43786. var h = (4 * meters) / this.hScreenSize;
  43787. return BABYLON.Matrix.Translation(h, 0, 0);
  43788. },
  43789. enumerable: true,
  43790. configurable: true
  43791. });
  43792. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  43793. get: function () {
  43794. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  43795. var h = (4 * meters) / this.hScreenSize;
  43796. return BABYLON.Matrix.Translation(-h, 0, 0);
  43797. },
  43798. enumerable: true,
  43799. configurable: true
  43800. });
  43801. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  43802. get: function () {
  43803. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  43804. },
  43805. enumerable: true,
  43806. configurable: true
  43807. });
  43808. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  43809. get: function () {
  43810. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  43811. },
  43812. enumerable: true,
  43813. configurable: true
  43814. });
  43815. VRCameraMetrics.GetDefault = function () {
  43816. var result = new VRCameraMetrics();
  43817. result.hResolution = 1280;
  43818. result.vResolution = 800;
  43819. result.hScreenSize = 0.149759993;
  43820. result.vScreenSize = 0.0935999975;
  43821. result.vScreenCenter = 0.0467999987,
  43822. result.eyeToScreenDistance = 0.0410000011;
  43823. result.lensSeparationDistance = 0.0635000020;
  43824. result.interpupillaryDistance = 0.0640000030;
  43825. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  43826. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  43827. result.postProcessScaleFactor = 1.714605507808412;
  43828. result.lensCenterOffset = 0.151976421;
  43829. return result;
  43830. };
  43831. return VRCameraMetrics;
  43832. }());
  43833. BABYLON.VRCameraMetrics = VRCameraMetrics;
  43834. })(BABYLON || (BABYLON = {}));
  43835. var BABYLON;
  43836. (function (BABYLON) {
  43837. var WebVRFreeCamera = (function (_super) {
  43838. __extends(WebVRFreeCamera, _super);
  43839. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  43840. var _this = this;
  43841. if (compensateDistortion === void 0) { compensateDistortion = false; }
  43842. if (webVROptions === void 0) { webVROptions = {}; }
  43843. _super.call(this, name, position, scene);
  43844. this.webVROptions = webVROptions;
  43845. this._vrDevice = null;
  43846. this._cacheState = null;
  43847. this._vrEnabled = false;
  43848. this._attached = false;
  43849. //enable VR
  43850. this.getEngine().initWebVR();
  43851. if (!this.getEngine().vrDisplaysPromise) {
  43852. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  43853. }
  43854. else {
  43855. //TODO get the metrics updated using the device's eye parameters!
  43856. //TODO also check that the device has the right capabilities!
  43857. this._frameData = new VRFrameData();
  43858. this.getEngine().vrDisplaysPromise.then(function (devices) {
  43859. if (devices.length > 0) {
  43860. _this._vrEnabled = true;
  43861. if (_this.webVROptions.displayName) {
  43862. var found = devices.some(function (device) {
  43863. if (device.displayName === _this.webVROptions.displayName) {
  43864. _this._vrDevice = device;
  43865. return true;
  43866. }
  43867. else {
  43868. return false;
  43869. }
  43870. });
  43871. if (!found) {
  43872. _this._vrDevice = devices[0];
  43873. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  43874. }
  43875. }
  43876. else {
  43877. //choose the first one
  43878. _this._vrDevice = devices[0];
  43879. }
  43880. //reset the rig parameters.
  43881. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice, frameData: _this._frameData });
  43882. if (_this._attached) {
  43883. _this.getEngine().enableVR(_this._vrDevice);
  43884. }
  43885. }
  43886. else {
  43887. BABYLON.Tools.Error("No WebVR devices found!");
  43888. }
  43889. });
  43890. }
  43891. this.rotationQuaternion = new BABYLON.Quaternion();
  43892. this._quaternionCache = new BABYLON.Quaternion();
  43893. }
  43894. WebVRFreeCamera.prototype._checkInputs = function () {
  43895. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  43896. var currentPost = this._frameData.pose;
  43897. //make sure we have data
  43898. if (currentPost && currentPost.orientation) {
  43899. this._cacheState = currentPost;
  43900. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], -this._cacheState.orientation[2], -this._cacheState.orientation[3]);
  43901. if (this.webVROptions.trackPosition && this._cacheState.position) {
  43902. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  43903. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  43904. }
  43905. }
  43906. }
  43907. _super.prototype._checkInputs.call(this);
  43908. };
  43909. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43910. _super.prototype.attachControl.call(this, element, noPreventDefault);
  43911. this._attached = true;
  43912. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43913. if (this._vrEnabled) {
  43914. this.getEngine().enableVR(this._vrDevice);
  43915. }
  43916. };
  43917. WebVRFreeCamera.prototype.detachControl = function (element) {
  43918. _super.prototype.detachControl.call(this, element);
  43919. this._vrEnabled = false;
  43920. this._attached = false;
  43921. this.getEngine().disableVR();
  43922. };
  43923. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  43924. //Backwards comp.
  43925. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  43926. //this.getEngine().switchFullscreen(requestPointerlock);
  43927. };
  43928. WebVRFreeCamera.prototype.getTypeName = function () {
  43929. return "WebVRFreeCamera";
  43930. };
  43931. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  43932. //uses the vrDisplay's "resetPose()".
  43933. //pitch and roll won't be affected.
  43934. this._vrDevice.resetPose();
  43935. };
  43936. return WebVRFreeCamera;
  43937. }(BABYLON.FreeCamera));
  43938. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  43939. })(BABYLON || (BABYLON = {}));
  43940. var BABYLON;
  43941. (function (BABYLON) {
  43942. // Standard optimizations
  43943. var SceneOptimization = (function () {
  43944. function SceneOptimization(priority) {
  43945. if (priority === void 0) { priority = 0; }
  43946. this.priority = priority;
  43947. this.apply = function (scene) {
  43948. return true; // Return true if everything that can be done was applied
  43949. };
  43950. }
  43951. return SceneOptimization;
  43952. }());
  43953. BABYLON.SceneOptimization = SceneOptimization;
  43954. var TextureOptimization = (function (_super) {
  43955. __extends(TextureOptimization, _super);
  43956. function TextureOptimization(priority, maximumSize) {
  43957. var _this = this;
  43958. if (priority === void 0) { priority = 0; }
  43959. if (maximumSize === void 0) { maximumSize = 1024; }
  43960. _super.call(this, priority);
  43961. this.priority = priority;
  43962. this.maximumSize = maximumSize;
  43963. this.apply = function (scene) {
  43964. var allDone = true;
  43965. for (var index = 0; index < scene.textures.length; index++) {
  43966. var texture = scene.textures[index];
  43967. if (!texture.canRescale) {
  43968. continue;
  43969. }
  43970. var currentSize = texture.getSize();
  43971. var maxDimension = Math.max(currentSize.width, currentSize.height);
  43972. if (maxDimension > _this.maximumSize) {
  43973. texture.scale(0.5);
  43974. allDone = false;
  43975. }
  43976. }
  43977. return allDone;
  43978. };
  43979. }
  43980. return TextureOptimization;
  43981. }(SceneOptimization));
  43982. BABYLON.TextureOptimization = TextureOptimization;
  43983. var HardwareScalingOptimization = (function (_super) {
  43984. __extends(HardwareScalingOptimization, _super);
  43985. function HardwareScalingOptimization(priority, maximumScale) {
  43986. var _this = this;
  43987. if (priority === void 0) { priority = 0; }
  43988. if (maximumScale === void 0) { maximumScale = 2; }
  43989. _super.call(this, priority);
  43990. this.priority = priority;
  43991. this.maximumScale = maximumScale;
  43992. this._currentScale = 1;
  43993. this.apply = function (scene) {
  43994. _this._currentScale++;
  43995. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  43996. return _this._currentScale >= _this.maximumScale;
  43997. };
  43998. }
  43999. return HardwareScalingOptimization;
  44000. }(SceneOptimization));
  44001. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  44002. var ShadowsOptimization = (function (_super) {
  44003. __extends(ShadowsOptimization, _super);
  44004. function ShadowsOptimization() {
  44005. _super.apply(this, arguments);
  44006. this.apply = function (scene) {
  44007. scene.shadowsEnabled = false;
  44008. return true;
  44009. };
  44010. }
  44011. return ShadowsOptimization;
  44012. }(SceneOptimization));
  44013. BABYLON.ShadowsOptimization = ShadowsOptimization;
  44014. var PostProcessesOptimization = (function (_super) {
  44015. __extends(PostProcessesOptimization, _super);
  44016. function PostProcessesOptimization() {
  44017. _super.apply(this, arguments);
  44018. this.apply = function (scene) {
  44019. scene.postProcessesEnabled = false;
  44020. return true;
  44021. };
  44022. }
  44023. return PostProcessesOptimization;
  44024. }(SceneOptimization));
  44025. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  44026. var LensFlaresOptimization = (function (_super) {
  44027. __extends(LensFlaresOptimization, _super);
  44028. function LensFlaresOptimization() {
  44029. _super.apply(this, arguments);
  44030. this.apply = function (scene) {
  44031. scene.lensFlaresEnabled = false;
  44032. return true;
  44033. };
  44034. }
  44035. return LensFlaresOptimization;
  44036. }(SceneOptimization));
  44037. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  44038. var ParticlesOptimization = (function (_super) {
  44039. __extends(ParticlesOptimization, _super);
  44040. function ParticlesOptimization() {
  44041. _super.apply(this, arguments);
  44042. this.apply = function (scene) {
  44043. scene.particlesEnabled = false;
  44044. return true;
  44045. };
  44046. }
  44047. return ParticlesOptimization;
  44048. }(SceneOptimization));
  44049. BABYLON.ParticlesOptimization = ParticlesOptimization;
  44050. var RenderTargetsOptimization = (function (_super) {
  44051. __extends(RenderTargetsOptimization, _super);
  44052. function RenderTargetsOptimization() {
  44053. _super.apply(this, arguments);
  44054. this.apply = function (scene) {
  44055. scene.renderTargetsEnabled = false;
  44056. return true;
  44057. };
  44058. }
  44059. return RenderTargetsOptimization;
  44060. }(SceneOptimization));
  44061. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  44062. var MergeMeshesOptimization = (function (_super) {
  44063. __extends(MergeMeshesOptimization, _super);
  44064. function MergeMeshesOptimization() {
  44065. var _this = this;
  44066. _super.apply(this, arguments);
  44067. this._canBeMerged = function (abstractMesh) {
  44068. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  44069. return false;
  44070. }
  44071. var mesh = abstractMesh;
  44072. if (!mesh.isVisible || !mesh.isEnabled()) {
  44073. return false;
  44074. }
  44075. if (mesh.instances.length > 0) {
  44076. return false;
  44077. }
  44078. if (mesh.skeleton || mesh.hasLODLevels) {
  44079. return false;
  44080. }
  44081. if (mesh.parent) {
  44082. return false;
  44083. }
  44084. return true;
  44085. };
  44086. this.apply = function (scene, updateSelectionTree) {
  44087. var globalPool = scene.meshes.slice(0);
  44088. var globalLength = globalPool.length;
  44089. for (var index = 0; index < globalLength; index++) {
  44090. var currentPool = new Array();
  44091. var current = globalPool[index];
  44092. // Checks
  44093. if (!_this._canBeMerged(current)) {
  44094. continue;
  44095. }
  44096. currentPool.push(current);
  44097. // Find compatible meshes
  44098. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  44099. var otherMesh = globalPool[subIndex];
  44100. if (!_this._canBeMerged(otherMesh)) {
  44101. continue;
  44102. }
  44103. if (otherMesh.material !== current.material) {
  44104. continue;
  44105. }
  44106. if (otherMesh.checkCollisions !== current.checkCollisions) {
  44107. continue;
  44108. }
  44109. currentPool.push(otherMesh);
  44110. globalLength--;
  44111. globalPool.splice(subIndex, 1);
  44112. subIndex--;
  44113. }
  44114. if (currentPool.length < 2) {
  44115. continue;
  44116. }
  44117. // Merge meshes
  44118. BABYLON.Mesh.MergeMeshes(currentPool);
  44119. }
  44120. if (updateSelectionTree != undefined) {
  44121. if (updateSelectionTree) {
  44122. scene.createOrUpdateSelectionOctree();
  44123. }
  44124. }
  44125. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  44126. scene.createOrUpdateSelectionOctree();
  44127. }
  44128. return true;
  44129. };
  44130. }
  44131. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  44132. get: function () {
  44133. return MergeMeshesOptimization._UpdateSelectionTree;
  44134. },
  44135. set: function (value) {
  44136. MergeMeshesOptimization._UpdateSelectionTree = value;
  44137. },
  44138. enumerable: true,
  44139. configurable: true
  44140. });
  44141. MergeMeshesOptimization._UpdateSelectionTree = false;
  44142. return MergeMeshesOptimization;
  44143. }(SceneOptimization));
  44144. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  44145. // Options
  44146. var SceneOptimizerOptions = (function () {
  44147. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  44148. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  44149. if (trackerDuration === void 0) { trackerDuration = 2000; }
  44150. this.targetFrameRate = targetFrameRate;
  44151. this.trackerDuration = trackerDuration;
  44152. this.optimizations = new Array();
  44153. }
  44154. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  44155. var result = new SceneOptimizerOptions(targetFrameRate);
  44156. var priority = 0;
  44157. result.optimizations.push(new MergeMeshesOptimization(priority));
  44158. result.optimizations.push(new ShadowsOptimization(priority));
  44159. result.optimizations.push(new LensFlaresOptimization(priority));
  44160. // Next priority
  44161. priority++;
  44162. result.optimizations.push(new PostProcessesOptimization(priority));
  44163. result.optimizations.push(new ParticlesOptimization(priority));
  44164. // Next priority
  44165. priority++;
  44166. result.optimizations.push(new TextureOptimization(priority, 1024));
  44167. return result;
  44168. };
  44169. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  44170. var result = new SceneOptimizerOptions(targetFrameRate);
  44171. var priority = 0;
  44172. result.optimizations.push(new MergeMeshesOptimization(priority));
  44173. result.optimizations.push(new ShadowsOptimization(priority));
  44174. result.optimizations.push(new LensFlaresOptimization(priority));
  44175. // Next priority
  44176. priority++;
  44177. result.optimizations.push(new PostProcessesOptimization(priority));
  44178. result.optimizations.push(new ParticlesOptimization(priority));
  44179. // Next priority
  44180. priority++;
  44181. result.optimizations.push(new TextureOptimization(priority, 512));
  44182. // Next priority
  44183. priority++;
  44184. result.optimizations.push(new RenderTargetsOptimization(priority));
  44185. // Next priority
  44186. priority++;
  44187. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  44188. return result;
  44189. };
  44190. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  44191. var result = new SceneOptimizerOptions(targetFrameRate);
  44192. var priority = 0;
  44193. result.optimizations.push(new MergeMeshesOptimization(priority));
  44194. result.optimizations.push(new ShadowsOptimization(priority));
  44195. result.optimizations.push(new LensFlaresOptimization(priority));
  44196. // Next priority
  44197. priority++;
  44198. result.optimizations.push(new PostProcessesOptimization(priority));
  44199. result.optimizations.push(new ParticlesOptimization(priority));
  44200. // Next priority
  44201. priority++;
  44202. result.optimizations.push(new TextureOptimization(priority, 256));
  44203. // Next priority
  44204. priority++;
  44205. result.optimizations.push(new RenderTargetsOptimization(priority));
  44206. // Next priority
  44207. priority++;
  44208. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  44209. return result;
  44210. };
  44211. return SceneOptimizerOptions;
  44212. }());
  44213. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  44214. // Scene optimizer tool
  44215. var SceneOptimizer = (function () {
  44216. function SceneOptimizer() {
  44217. }
  44218. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  44219. // TODO: add an epsilon
  44220. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  44221. if (onSuccess) {
  44222. onSuccess();
  44223. }
  44224. return;
  44225. }
  44226. // Apply current level of optimizations
  44227. var allDone = true;
  44228. var noOptimizationApplied = true;
  44229. for (var index = 0; index < options.optimizations.length; index++) {
  44230. var optimization = options.optimizations[index];
  44231. if (optimization.priority === currentPriorityLevel) {
  44232. noOptimizationApplied = false;
  44233. allDone = allDone && optimization.apply(scene);
  44234. }
  44235. }
  44236. // If no optimization was applied, this is a failure :(
  44237. if (noOptimizationApplied) {
  44238. if (onFailure) {
  44239. onFailure();
  44240. }
  44241. return;
  44242. }
  44243. // If all optimizations were done, move to next level
  44244. if (allDone) {
  44245. currentPriorityLevel++;
  44246. }
  44247. // Let's the system running for a specific amount of time before checking FPS
  44248. scene.executeWhenReady(function () {
  44249. setTimeout(function () {
  44250. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  44251. }, options.trackerDuration);
  44252. });
  44253. };
  44254. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  44255. if (!options) {
  44256. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  44257. }
  44258. // Let's the system running for a specific amount of time before checking FPS
  44259. scene.executeWhenReady(function () {
  44260. setTimeout(function () {
  44261. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  44262. }, options.trackerDuration);
  44263. });
  44264. };
  44265. return SceneOptimizer;
  44266. }());
  44267. BABYLON.SceneOptimizer = SceneOptimizer;
  44268. })(BABYLON || (BABYLON = {}));
  44269. var BABYLON;
  44270. (function (BABYLON) {
  44271. var Internals;
  44272. (function (Internals) {
  44273. var MeshLODLevel = (function () {
  44274. function MeshLODLevel(distance, mesh) {
  44275. this.distance = distance;
  44276. this.mesh = mesh;
  44277. }
  44278. return MeshLODLevel;
  44279. }());
  44280. Internals.MeshLODLevel = MeshLODLevel;
  44281. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  44282. })(BABYLON || (BABYLON = {}));
  44283. var BABYLON;
  44284. (function (BABYLON) {
  44285. var RawTexture = (function (_super) {
  44286. __extends(RawTexture, _super);
  44287. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  44288. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44289. if (invertY === void 0) { invertY = false; }
  44290. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44291. _super.call(this, null, scene, !generateMipMaps, invertY);
  44292. this.format = format;
  44293. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  44294. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44295. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44296. }
  44297. RawTexture.prototype.update = function (data) {
  44298. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  44299. };
  44300. // Statics
  44301. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44302. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44303. if (invertY === void 0) { invertY = false; }
  44304. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44305. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  44306. };
  44307. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44308. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44309. if (invertY === void 0) { invertY = false; }
  44310. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44311. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  44312. };
  44313. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44314. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44315. if (invertY === void 0) { invertY = false; }
  44316. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44317. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  44318. };
  44319. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44320. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44321. if (invertY === void 0) { invertY = false; }
  44322. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44323. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  44324. };
  44325. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44326. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44327. if (invertY === void 0) { invertY = false; }
  44328. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44329. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  44330. };
  44331. return RawTexture;
  44332. }(BABYLON.Texture));
  44333. BABYLON.RawTexture = RawTexture;
  44334. })(BABYLON || (BABYLON = {}));
  44335. var BABYLON;
  44336. (function (BABYLON) {
  44337. var IndexedVector2 = (function (_super) {
  44338. __extends(IndexedVector2, _super);
  44339. function IndexedVector2(original, index) {
  44340. _super.call(this, original.x, original.y);
  44341. this.index = index;
  44342. }
  44343. return IndexedVector2;
  44344. }(BABYLON.Vector2));
  44345. var PolygonPoints = (function () {
  44346. function PolygonPoints() {
  44347. this.elements = new Array();
  44348. }
  44349. PolygonPoints.prototype.add = function (originalPoints) {
  44350. var _this = this;
  44351. var result = new Array();
  44352. originalPoints.forEach(function (point) {
  44353. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  44354. var newPoint = new IndexedVector2(point, _this.elements.length);
  44355. result.push(newPoint);
  44356. _this.elements.push(newPoint);
  44357. }
  44358. });
  44359. return result;
  44360. };
  44361. PolygonPoints.prototype.computeBounds = function () {
  44362. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  44363. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  44364. this.elements.forEach(function (point) {
  44365. // x
  44366. if (point.x < lmin.x) {
  44367. lmin.x = point.x;
  44368. }
  44369. else if (point.x > lmax.x) {
  44370. lmax.x = point.x;
  44371. }
  44372. // y
  44373. if (point.y < lmin.y) {
  44374. lmin.y = point.y;
  44375. }
  44376. else if (point.y > lmax.y) {
  44377. lmax.y = point.y;
  44378. }
  44379. });
  44380. return {
  44381. min: lmin,
  44382. max: lmax,
  44383. width: lmax.x - lmin.x,
  44384. height: lmax.y - lmin.y
  44385. };
  44386. };
  44387. return PolygonPoints;
  44388. }());
  44389. var Polygon = (function () {
  44390. function Polygon() {
  44391. }
  44392. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  44393. return [
  44394. new BABYLON.Vector2(xmin, ymin),
  44395. new BABYLON.Vector2(xmax, ymin),
  44396. new BABYLON.Vector2(xmax, ymax),
  44397. new BABYLON.Vector2(xmin, ymax)
  44398. ];
  44399. };
  44400. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  44401. if (cx === void 0) { cx = 0; }
  44402. if (cy === void 0) { cy = 0; }
  44403. if (numberOfSides === void 0) { numberOfSides = 32; }
  44404. var result = new Array();
  44405. var angle = 0;
  44406. var increment = (Math.PI * 2) / numberOfSides;
  44407. for (var i = 0; i < numberOfSides; i++) {
  44408. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  44409. angle -= increment;
  44410. }
  44411. return result;
  44412. };
  44413. Polygon.Parse = function (input) {
  44414. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  44415. var i, result = [];
  44416. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  44417. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  44418. }
  44419. return result;
  44420. };
  44421. Polygon.StartingAt = function (x, y) {
  44422. return BABYLON.Path2.StartingAt(x, y);
  44423. };
  44424. return Polygon;
  44425. }());
  44426. BABYLON.Polygon = Polygon;
  44427. var PolygonMeshBuilder = (function () {
  44428. function PolygonMeshBuilder(name, contours, scene) {
  44429. this._points = new PolygonPoints();
  44430. this._outlinepoints = new PolygonPoints();
  44431. this._holes = [];
  44432. this._epoints = new Array();
  44433. this._eholes = new Array();
  44434. this._name = name;
  44435. this._scene = scene;
  44436. var points;
  44437. if (contours instanceof BABYLON.Path2) {
  44438. points = contours.getPoints();
  44439. }
  44440. else {
  44441. points = contours;
  44442. }
  44443. this._addToepoint(points);
  44444. this._points.add(points);
  44445. this._outlinepoints.add(points);
  44446. }
  44447. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  44448. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  44449. var p = points_1[_i];
  44450. this._epoints.push(p.x, p.y);
  44451. }
  44452. };
  44453. PolygonMeshBuilder.prototype.addHole = function (hole) {
  44454. this._points.add(hole);
  44455. var holepoints = new PolygonPoints();
  44456. holepoints.add(hole);
  44457. this._holes.push(holepoints);
  44458. this._eholes.push(this._epoints.length / 2);
  44459. this._addToepoint(hole);
  44460. return this;
  44461. };
  44462. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  44463. var _this = this;
  44464. if (updatable === void 0) { updatable = false; }
  44465. var result = new BABYLON.Mesh(this._name, this._scene);
  44466. var normals = [];
  44467. var positions = [];
  44468. var uvs = [];
  44469. var bounds = this._points.computeBounds();
  44470. this._points.elements.forEach(function (p) {
  44471. normals.push(0, 1.0, 0);
  44472. positions.push(p.x, 0, p.y);
  44473. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  44474. });
  44475. var indices = [];
  44476. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  44477. for (var i = 0; i < res.length; i++) {
  44478. indices.push(res[i]);
  44479. }
  44480. if (depth > 0) {
  44481. var positionscount = (positions.length / 3); //get the current pointcount
  44482. this._points.elements.forEach(function (p) {
  44483. normals.push(0, -1.0, 0);
  44484. positions.push(p.x, -depth, p.y);
  44485. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  44486. });
  44487. var totalCount = indices.length;
  44488. for (var i = 0; i < totalCount; i += 3) {
  44489. var i0 = indices[i + 0];
  44490. var i1 = indices[i + 1];
  44491. var i2 = indices[i + 2];
  44492. indices.push(i2 + positionscount);
  44493. indices.push(i1 + positionscount);
  44494. indices.push(i0 + positionscount);
  44495. }
  44496. //Add the sides
  44497. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  44498. this._holes.forEach(function (hole) {
  44499. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  44500. });
  44501. }
  44502. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  44503. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  44504. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  44505. result.setIndices(indices);
  44506. return result;
  44507. };
  44508. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  44509. var StartIndex = positions.length / 3;
  44510. var ulength = 0;
  44511. for (var i = 0; i < points.elements.length; i++) {
  44512. var p = points.elements[i];
  44513. var p1;
  44514. if ((i + 1) > points.elements.length - 1) {
  44515. p1 = points.elements[0];
  44516. }
  44517. else {
  44518. p1 = points.elements[i + 1];
  44519. }
  44520. positions.push(p.x, 0, p.y);
  44521. positions.push(p.x, -depth, p.y);
  44522. positions.push(p1.x, 0, p1.y);
  44523. positions.push(p1.x, -depth, p1.y);
  44524. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  44525. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  44526. var v3 = v2.subtract(v1);
  44527. var v4 = new BABYLON.Vector3(0, 1, 0);
  44528. var vn = BABYLON.Vector3.Cross(v3, v4);
  44529. vn = vn.normalize();
  44530. uvs.push(ulength / bounds.width, 0);
  44531. uvs.push(ulength / bounds.width, 1);
  44532. ulength += v3.length();
  44533. uvs.push((ulength / bounds.width), 0);
  44534. uvs.push((ulength / bounds.width), 1);
  44535. if (!flip) {
  44536. normals.push(-vn.x, -vn.y, -vn.z);
  44537. normals.push(-vn.x, -vn.y, -vn.z);
  44538. normals.push(-vn.x, -vn.y, -vn.z);
  44539. normals.push(-vn.x, -vn.y, -vn.z);
  44540. indices.push(StartIndex);
  44541. indices.push(StartIndex + 1);
  44542. indices.push(StartIndex + 2);
  44543. indices.push(StartIndex + 1);
  44544. indices.push(StartIndex + 3);
  44545. indices.push(StartIndex + 2);
  44546. }
  44547. else {
  44548. normals.push(vn.x, vn.y, vn.z);
  44549. normals.push(vn.x, vn.y, vn.z);
  44550. normals.push(vn.x, vn.y, vn.z);
  44551. normals.push(vn.x, vn.y, vn.z);
  44552. indices.push(StartIndex);
  44553. indices.push(StartIndex + 2);
  44554. indices.push(StartIndex + 1);
  44555. indices.push(StartIndex + 1);
  44556. indices.push(StartIndex + 2);
  44557. indices.push(StartIndex + 3);
  44558. }
  44559. StartIndex += 4;
  44560. }
  44561. ;
  44562. };
  44563. return PolygonMeshBuilder;
  44564. }());
  44565. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  44566. })(BABYLON || (BABYLON = {}));
  44567. var BABYLON;
  44568. (function (BABYLON) {
  44569. var Octree = (function () {
  44570. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  44571. if (maxDepth === void 0) { maxDepth = 2; }
  44572. this.maxDepth = maxDepth;
  44573. this.dynamicContent = new Array();
  44574. this._maxBlockCapacity = maxBlockCapacity || 64;
  44575. this._selectionContent = new BABYLON.SmartArray(1024);
  44576. this._creationFunc = creationFunc;
  44577. }
  44578. // Methods
  44579. Octree.prototype.update = function (worldMin, worldMax, entries) {
  44580. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  44581. };
  44582. Octree.prototype.addMesh = function (entry) {
  44583. for (var index = 0; index < this.blocks.length; index++) {
  44584. var block = this.blocks[index];
  44585. block.addEntry(entry);
  44586. }
  44587. };
  44588. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  44589. this._selectionContent.reset();
  44590. for (var index = 0; index < this.blocks.length; index++) {
  44591. var block = this.blocks[index];
  44592. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  44593. }
  44594. if (allowDuplicate) {
  44595. this._selectionContent.concat(this.dynamicContent);
  44596. }
  44597. else {
  44598. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  44599. }
  44600. return this._selectionContent;
  44601. };
  44602. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  44603. this._selectionContent.reset();
  44604. for (var index = 0; index < this.blocks.length; index++) {
  44605. var block = this.blocks[index];
  44606. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  44607. }
  44608. if (allowDuplicate) {
  44609. this._selectionContent.concat(this.dynamicContent);
  44610. }
  44611. else {
  44612. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  44613. }
  44614. return this._selectionContent;
  44615. };
  44616. Octree.prototype.intersectsRay = function (ray) {
  44617. this._selectionContent.reset();
  44618. for (var index = 0; index < this.blocks.length; index++) {
  44619. var block = this.blocks[index];
  44620. block.intersectsRay(ray, this._selectionContent);
  44621. }
  44622. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  44623. return this._selectionContent;
  44624. };
  44625. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  44626. target.blocks = new Array();
  44627. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  44628. // Segmenting space
  44629. for (var x = 0; x < 2; x++) {
  44630. for (var y = 0; y < 2; y++) {
  44631. for (var z = 0; z < 2; z++) {
  44632. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  44633. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  44634. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  44635. block.addEntries(entries);
  44636. target.blocks.push(block);
  44637. }
  44638. }
  44639. }
  44640. };
  44641. Octree.CreationFuncForMeshes = function (entry, block) {
  44642. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  44643. block.entries.push(entry);
  44644. }
  44645. };
  44646. Octree.CreationFuncForSubMeshes = function (entry, block) {
  44647. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  44648. block.entries.push(entry);
  44649. }
  44650. };
  44651. return Octree;
  44652. }());
  44653. BABYLON.Octree = Octree;
  44654. })(BABYLON || (BABYLON = {}));
  44655. var BABYLON;
  44656. (function (BABYLON) {
  44657. var OctreeBlock = (function () {
  44658. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  44659. this.entries = new Array();
  44660. this._boundingVectors = new Array();
  44661. this._capacity = capacity;
  44662. this._depth = depth;
  44663. this._maxDepth = maxDepth;
  44664. this._creationFunc = creationFunc;
  44665. this._minPoint = minPoint;
  44666. this._maxPoint = maxPoint;
  44667. this._boundingVectors.push(minPoint.clone());
  44668. this._boundingVectors.push(maxPoint.clone());
  44669. this._boundingVectors.push(minPoint.clone());
  44670. this._boundingVectors[2].x = maxPoint.x;
  44671. this._boundingVectors.push(minPoint.clone());
  44672. this._boundingVectors[3].y = maxPoint.y;
  44673. this._boundingVectors.push(minPoint.clone());
  44674. this._boundingVectors[4].z = maxPoint.z;
  44675. this._boundingVectors.push(maxPoint.clone());
  44676. this._boundingVectors[5].z = minPoint.z;
  44677. this._boundingVectors.push(maxPoint.clone());
  44678. this._boundingVectors[6].x = minPoint.x;
  44679. this._boundingVectors.push(maxPoint.clone());
  44680. this._boundingVectors[7].y = minPoint.y;
  44681. }
  44682. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  44683. // Property
  44684. get: function () {
  44685. return this._capacity;
  44686. },
  44687. enumerable: true,
  44688. configurable: true
  44689. });
  44690. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  44691. get: function () {
  44692. return this._minPoint;
  44693. },
  44694. enumerable: true,
  44695. configurable: true
  44696. });
  44697. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  44698. get: function () {
  44699. return this._maxPoint;
  44700. },
  44701. enumerable: true,
  44702. configurable: true
  44703. });
  44704. // Methods
  44705. OctreeBlock.prototype.addEntry = function (entry) {
  44706. if (this.blocks) {
  44707. for (var index = 0; index < this.blocks.length; index++) {
  44708. var block = this.blocks[index];
  44709. block.addEntry(entry);
  44710. }
  44711. return;
  44712. }
  44713. this._creationFunc(entry, this);
  44714. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  44715. this.createInnerBlocks();
  44716. }
  44717. };
  44718. OctreeBlock.prototype.addEntries = function (entries) {
  44719. for (var index = 0; index < entries.length; index++) {
  44720. var mesh = entries[index];
  44721. this.addEntry(mesh);
  44722. }
  44723. };
  44724. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  44725. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  44726. if (this.blocks) {
  44727. for (var index = 0; index < this.blocks.length; index++) {
  44728. var block = this.blocks[index];
  44729. block.select(frustumPlanes, selection, allowDuplicate);
  44730. }
  44731. return;
  44732. }
  44733. if (allowDuplicate) {
  44734. selection.concat(this.entries);
  44735. }
  44736. else {
  44737. selection.concatWithNoDuplicate(this.entries);
  44738. }
  44739. }
  44740. };
  44741. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  44742. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  44743. if (this.blocks) {
  44744. for (var index = 0; index < this.blocks.length; index++) {
  44745. var block = this.blocks[index];
  44746. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  44747. }
  44748. return;
  44749. }
  44750. if (allowDuplicate) {
  44751. selection.concat(this.entries);
  44752. }
  44753. else {
  44754. selection.concatWithNoDuplicate(this.entries);
  44755. }
  44756. }
  44757. };
  44758. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  44759. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  44760. if (this.blocks) {
  44761. for (var index = 0; index < this.blocks.length; index++) {
  44762. var block = this.blocks[index];
  44763. block.intersectsRay(ray, selection);
  44764. }
  44765. return;
  44766. }
  44767. selection.concatWithNoDuplicate(this.entries);
  44768. }
  44769. };
  44770. OctreeBlock.prototype.createInnerBlocks = function () {
  44771. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  44772. };
  44773. return OctreeBlock;
  44774. }());
  44775. BABYLON.OctreeBlock = OctreeBlock;
  44776. })(BABYLON || (BABYLON = {}));
  44777. var BABYLON;
  44778. (function (BABYLON) {
  44779. var BlurPostProcess = (function (_super) {
  44780. __extends(BlurPostProcess, _super);
  44781. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  44782. var _this = this;
  44783. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  44784. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  44785. this.direction = direction;
  44786. this.blurWidth = blurWidth;
  44787. this.onApplyObservable.add(function (effect) {
  44788. effect.setFloat2("screenSize", _this.width, _this.height);
  44789. effect.setVector2("direction", _this.direction);
  44790. effect.setFloat("blurWidth", _this.blurWidth);
  44791. });
  44792. }
  44793. return BlurPostProcess;
  44794. }(BABYLON.PostProcess));
  44795. BABYLON.BlurPostProcess = BlurPostProcess;
  44796. })(BABYLON || (BABYLON = {}));
  44797. var BABYLON;
  44798. (function (BABYLON) {
  44799. var RefractionPostProcess = (function (_super) {
  44800. __extends(RefractionPostProcess, _super);
  44801. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  44802. var _this = this;
  44803. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  44804. this.color = color;
  44805. this.depth = depth;
  44806. this.colorLevel = colorLevel;
  44807. this.onActivateObservable.add(function (cam) {
  44808. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  44809. });
  44810. this.onApplyObservable.add(function (effect) {
  44811. effect.setColor3("baseColor", _this.color);
  44812. effect.setFloat("depth", _this.depth);
  44813. effect.setFloat("colorLevel", _this.colorLevel);
  44814. effect.setTexture("refractionSampler", _this._refRexture);
  44815. });
  44816. }
  44817. // Methods
  44818. RefractionPostProcess.prototype.dispose = function (camera) {
  44819. if (this._refRexture) {
  44820. this._refRexture.dispose();
  44821. }
  44822. _super.prototype.dispose.call(this, camera);
  44823. };
  44824. return RefractionPostProcess;
  44825. }(BABYLON.PostProcess));
  44826. BABYLON.RefractionPostProcess = RefractionPostProcess;
  44827. })(BABYLON || (BABYLON = {}));
  44828. var BABYLON;
  44829. (function (BABYLON) {
  44830. var BlackAndWhitePostProcess = (function (_super) {
  44831. __extends(BlackAndWhitePostProcess, _super);
  44832. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  44833. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  44834. }
  44835. return BlackAndWhitePostProcess;
  44836. }(BABYLON.PostProcess));
  44837. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  44838. })(BABYLON || (BABYLON = {}));
  44839. var BABYLON;
  44840. (function (BABYLON) {
  44841. var ConvolutionPostProcess = (function (_super) {
  44842. __extends(ConvolutionPostProcess, _super);
  44843. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  44844. var _this = this;
  44845. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  44846. this.kernel = kernel;
  44847. this.onApply = function (effect) {
  44848. effect.setFloat2("screenSize", _this.width, _this.height);
  44849. effect.setArray("kernel", _this.kernel);
  44850. };
  44851. }
  44852. // Statics
  44853. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  44854. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  44855. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  44856. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  44857. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  44858. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  44859. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  44860. return ConvolutionPostProcess;
  44861. }(BABYLON.PostProcess));
  44862. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  44863. })(BABYLON || (BABYLON = {}));
  44864. var BABYLON;
  44865. (function (BABYLON) {
  44866. var FilterPostProcess = (function (_super) {
  44867. __extends(FilterPostProcess, _super);
  44868. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  44869. var _this = this;
  44870. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  44871. this.kernelMatrix = kernelMatrix;
  44872. this.onApply = function (effect) {
  44873. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  44874. };
  44875. }
  44876. return FilterPostProcess;
  44877. }(BABYLON.PostProcess));
  44878. BABYLON.FilterPostProcess = FilterPostProcess;
  44879. })(BABYLON || (BABYLON = {}));
  44880. var BABYLON;
  44881. (function (BABYLON) {
  44882. var FxaaPostProcess = (function (_super) {
  44883. __extends(FxaaPostProcess, _super);
  44884. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  44885. var _this = this;
  44886. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  44887. this.onSizeChangedObservable.add(function () {
  44888. _this.texelWidth = 1.0 / _this.width;
  44889. _this.texelHeight = 1.0 / _this.height;
  44890. });
  44891. this.onApplyObservable.add(function (effect) {
  44892. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  44893. });
  44894. }
  44895. return FxaaPostProcess;
  44896. }(BABYLON.PostProcess));
  44897. BABYLON.FxaaPostProcess = FxaaPostProcess;
  44898. })(BABYLON || (BABYLON = {}));
  44899. var BABYLON;
  44900. (function (BABYLON) {
  44901. var StereoscopicInterlacePostProcess = (function (_super) {
  44902. __extends(StereoscopicInterlacePostProcess, _super);
  44903. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  44904. var _this = this;
  44905. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  44906. this._passedProcess = rigCameras[0]._rigPostProcess;
  44907. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  44908. this.onSizeChangedObservable.add(function () {
  44909. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  44910. });
  44911. this.onApplyObservable.add(function (effect) {
  44912. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  44913. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  44914. });
  44915. }
  44916. return StereoscopicInterlacePostProcess;
  44917. }(BABYLON.PostProcess));
  44918. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  44919. })(BABYLON || (BABYLON = {}));
  44920. var BABYLON;
  44921. (function (BABYLON) {
  44922. var LensFlare = (function () {
  44923. function LensFlare(size, position, color, imgUrl, system) {
  44924. this.size = size;
  44925. this.position = position;
  44926. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  44927. this.dispose = function () {
  44928. if (this.texture) {
  44929. this.texture.dispose();
  44930. }
  44931. // Remove from scene
  44932. var index = this._system.lensFlares.indexOf(this);
  44933. this._system.lensFlares.splice(index, 1);
  44934. };
  44935. this.color = color || new BABYLON.Color3(1, 1, 1);
  44936. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  44937. this._system = system;
  44938. system.lensFlares.push(this);
  44939. }
  44940. return LensFlare;
  44941. }());
  44942. BABYLON.LensFlare = LensFlare;
  44943. })(BABYLON || (BABYLON = {}));
  44944. var BABYLON;
  44945. (function (BABYLON) {
  44946. var LensFlareSystem = (function () {
  44947. function LensFlareSystem(name, emitter, scene) {
  44948. this.name = name;
  44949. this.lensFlares = new Array();
  44950. this.borderLimit = 300;
  44951. this.viewportBorder = 0;
  44952. this.layerMask = 0x0FFFFFFF;
  44953. this._vertexBuffers = {};
  44954. this._isEnabled = true;
  44955. this._scene = scene;
  44956. this._emitter = emitter;
  44957. this.id = name;
  44958. scene.lensFlareSystems.push(this);
  44959. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  44960. var engine = scene.getEngine();
  44961. // VBO
  44962. var vertices = [];
  44963. vertices.push(1, 1);
  44964. vertices.push(-1, 1);
  44965. vertices.push(-1, -1);
  44966. vertices.push(1, -1);
  44967. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  44968. // Indices
  44969. var indices = [];
  44970. indices.push(0);
  44971. indices.push(1);
  44972. indices.push(2);
  44973. indices.push(0);
  44974. indices.push(2);
  44975. indices.push(3);
  44976. this._indexBuffer = engine.createIndexBuffer(indices);
  44977. // Effects
  44978. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  44979. }
  44980. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  44981. get: function () {
  44982. return this._isEnabled;
  44983. },
  44984. set: function (value) {
  44985. this._isEnabled = value;
  44986. },
  44987. enumerable: true,
  44988. configurable: true
  44989. });
  44990. LensFlareSystem.prototype.getScene = function () {
  44991. return this._scene;
  44992. };
  44993. LensFlareSystem.prototype.getEmitter = function () {
  44994. return this._emitter;
  44995. };
  44996. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  44997. this._emitter = newEmitter;
  44998. };
  44999. LensFlareSystem.prototype.getEmitterPosition = function () {
  45000. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  45001. };
  45002. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  45003. var position = this.getEmitterPosition();
  45004. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  45005. this._positionX = position.x;
  45006. this._positionY = position.y;
  45007. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  45008. if (this.viewportBorder > 0) {
  45009. globalViewport.x -= this.viewportBorder;
  45010. globalViewport.y -= this.viewportBorder;
  45011. globalViewport.width += this.viewportBorder * 2;
  45012. globalViewport.height += this.viewportBorder * 2;
  45013. position.x += this.viewportBorder;
  45014. position.y += this.viewportBorder;
  45015. this._positionX += this.viewportBorder;
  45016. this._positionY += this.viewportBorder;
  45017. }
  45018. if (position.z > 0) {
  45019. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  45020. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  45021. return true;
  45022. }
  45023. return true;
  45024. }
  45025. return false;
  45026. };
  45027. LensFlareSystem.prototype._isVisible = function () {
  45028. if (!this._isEnabled) {
  45029. return false;
  45030. }
  45031. var emitterPosition = this.getEmitterPosition();
  45032. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  45033. var distance = direction.length();
  45034. direction.normalize();
  45035. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  45036. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  45037. return !pickInfo.hit || pickInfo.distance > distance;
  45038. };
  45039. LensFlareSystem.prototype.render = function () {
  45040. if (!this._effect.isReady())
  45041. return false;
  45042. var engine = this._scene.getEngine();
  45043. var viewport = this._scene.activeCamera.viewport;
  45044. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  45045. // Position
  45046. if (!this.computeEffectivePosition(globalViewport)) {
  45047. return false;
  45048. }
  45049. // Visibility
  45050. if (!this._isVisible()) {
  45051. return false;
  45052. }
  45053. // Intensity
  45054. var awayX;
  45055. var awayY;
  45056. if (this._positionX < this.borderLimit + globalViewport.x) {
  45057. awayX = this.borderLimit + globalViewport.x - this._positionX;
  45058. }
  45059. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  45060. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  45061. }
  45062. else {
  45063. awayX = 0;
  45064. }
  45065. if (this._positionY < this.borderLimit + globalViewport.y) {
  45066. awayY = this.borderLimit + globalViewport.y - this._positionY;
  45067. }
  45068. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  45069. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  45070. }
  45071. else {
  45072. awayY = 0;
  45073. }
  45074. var away = (awayX > awayY) ? awayX : awayY;
  45075. away -= this.viewportBorder;
  45076. if (away > this.borderLimit) {
  45077. away = this.borderLimit;
  45078. }
  45079. var intensity = 1.0 - (away / this.borderLimit);
  45080. if (intensity < 0) {
  45081. return false;
  45082. }
  45083. if (intensity > 1.0) {
  45084. intensity = 1.0;
  45085. }
  45086. if (this.viewportBorder > 0) {
  45087. globalViewport.x += this.viewportBorder;
  45088. globalViewport.y += this.viewportBorder;
  45089. globalViewport.width -= this.viewportBorder * 2;
  45090. globalViewport.height -= this.viewportBorder * 2;
  45091. this._positionX -= this.viewportBorder;
  45092. this._positionY -= this.viewportBorder;
  45093. }
  45094. // Position
  45095. var centerX = globalViewport.x + globalViewport.width / 2;
  45096. var centerY = globalViewport.y + globalViewport.height / 2;
  45097. var distX = centerX - this._positionX;
  45098. var distY = centerY - this._positionY;
  45099. // Effects
  45100. engine.enableEffect(this._effect);
  45101. engine.setState(false);
  45102. engine.setDepthBuffer(false);
  45103. // VBOs
  45104. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  45105. // Flares
  45106. for (var index = 0; index < this.lensFlares.length; index++) {
  45107. var flare = this.lensFlares[index];
  45108. engine.setAlphaMode(flare.alphaMode);
  45109. var x = centerX - (distX * flare.position);
  45110. var y = centerY - (distY * flare.position);
  45111. var cw = flare.size;
  45112. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  45113. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  45114. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  45115. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  45116. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  45117. // Texture
  45118. this._effect.setTexture("textureSampler", flare.texture);
  45119. // Color
  45120. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  45121. // Draw order
  45122. engine.draw(true, 0, 6);
  45123. }
  45124. engine.setDepthBuffer(true);
  45125. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  45126. return true;
  45127. };
  45128. LensFlareSystem.prototype.dispose = function () {
  45129. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  45130. if (vertexBuffer) {
  45131. vertexBuffer.dispose();
  45132. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  45133. }
  45134. if (this._indexBuffer) {
  45135. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  45136. this._indexBuffer = null;
  45137. }
  45138. while (this.lensFlares.length) {
  45139. this.lensFlares[0].dispose();
  45140. }
  45141. // Remove from scene
  45142. var index = this._scene.lensFlareSystems.indexOf(this);
  45143. this._scene.lensFlareSystems.splice(index, 1);
  45144. };
  45145. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  45146. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  45147. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  45148. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  45149. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  45150. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  45151. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  45152. var parsedFlare = parsedLensFlareSystem.flares[index];
  45153. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  45154. }
  45155. return lensFlareSystem;
  45156. };
  45157. LensFlareSystem.prototype.serialize = function () {
  45158. var serializationObject = {};
  45159. serializationObject.id = this.id;
  45160. serializationObject.name = this.name;
  45161. serializationObject.emitterId = this.getEmitter().id;
  45162. serializationObject.borderLimit = this.borderLimit;
  45163. serializationObject.flares = [];
  45164. for (var index = 0; index < this.lensFlares.length; index++) {
  45165. var flare = this.lensFlares[index];
  45166. serializationObject.flares.push({
  45167. size: flare.size,
  45168. position: flare.position,
  45169. color: flare.color.asArray(),
  45170. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  45171. });
  45172. }
  45173. return serializationObject;
  45174. };
  45175. return LensFlareSystem;
  45176. }());
  45177. BABYLON.LensFlareSystem = LensFlareSystem;
  45178. })(BABYLON || (BABYLON = {}));
  45179. var BABYLON;
  45180. (function (BABYLON) {
  45181. // We're mainly based on the logic defined into the FreeCamera code
  45182. var DeviceOrientationCamera = (function (_super) {
  45183. __extends(DeviceOrientationCamera, _super);
  45184. function DeviceOrientationCamera(name, position, scene) {
  45185. _super.call(this, name, position, scene);
  45186. this._quaternionCache = new BABYLON.Quaternion();
  45187. this.inputs.addDeviceOrientation();
  45188. }
  45189. DeviceOrientationCamera.prototype.getTypeName = function () {
  45190. return "DeviceOrientationCamera";
  45191. };
  45192. DeviceOrientationCamera.prototype._checkInputs = function () {
  45193. _super.prototype._checkInputs.call(this);
  45194. this._quaternionCache.copyFrom(this.rotationQuaternion);
  45195. if (this._initialQuaternion) {
  45196. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  45197. }
  45198. };
  45199. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  45200. var _this = this;
  45201. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  45202. //can only work if this camera has a rotation quaternion already.
  45203. if (!this.rotationQuaternion)
  45204. return;
  45205. if (!this._initialQuaternion) {
  45206. this._initialQuaternion = new BABYLON.Quaternion();
  45207. }
  45208. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  45209. ['x', 'y', 'z'].forEach(function (axisName) {
  45210. if (!axis[axisName]) {
  45211. _this._initialQuaternion[axisName] = 0;
  45212. }
  45213. else {
  45214. _this._initialQuaternion[axisName] *= -1;
  45215. }
  45216. });
  45217. this._initialQuaternion.normalize();
  45218. //force rotation update
  45219. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  45220. };
  45221. return DeviceOrientationCamera;
  45222. }(BABYLON.FreeCamera));
  45223. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  45224. })(BABYLON || (BABYLON = {}));
  45225. var BABYLON;
  45226. (function (BABYLON) {
  45227. var VRDeviceOrientationFreeCamera = (function (_super) {
  45228. __extends(VRDeviceOrientationFreeCamera, _super);
  45229. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  45230. if (compensateDistortion === void 0) { compensateDistortion = true; }
  45231. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  45232. _super.call(this, name, position, scene);
  45233. vrCameraMetrics.compensateDistortion = compensateDistortion;
  45234. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  45235. }
  45236. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  45237. return "VRDeviceOrientationFreeCamera";
  45238. };
  45239. return VRDeviceOrientationFreeCamera;
  45240. }(BABYLON.DeviceOrientationCamera));
  45241. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  45242. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  45243. __extends(VRDeviceOrientationArcRotateCamera, _super);
  45244. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  45245. if (compensateDistortion === void 0) { compensateDistortion = true; }
  45246. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  45247. _super.call(this, name, alpha, beta, radius, target, scene);
  45248. vrCameraMetrics.compensateDistortion = compensateDistortion;
  45249. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  45250. this.inputs.addVRDeviceOrientation();
  45251. }
  45252. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  45253. return "VRDeviceOrientationArcRotateCamera";
  45254. };
  45255. return VRDeviceOrientationArcRotateCamera;
  45256. }(BABYLON.ArcRotateCamera));
  45257. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  45258. })(BABYLON || (BABYLON = {}));
  45259. var BABYLON;
  45260. (function (BABYLON) {
  45261. // We're mainly based on the logic defined into the FreeCamera code
  45262. var UniversalCamera = (function (_super) {
  45263. __extends(UniversalCamera, _super);
  45264. //-- end properties for backward compatibility for inputs
  45265. function UniversalCamera(name, position, scene) {
  45266. _super.call(this, name, position, scene);
  45267. this.inputs.addGamepad();
  45268. }
  45269. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  45270. //-- Begin properties for backward compatibility for inputs
  45271. get: function () {
  45272. var gamepad = this.inputs.attached["gamepad"];
  45273. if (gamepad)
  45274. return gamepad.gamepadAngularSensibility;
  45275. },
  45276. set: function (value) {
  45277. var gamepad = this.inputs.attached["gamepad"];
  45278. if (gamepad)
  45279. gamepad.gamepadAngularSensibility = value;
  45280. },
  45281. enumerable: true,
  45282. configurable: true
  45283. });
  45284. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  45285. get: function () {
  45286. var gamepad = this.inputs.attached["gamepad"];
  45287. if (gamepad)
  45288. return gamepad.gamepadMoveSensibility;
  45289. },
  45290. set: function (value) {
  45291. var gamepad = this.inputs.attached["gamepad"];
  45292. if (gamepad)
  45293. gamepad.gamepadMoveSensibility = value;
  45294. },
  45295. enumerable: true,
  45296. configurable: true
  45297. });
  45298. UniversalCamera.prototype.getTypeName = function () {
  45299. return "UniversalCamera";
  45300. };
  45301. return UniversalCamera;
  45302. }(BABYLON.TouchCamera));
  45303. BABYLON.UniversalCamera = UniversalCamera;
  45304. })(BABYLON || (BABYLON = {}));
  45305. var BABYLON;
  45306. (function (BABYLON) {
  45307. var Gamepads = (function () {
  45308. function Gamepads(ongamedpadconnected) {
  45309. var _this = this;
  45310. this.babylonGamepads = [];
  45311. this.oneGamepadConnected = false;
  45312. this.isMonitoring = false;
  45313. this.gamepadEventSupported = 'GamepadEvent' in window;
  45314. this.gamepadSupportAvailable = (navigator.getGamepads ||
  45315. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  45316. this._callbackGamepadConnected = ongamedpadconnected;
  45317. if (this.gamepadSupportAvailable) {
  45318. // Checking if the gamepad connected event is supported (like in Firefox)
  45319. if (this.gamepadEventSupported) {
  45320. this._onGamepadConnectedEvent = function (evt) {
  45321. _this._onGamepadConnected(evt);
  45322. };
  45323. this._onGamepadDisonnectedEvent = function (evt) {
  45324. _this._onGamepadDisconnected(evt);
  45325. };
  45326. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  45327. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  45328. }
  45329. else {
  45330. this._startMonitoringGamepads();
  45331. }
  45332. }
  45333. }
  45334. Gamepads.prototype.dispose = function () {
  45335. if (Gamepads.gamepadDOMInfo) {
  45336. document.body.removeChild(Gamepads.gamepadDOMInfo);
  45337. }
  45338. if (this._onGamepadConnectedEvent) {
  45339. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  45340. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  45341. this._onGamepadConnectedEvent = null;
  45342. this._onGamepadDisonnectedEvent = null;
  45343. }
  45344. };
  45345. Gamepads.prototype._onGamepadConnected = function (evt) {
  45346. var newGamepad = this._addNewGamepad(evt.gamepad);
  45347. if (this._callbackGamepadConnected)
  45348. this._callbackGamepadConnected(newGamepad);
  45349. this._startMonitoringGamepads();
  45350. };
  45351. Gamepads.prototype._addNewGamepad = function (gamepad) {
  45352. if (!this.oneGamepadConnected) {
  45353. this.oneGamepadConnected = true;
  45354. if (Gamepads.gamepadDOMInfo) {
  45355. document.body.removeChild(Gamepads.gamepadDOMInfo);
  45356. Gamepads.gamepadDOMInfo = null;
  45357. }
  45358. }
  45359. var newGamepad;
  45360. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  45361. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  45362. }
  45363. else {
  45364. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  45365. }
  45366. this.babylonGamepads.push(newGamepad);
  45367. return newGamepad;
  45368. };
  45369. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  45370. // Remove the gamepad from the list of gamepads to monitor.
  45371. for (var i in this.babylonGamepads) {
  45372. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  45373. this.babylonGamepads.splice(+i, 1);
  45374. break;
  45375. }
  45376. }
  45377. // If no gamepads are left, stop the polling loop.
  45378. if (this.babylonGamepads.length == 0) {
  45379. this._stopMonitoringGamepads();
  45380. }
  45381. };
  45382. Gamepads.prototype._startMonitoringGamepads = function () {
  45383. if (!this.isMonitoring) {
  45384. this.isMonitoring = true;
  45385. this._checkGamepadsStatus();
  45386. }
  45387. };
  45388. Gamepads.prototype._stopMonitoringGamepads = function () {
  45389. this.isMonitoring = false;
  45390. };
  45391. Gamepads.prototype._checkGamepadsStatus = function () {
  45392. var _this = this;
  45393. // updating gamepad objects
  45394. this._updateGamepadObjects();
  45395. for (var i in this.babylonGamepads) {
  45396. this.babylonGamepads[i].update();
  45397. }
  45398. if (this.isMonitoring) {
  45399. if (window.requestAnimationFrame) {
  45400. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45401. }
  45402. else if (window.mozRequestAnimationFrame) {
  45403. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45404. }
  45405. else if (window.webkitRequestAnimationFrame) {
  45406. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45407. }
  45408. }
  45409. };
  45410. // This function is called only on Chrome, which does not yet support
  45411. // connection/disconnection events, but requires you to monitor
  45412. // an array for changes.
  45413. Gamepads.prototype._updateGamepadObjects = function () {
  45414. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  45415. for (var i = 0; i < gamepads.length; i++) {
  45416. if (gamepads[i]) {
  45417. if (!(gamepads[i].index in this.babylonGamepads)) {
  45418. var newGamepad = this._addNewGamepad(gamepads[i]);
  45419. if (this._callbackGamepadConnected) {
  45420. this._callbackGamepadConnected(newGamepad);
  45421. }
  45422. }
  45423. else {
  45424. this.babylonGamepads[i].browserGamepad = gamepads[i];
  45425. }
  45426. }
  45427. }
  45428. };
  45429. return Gamepads;
  45430. }());
  45431. BABYLON.Gamepads = Gamepads;
  45432. var StickValues = (function () {
  45433. function StickValues(x, y) {
  45434. this.x = x;
  45435. this.y = y;
  45436. }
  45437. return StickValues;
  45438. }());
  45439. BABYLON.StickValues = StickValues;
  45440. var Gamepad = (function () {
  45441. function Gamepad(id, index, browserGamepad) {
  45442. this.id = id;
  45443. this.index = index;
  45444. this.browserGamepad = browserGamepad;
  45445. if (this.browserGamepad.axes.length >= 2) {
  45446. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  45447. }
  45448. if (this.browserGamepad.axes.length >= 4) {
  45449. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  45450. }
  45451. }
  45452. Gamepad.prototype.onleftstickchanged = function (callback) {
  45453. this._onleftstickchanged = callback;
  45454. };
  45455. Gamepad.prototype.onrightstickchanged = function (callback) {
  45456. this._onrightstickchanged = callback;
  45457. };
  45458. Object.defineProperty(Gamepad.prototype, "leftStick", {
  45459. get: function () {
  45460. return this._leftStick;
  45461. },
  45462. set: function (newValues) {
  45463. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  45464. this._onleftstickchanged(newValues);
  45465. }
  45466. this._leftStick = newValues;
  45467. },
  45468. enumerable: true,
  45469. configurable: true
  45470. });
  45471. Object.defineProperty(Gamepad.prototype, "rightStick", {
  45472. get: function () {
  45473. return this._rightStick;
  45474. },
  45475. set: function (newValues) {
  45476. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  45477. this._onrightstickchanged(newValues);
  45478. }
  45479. this._rightStick = newValues;
  45480. },
  45481. enumerable: true,
  45482. configurable: true
  45483. });
  45484. Gamepad.prototype.update = function () {
  45485. if (this._leftStick) {
  45486. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  45487. }
  45488. if (this._rightStick) {
  45489. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  45490. }
  45491. };
  45492. return Gamepad;
  45493. }());
  45494. BABYLON.Gamepad = Gamepad;
  45495. var GenericPad = (function (_super) {
  45496. __extends(GenericPad, _super);
  45497. function GenericPad(id, index, gamepad) {
  45498. _super.call(this, id, index, gamepad);
  45499. this.id = id;
  45500. this.index = index;
  45501. this.gamepad = gamepad;
  45502. this._buttons = new Array(gamepad.buttons.length);
  45503. }
  45504. GenericPad.prototype.onbuttondown = function (callback) {
  45505. this._onbuttondown = callback;
  45506. };
  45507. GenericPad.prototype.onbuttonup = function (callback) {
  45508. this._onbuttonup = callback;
  45509. };
  45510. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  45511. if (newValue !== currentValue) {
  45512. if (this._onbuttondown && newValue === 1) {
  45513. this._onbuttondown(buttonIndex);
  45514. }
  45515. if (this._onbuttonup && newValue === 0) {
  45516. this._onbuttonup(buttonIndex);
  45517. }
  45518. }
  45519. return newValue;
  45520. };
  45521. GenericPad.prototype.update = function () {
  45522. _super.prototype.update.call(this);
  45523. for (var index = 0; index < this._buttons.length; index++) {
  45524. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  45525. }
  45526. };
  45527. return GenericPad;
  45528. }(Gamepad));
  45529. BABYLON.GenericPad = GenericPad;
  45530. (function (Xbox360Button) {
  45531. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  45532. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  45533. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  45534. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  45535. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  45536. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  45537. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  45538. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  45539. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  45540. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  45541. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  45542. var Xbox360Button = BABYLON.Xbox360Button;
  45543. (function (Xbox360Dpad) {
  45544. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  45545. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  45546. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  45547. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  45548. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  45549. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  45550. var Xbox360Pad = (function (_super) {
  45551. __extends(Xbox360Pad, _super);
  45552. function Xbox360Pad() {
  45553. _super.apply(this, arguments);
  45554. this._leftTrigger = 0;
  45555. this._rightTrigger = 0;
  45556. this._buttonA = 0;
  45557. this._buttonB = 0;
  45558. this._buttonX = 0;
  45559. this._buttonY = 0;
  45560. this._buttonBack = 0;
  45561. this._buttonStart = 0;
  45562. this._buttonLB = 0;
  45563. this._buttonRB = 0;
  45564. this._buttonLeftStick = 0;
  45565. this._buttonRightStick = 0;
  45566. this._dPadUp = 0;
  45567. this._dPadDown = 0;
  45568. this._dPadLeft = 0;
  45569. this._dPadRight = 0;
  45570. }
  45571. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  45572. this._onlefttriggerchanged = callback;
  45573. };
  45574. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  45575. this._onrighttriggerchanged = callback;
  45576. };
  45577. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  45578. get: function () {
  45579. return this._leftTrigger;
  45580. },
  45581. set: function (newValue) {
  45582. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  45583. this._onlefttriggerchanged(newValue);
  45584. }
  45585. this._leftTrigger = newValue;
  45586. },
  45587. enumerable: true,
  45588. configurable: true
  45589. });
  45590. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  45591. get: function () {
  45592. return this._rightTrigger;
  45593. },
  45594. set: function (newValue) {
  45595. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  45596. this._onrighttriggerchanged(newValue);
  45597. }
  45598. this._rightTrigger = newValue;
  45599. },
  45600. enumerable: true,
  45601. configurable: true
  45602. });
  45603. Xbox360Pad.prototype.onbuttondown = function (callback) {
  45604. this._onbuttondown = callback;
  45605. };
  45606. Xbox360Pad.prototype.onbuttonup = function (callback) {
  45607. this._onbuttonup = callback;
  45608. };
  45609. Xbox360Pad.prototype.ondpaddown = function (callback) {
  45610. this._ondpaddown = callback;
  45611. };
  45612. Xbox360Pad.prototype.ondpadup = function (callback) {
  45613. this._ondpadup = callback;
  45614. };
  45615. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  45616. if (newValue !== currentValue) {
  45617. if (this._onbuttondown && newValue === 1) {
  45618. this._onbuttondown(buttonType);
  45619. }
  45620. if (this._onbuttonup && newValue === 0) {
  45621. this._onbuttonup(buttonType);
  45622. }
  45623. }
  45624. return newValue;
  45625. };
  45626. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  45627. if (newValue !== currentValue) {
  45628. if (this._ondpaddown && newValue === 1) {
  45629. this._ondpaddown(buttonType);
  45630. }
  45631. if (this._ondpadup && newValue === 0) {
  45632. this._ondpadup(buttonType);
  45633. }
  45634. }
  45635. return newValue;
  45636. };
  45637. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  45638. get: function () {
  45639. return this._buttonA;
  45640. },
  45641. set: function (value) {
  45642. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  45643. },
  45644. enumerable: true,
  45645. configurable: true
  45646. });
  45647. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  45648. get: function () {
  45649. return this._buttonB;
  45650. },
  45651. set: function (value) {
  45652. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  45653. },
  45654. enumerable: true,
  45655. configurable: true
  45656. });
  45657. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  45658. get: function () {
  45659. return this._buttonX;
  45660. },
  45661. set: function (value) {
  45662. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  45663. },
  45664. enumerable: true,
  45665. configurable: true
  45666. });
  45667. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  45668. get: function () {
  45669. return this._buttonY;
  45670. },
  45671. set: function (value) {
  45672. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  45673. },
  45674. enumerable: true,
  45675. configurable: true
  45676. });
  45677. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  45678. get: function () {
  45679. return this._buttonStart;
  45680. },
  45681. set: function (value) {
  45682. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  45683. },
  45684. enumerable: true,
  45685. configurable: true
  45686. });
  45687. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  45688. get: function () {
  45689. return this._buttonBack;
  45690. },
  45691. set: function (value) {
  45692. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  45693. },
  45694. enumerable: true,
  45695. configurable: true
  45696. });
  45697. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  45698. get: function () {
  45699. return this._buttonLB;
  45700. },
  45701. set: function (value) {
  45702. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  45703. },
  45704. enumerable: true,
  45705. configurable: true
  45706. });
  45707. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  45708. get: function () {
  45709. return this._buttonRB;
  45710. },
  45711. set: function (value) {
  45712. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  45713. },
  45714. enumerable: true,
  45715. configurable: true
  45716. });
  45717. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  45718. get: function () {
  45719. return this._buttonLeftStick;
  45720. },
  45721. set: function (value) {
  45722. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  45723. },
  45724. enumerable: true,
  45725. configurable: true
  45726. });
  45727. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  45728. get: function () {
  45729. return this._buttonRightStick;
  45730. },
  45731. set: function (value) {
  45732. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  45733. },
  45734. enumerable: true,
  45735. configurable: true
  45736. });
  45737. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  45738. get: function () {
  45739. return this._dPadUp;
  45740. },
  45741. set: function (value) {
  45742. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  45743. },
  45744. enumerable: true,
  45745. configurable: true
  45746. });
  45747. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  45748. get: function () {
  45749. return this._dPadDown;
  45750. },
  45751. set: function (value) {
  45752. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  45753. },
  45754. enumerable: true,
  45755. configurable: true
  45756. });
  45757. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  45758. get: function () {
  45759. return this._dPadLeft;
  45760. },
  45761. set: function (value) {
  45762. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  45763. },
  45764. enumerable: true,
  45765. configurable: true
  45766. });
  45767. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  45768. get: function () {
  45769. return this._dPadRight;
  45770. },
  45771. set: function (value) {
  45772. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  45773. },
  45774. enumerable: true,
  45775. configurable: true
  45776. });
  45777. Xbox360Pad.prototype.update = function () {
  45778. _super.prototype.update.call(this);
  45779. this.buttonA = this.browserGamepad.buttons[0].value;
  45780. this.buttonB = this.browserGamepad.buttons[1].value;
  45781. this.buttonX = this.browserGamepad.buttons[2].value;
  45782. this.buttonY = this.browserGamepad.buttons[3].value;
  45783. this.buttonLB = this.browserGamepad.buttons[4].value;
  45784. this.buttonRB = this.browserGamepad.buttons[5].value;
  45785. this.leftTrigger = this.browserGamepad.buttons[6].value;
  45786. this.rightTrigger = this.browserGamepad.buttons[7].value;
  45787. this.buttonBack = this.browserGamepad.buttons[8].value;
  45788. this.buttonStart = this.browserGamepad.buttons[9].value;
  45789. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  45790. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  45791. this.dPadUp = this.browserGamepad.buttons[12].value;
  45792. this.dPadDown = this.browserGamepad.buttons[13].value;
  45793. this.dPadLeft = this.browserGamepad.buttons[14].value;
  45794. this.dPadRight = this.browserGamepad.buttons[15].value;
  45795. };
  45796. return Xbox360Pad;
  45797. }(Gamepad));
  45798. BABYLON.Xbox360Pad = Xbox360Pad;
  45799. })(BABYLON || (BABYLON = {}));
  45800. var BABYLON;
  45801. (function (BABYLON) {
  45802. // We're mainly based on the logic defined into the FreeCamera code
  45803. var GamepadCamera = (function (_super) {
  45804. __extends(GamepadCamera, _super);
  45805. //-- end properties for backward compatibility for inputs
  45806. function GamepadCamera(name, position, scene) {
  45807. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  45808. _super.call(this, name, position, scene);
  45809. }
  45810. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  45811. //-- Begin properties for backward compatibility for inputs
  45812. get: function () {
  45813. var gamepad = this.inputs.attached["gamepad"];
  45814. if (gamepad)
  45815. return gamepad.gamepadAngularSensibility;
  45816. },
  45817. set: function (value) {
  45818. var gamepad = this.inputs.attached["gamepad"];
  45819. if (gamepad)
  45820. gamepad.gamepadAngularSensibility = value;
  45821. },
  45822. enumerable: true,
  45823. configurable: true
  45824. });
  45825. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  45826. get: function () {
  45827. var gamepad = this.inputs.attached["gamepad"];
  45828. if (gamepad)
  45829. return gamepad.gamepadMoveSensibility;
  45830. },
  45831. set: function (value) {
  45832. var gamepad = this.inputs.attached["gamepad"];
  45833. if (gamepad)
  45834. gamepad.gamepadMoveSensibility = value;
  45835. },
  45836. enumerable: true,
  45837. configurable: true
  45838. });
  45839. GamepadCamera.prototype.getTypeName = function () {
  45840. return "GamepadCamera";
  45841. };
  45842. return GamepadCamera;
  45843. }(BABYLON.UniversalCamera));
  45844. BABYLON.GamepadCamera = GamepadCamera;
  45845. })(BABYLON || (BABYLON = {}));
  45846. var BABYLON;
  45847. (function (BABYLON) {
  45848. var Analyser = (function () {
  45849. function Analyser(scene) {
  45850. this.SMOOTHING = 0.75;
  45851. this.FFT_SIZE = 512;
  45852. this.BARGRAPHAMPLITUDE = 256;
  45853. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  45854. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  45855. this._scene = scene;
  45856. this._audioEngine = BABYLON.Engine.audioEngine;
  45857. if (this._audioEngine.canUseWebAudio) {
  45858. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  45859. this._webAudioAnalyser.minDecibels = -140;
  45860. this._webAudioAnalyser.maxDecibels = 0;
  45861. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45862. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45863. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  45864. }
  45865. }
  45866. Analyser.prototype.getFrequencyBinCount = function () {
  45867. if (this._audioEngine.canUseWebAudio) {
  45868. return this._webAudioAnalyser.frequencyBinCount;
  45869. }
  45870. else {
  45871. return 0;
  45872. }
  45873. };
  45874. Analyser.prototype.getByteFrequencyData = function () {
  45875. if (this._audioEngine.canUseWebAudio) {
  45876. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45877. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45878. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  45879. }
  45880. return this._byteFreqs;
  45881. };
  45882. Analyser.prototype.getByteTimeDomainData = function () {
  45883. if (this._audioEngine.canUseWebAudio) {
  45884. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45885. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45886. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  45887. }
  45888. return this._byteTime;
  45889. };
  45890. Analyser.prototype.getFloatFrequencyData = function () {
  45891. if (this._audioEngine.canUseWebAudio) {
  45892. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45893. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45894. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  45895. }
  45896. return this._floatFreqs;
  45897. };
  45898. Analyser.prototype.drawDebugCanvas = function () {
  45899. var _this = this;
  45900. if (this._audioEngine.canUseWebAudio) {
  45901. if (!this._debugCanvas) {
  45902. this._debugCanvas = document.createElement("canvas");
  45903. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  45904. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  45905. this._debugCanvas.style.position = "absolute";
  45906. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  45907. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  45908. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  45909. document.body.appendChild(this._debugCanvas);
  45910. this._registerFunc = function () {
  45911. _this.drawDebugCanvas();
  45912. };
  45913. this._scene.registerBeforeRender(this._registerFunc);
  45914. }
  45915. if (this._registerFunc) {
  45916. var workingArray = this.getByteFrequencyData();
  45917. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  45918. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  45919. // Draw the frequency domain chart.
  45920. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  45921. var value = workingArray[i];
  45922. var percent = value / this.BARGRAPHAMPLITUDE;
  45923. var height = this.DEBUGCANVASSIZE.height * percent;
  45924. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  45925. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  45926. var hue = i / this.getFrequencyBinCount() * 360;
  45927. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  45928. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  45929. }
  45930. }
  45931. }
  45932. };
  45933. Analyser.prototype.stopDebugCanvas = function () {
  45934. if (this._debugCanvas) {
  45935. this._scene.unregisterBeforeRender(this._registerFunc);
  45936. this._registerFunc = null;
  45937. document.body.removeChild(this._debugCanvas);
  45938. this._debugCanvas = null;
  45939. this._debugCanvasContext = null;
  45940. }
  45941. };
  45942. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  45943. if (this._audioEngine.canUseWebAudio) {
  45944. inputAudioNode.connect(this._webAudioAnalyser);
  45945. this._webAudioAnalyser.connect(outputAudioNode);
  45946. }
  45947. };
  45948. Analyser.prototype.dispose = function () {
  45949. if (this._audioEngine.canUseWebAudio) {
  45950. this._webAudioAnalyser.disconnect();
  45951. }
  45952. };
  45953. return Analyser;
  45954. }());
  45955. BABYLON.Analyser = Analyser;
  45956. })(BABYLON || (BABYLON = {}));
  45957. var BABYLON;
  45958. (function (BABYLON) {
  45959. var DepthRenderer = (function () {
  45960. function DepthRenderer(scene, type) {
  45961. var _this = this;
  45962. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  45963. this._viewMatrix = BABYLON.Matrix.Zero();
  45964. this._projectionMatrix = BABYLON.Matrix.Zero();
  45965. this._transformMatrix = BABYLON.Matrix.Zero();
  45966. this._worldViewProjection = BABYLON.Matrix.Zero();
  45967. this._scene = scene;
  45968. var engine = scene.getEngine();
  45969. // Render target
  45970. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  45971. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45972. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45973. this._depthMap.refreshRate = 1;
  45974. this._depthMap.renderParticles = false;
  45975. this._depthMap.renderList = null;
  45976. // set default depth value to 1.0 (far away)
  45977. this._depthMap.onClearObservable.add(function (engine) {
  45978. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  45979. });
  45980. // Custom render function
  45981. var renderSubMesh = function (subMesh) {
  45982. var mesh = subMesh.getRenderingMesh();
  45983. var scene = _this._scene;
  45984. var engine = scene.getEngine();
  45985. // Culling
  45986. engine.setState(subMesh.getMaterial().backFaceCulling);
  45987. // Managing instances
  45988. var batch = mesh._getInstancesRenderList(subMesh._id);
  45989. if (batch.mustReturn) {
  45990. return;
  45991. }
  45992. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  45993. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  45994. engine.enableEffect(_this._effect);
  45995. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  45996. var material = subMesh.getMaterial();
  45997. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  45998. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  45999. // Alpha test
  46000. if (material && material.needAlphaTesting()) {
  46001. var alphaTexture = material.getAlphaTestTexture();
  46002. _this._effect.setTexture("diffuseSampler", alphaTexture);
  46003. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  46004. }
  46005. // Bones
  46006. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46007. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  46008. }
  46009. // Draw
  46010. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  46011. }
  46012. };
  46013. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  46014. var index;
  46015. for (index = 0; index < opaqueSubMeshes.length; index++) {
  46016. renderSubMesh(opaqueSubMeshes.data[index]);
  46017. }
  46018. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  46019. renderSubMesh(alphaTestSubMeshes.data[index]);
  46020. }
  46021. };
  46022. }
  46023. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  46024. var material = subMesh.getMaterial();
  46025. if (material.disableDepthWrite) {
  46026. return false;
  46027. }
  46028. var defines = [];
  46029. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46030. var mesh = subMesh.getMesh();
  46031. var scene = mesh.getScene();
  46032. // Alpha test
  46033. if (material && material.needAlphaTesting()) {
  46034. defines.push("#define ALPHATEST");
  46035. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  46036. attribs.push(BABYLON.VertexBuffer.UVKind);
  46037. defines.push("#define UV1");
  46038. }
  46039. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  46040. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46041. defines.push("#define UV2");
  46042. }
  46043. }
  46044. // Bones
  46045. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46046. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46047. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46048. if (mesh.numBoneInfluencers > 4) {
  46049. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  46050. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  46051. }
  46052. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46053. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46054. }
  46055. else {
  46056. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46057. }
  46058. // Instances
  46059. if (useInstances) {
  46060. defines.push("#define INSTANCES");
  46061. attribs.push("world0");
  46062. attribs.push("world1");
  46063. attribs.push("world2");
  46064. attribs.push("world3");
  46065. }
  46066. // Get correct effect
  46067. var join = defines.join("\n");
  46068. if (this._cachedDefines !== join) {
  46069. this._cachedDefines = join;
  46070. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  46071. }
  46072. return this._effect.isReady();
  46073. };
  46074. DepthRenderer.prototype.getDepthMap = function () {
  46075. return this._depthMap;
  46076. };
  46077. // Methods
  46078. DepthRenderer.prototype.dispose = function () {
  46079. this._depthMap.dispose();
  46080. };
  46081. return DepthRenderer;
  46082. }());
  46083. BABYLON.DepthRenderer = DepthRenderer;
  46084. })(BABYLON || (BABYLON = {}));
  46085. var BABYLON;
  46086. (function (BABYLON) {
  46087. var SSAORenderingPipeline = (function (_super) {
  46088. __extends(SSAORenderingPipeline, _super);
  46089. /**
  46090. * @constructor
  46091. * @param {string} name - The rendering pipeline name
  46092. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46093. * @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 }
  46094. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  46095. */
  46096. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  46097. var _this = this;
  46098. _super.call(this, scene.getEngine(), name);
  46099. // Members
  46100. /**
  46101. * The PassPostProcess id in the pipeline that contains the original scene color
  46102. * @type {string}
  46103. */
  46104. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  46105. /**
  46106. * The SSAO PostProcess id in the pipeline
  46107. * @type {string}
  46108. */
  46109. this.SSAORenderEffect = "SSAORenderEffect";
  46110. /**
  46111. * The horizontal blur PostProcess id in the pipeline
  46112. * @type {string}
  46113. */
  46114. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  46115. /**
  46116. * The vertical blur PostProcess id in the pipeline
  46117. * @type {string}
  46118. */
  46119. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  46120. /**
  46121. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  46122. * @type {string}
  46123. */
  46124. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  46125. /**
  46126. * The output strength of the SSAO post-process. Default value is 1.0.
  46127. * @type {number}
  46128. */
  46129. this.totalStrength = 1.0;
  46130. /**
  46131. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  46132. * @type {number}
  46133. */
  46134. this.radius = 0.0001;
  46135. /**
  46136. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  46137. * Must not be equal to fallOff and superior to fallOff.
  46138. * Default value is 0.975
  46139. * @type {number}
  46140. */
  46141. this.area = 0.0075;
  46142. /**
  46143. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  46144. * Must not be equal to area and inferior to area.
  46145. * Default value is 0.0
  46146. * @type {number}
  46147. */
  46148. this.fallOff = 0.000001;
  46149. /**
  46150. * The base color of the SSAO post-process
  46151. * The final result is "base + ssao" between [0, 1]
  46152. * @type {number}
  46153. */
  46154. this.base = 0.5;
  46155. this._firstUpdate = true;
  46156. this._scene = scene;
  46157. // Set up assets
  46158. this._createRandomTexture();
  46159. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  46160. var ssaoRatio = ratio.ssaoRatio || ratio;
  46161. var combineRatio = ratio.combineRatio || ratio;
  46162. this._ratio = {
  46163. ssaoRatio: ssaoRatio,
  46164. combineRatio: combineRatio
  46165. };
  46166. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  46167. this._createSSAOPostProcess(ssaoRatio);
  46168. this._createBlurPostProcess(ssaoRatio);
  46169. this._createSSAOCombinePostProcess(combineRatio);
  46170. // Set up pipeline
  46171. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  46172. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  46173. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  46174. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  46175. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  46176. // Finish
  46177. scene.postProcessRenderPipelineManager.addPipeline(this);
  46178. if (cameras)
  46179. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  46180. }
  46181. // Public Methods
  46182. /**
  46183. * Returns the horizontal blur PostProcess
  46184. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  46185. */
  46186. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  46187. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  46188. return null;
  46189. };
  46190. /**
  46191. * Returns the vertical blur PostProcess
  46192. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  46193. */
  46194. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  46195. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  46196. return null;
  46197. };
  46198. /**
  46199. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  46200. */
  46201. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  46202. if (disableDepthRender === void 0) { disableDepthRender = false; }
  46203. for (var i = 0; i < this._scene.cameras.length; i++) {
  46204. var camera = this._scene.cameras[i];
  46205. this._originalColorPostProcess.dispose(camera);
  46206. this._ssaoPostProcess.dispose(camera);
  46207. this._blurHPostProcess.dispose(camera);
  46208. this._blurVPostProcess.dispose(camera);
  46209. this._ssaoCombinePostProcess.dispose(camera);
  46210. }
  46211. this._randomTexture.dispose();
  46212. if (disableDepthRender)
  46213. this._scene.disableDepthRenderer();
  46214. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  46215. };
  46216. // Private Methods
  46217. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  46218. var _this = this;
  46219. /*
  46220. var samplerOffsets = [
  46221. -8.0, -6.0, -4.0, -2.0,
  46222. 0.0,
  46223. 2.0, 4.0, 6.0, 8.0
  46224. ];
  46225. */
  46226. var samples = 16;
  46227. var samplerOffsets = [];
  46228. for (var i = -8; i < 8; i++) {
  46229. samplerOffsets.push(i * 2);
  46230. }
  46231. 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");
  46232. this._blurHPostProcess.onApply = function (effect) {
  46233. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  46234. effect.setTexture("depthSampler", _this._depthTexture);
  46235. if (_this._firstUpdate) {
  46236. effect.setArray("samplerOffsets", samplerOffsets);
  46237. }
  46238. };
  46239. 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");
  46240. this._blurVPostProcess.onApply = function (effect) {
  46241. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  46242. effect.setTexture("depthSampler", _this._depthTexture);
  46243. if (_this._firstUpdate) {
  46244. effect.setArray("samplerOffsets", samplerOffsets);
  46245. _this._firstUpdate = false;
  46246. }
  46247. };
  46248. };
  46249. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  46250. var _this = this;
  46251. var numSamples = 16;
  46252. var sampleSphere = [
  46253. 0.5381, 0.1856, -0.4319,
  46254. 0.1379, 0.2486, 0.4430,
  46255. 0.3371, 0.5679, -0.0057,
  46256. -0.6999, -0.0451, -0.0019,
  46257. 0.0689, -0.1598, -0.8547,
  46258. 0.0560, 0.0069, -0.1843,
  46259. -0.0146, 0.1402, 0.0762,
  46260. 0.0100, -0.1924, -0.0344,
  46261. -0.3577, -0.5301, -0.4358,
  46262. -0.3169, 0.1063, 0.0158,
  46263. 0.0103, -0.5869, 0.0046,
  46264. -0.0897, -0.4940, 0.3287,
  46265. 0.7119, -0.0154, -0.0918,
  46266. -0.0533, 0.0596, -0.5411,
  46267. 0.0352, -0.0631, 0.5460,
  46268. -0.4776, 0.2847, -0.0271
  46269. ];
  46270. var samplesFactor = 1.0 / numSamples;
  46271. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  46272. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  46273. "area", "fallOff", "base", "range", "viewport"
  46274. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  46275. var viewport = new BABYLON.Vector2(0, 0);
  46276. this._ssaoPostProcess.onApply = function (effect) {
  46277. if (_this._firstUpdate) {
  46278. effect.setArray3("sampleSphere", sampleSphere);
  46279. effect.setFloat("samplesFactor", samplesFactor);
  46280. effect.setFloat("randTextureTiles", 4.0);
  46281. }
  46282. effect.setFloat("totalStrength", _this.totalStrength);
  46283. effect.setFloat("radius", _this.radius);
  46284. effect.setFloat("area", _this.area);
  46285. effect.setFloat("fallOff", _this.fallOff);
  46286. effect.setFloat("base", _this.base);
  46287. effect.setTexture("textureSampler", _this._depthTexture);
  46288. effect.setTexture("randomSampler", _this._randomTexture);
  46289. };
  46290. };
  46291. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  46292. var _this = this;
  46293. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  46294. this._ssaoCombinePostProcess.onApply = function (effect) {
  46295. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  46296. };
  46297. };
  46298. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  46299. var size = 512;
  46300. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  46301. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  46302. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  46303. var context = this._randomTexture.getContext();
  46304. var rand = function (min, max) {
  46305. return Math.random() * (max - min) + min;
  46306. };
  46307. var randVector = BABYLON.Vector3.Zero();
  46308. for (var x = 0; x < size; x++) {
  46309. for (var y = 0; y < size; y++) {
  46310. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  46311. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  46312. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  46313. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  46314. context.fillRect(x, y, 1, 1);
  46315. }
  46316. }
  46317. this._randomTexture.update(false);
  46318. };
  46319. __decorate([
  46320. BABYLON.serialize()
  46321. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  46322. __decorate([
  46323. BABYLON.serialize()
  46324. ], SSAORenderingPipeline.prototype, "radius", void 0);
  46325. __decorate([
  46326. BABYLON.serialize()
  46327. ], SSAORenderingPipeline.prototype, "area", void 0);
  46328. __decorate([
  46329. BABYLON.serialize()
  46330. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  46331. __decorate([
  46332. BABYLON.serialize()
  46333. ], SSAORenderingPipeline.prototype, "base", void 0);
  46334. __decorate([
  46335. BABYLON.serialize()
  46336. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  46337. return SSAORenderingPipeline;
  46338. }(BABYLON.PostProcessRenderPipeline));
  46339. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  46340. })(BABYLON || (BABYLON = {}));
  46341. var BABYLON;
  46342. (function (BABYLON) {
  46343. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  46344. var VolumetricLightScatteringPostProcess = (function (_super) {
  46345. __extends(VolumetricLightScatteringPostProcess, _super);
  46346. /**
  46347. * @constructor
  46348. * @param {string} name - The post-process name
  46349. * @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)
  46350. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  46351. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  46352. * @param {number} samples - The post-process quality, default 100
  46353. * @param {number} samplingMode - The post-process filtering mode
  46354. * @param {BABYLON.Engine} engine - The babylon engine
  46355. * @param {boolean} reusable - If the post-process is reusable
  46356. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  46357. */
  46358. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  46359. var _this = this;
  46360. if (samples === void 0) { samples = 100; }
  46361. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  46362. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  46363. this._screenCoordinates = BABYLON.Vector2.Zero();
  46364. /**
  46365. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  46366. * @type {Vector3}
  46367. */
  46368. this.customMeshPosition = BABYLON.Vector3.Zero();
  46369. /**
  46370. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  46371. * @type {boolean}
  46372. */
  46373. this.useCustomMeshPosition = false;
  46374. /**
  46375. * If the post-process should inverse the light scattering direction
  46376. * @type {boolean}
  46377. */
  46378. this.invert = true;
  46379. /**
  46380. * Array containing the excluded meshes not rendered in the internal pass
  46381. */
  46382. this.excludedMeshes = new Array();
  46383. /**
  46384. * Controls the overall intensity of the post-process
  46385. * @type {number}
  46386. */
  46387. this.exposure = 0.3;
  46388. /**
  46389. * Dissipates each sample's contribution in range [0, 1]
  46390. * @type {number}
  46391. */
  46392. this.decay = 0.96815;
  46393. /**
  46394. * Controls the overall intensity of each sample
  46395. * @type {number}
  46396. */
  46397. this.weight = 0.58767;
  46398. /**
  46399. * Controls the density of each sample
  46400. * @type {number}
  46401. */
  46402. this.density = 0.926;
  46403. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  46404. var engine = scene.getEngine();
  46405. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  46406. // Configure mesh
  46407. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  46408. // Configure
  46409. this._createPass(scene, ratio.passRatio || ratio);
  46410. this.onActivate = function (camera) {
  46411. if (!_this.isSupported) {
  46412. _this.dispose(camera);
  46413. }
  46414. _this.onActivate = null;
  46415. };
  46416. this.onApplyObservable.add(function (effect) {
  46417. _this._updateMeshScreenCoordinates(scene);
  46418. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  46419. effect.setFloat("exposure", _this.exposure);
  46420. effect.setFloat("decay", _this.decay);
  46421. effect.setFloat("weight", _this.weight);
  46422. effect.setFloat("density", _this.density);
  46423. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  46424. });
  46425. }
  46426. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  46427. get: function () {
  46428. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  46429. return false;
  46430. },
  46431. set: function (useDiffuseColor) {
  46432. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  46433. },
  46434. enumerable: true,
  46435. configurable: true
  46436. });
  46437. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  46438. var mesh = subMesh.getMesh();
  46439. // Render this.mesh as default
  46440. if (mesh === this.mesh) {
  46441. return mesh.material.isReady(mesh);
  46442. }
  46443. var defines = [];
  46444. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46445. var material = subMesh.getMaterial();
  46446. var needUV = false;
  46447. // Alpha test
  46448. if (material) {
  46449. if (material.needAlphaTesting()) {
  46450. defines.push("#define ALPHATEST");
  46451. }
  46452. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  46453. attribs.push(BABYLON.VertexBuffer.UVKind);
  46454. defines.push("#define UV1");
  46455. }
  46456. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  46457. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46458. defines.push("#define UV2");
  46459. }
  46460. }
  46461. // Bones
  46462. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46463. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46464. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46465. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46466. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46467. }
  46468. else {
  46469. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46470. }
  46471. // Instances
  46472. if (useInstances) {
  46473. defines.push("#define INSTANCES");
  46474. attribs.push("world0");
  46475. attribs.push("world1");
  46476. attribs.push("world2");
  46477. attribs.push("world3");
  46478. }
  46479. // Get correct effect
  46480. var join = defines.join("\n");
  46481. if (this._cachedDefines !== join) {
  46482. this._cachedDefines = join;
  46483. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  46484. }
  46485. return this._volumetricLightScatteringPass.isReady();
  46486. };
  46487. /**
  46488. * Sets the new light position for light scattering effect
  46489. * @param {BABYLON.Vector3} The new custom light position
  46490. */
  46491. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  46492. this.customMeshPosition = position;
  46493. };
  46494. /**
  46495. * Returns the light position for light scattering effect
  46496. * @return {BABYLON.Vector3} The custom light position
  46497. */
  46498. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  46499. return this.customMeshPosition;
  46500. };
  46501. /**
  46502. * Disposes the internal assets and detaches the post-process from the camera
  46503. */
  46504. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  46505. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  46506. if (rttIndex !== -1) {
  46507. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  46508. }
  46509. this._volumetricLightScatteringRTT.dispose();
  46510. _super.prototype.dispose.call(this, camera);
  46511. };
  46512. /**
  46513. * Returns the render target texture used by the post-process
  46514. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  46515. */
  46516. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  46517. return this._volumetricLightScatteringRTT;
  46518. };
  46519. // Private methods
  46520. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  46521. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  46522. return true;
  46523. }
  46524. return false;
  46525. };
  46526. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  46527. var _this = this;
  46528. var engine = scene.getEngine();
  46529. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  46530. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46531. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46532. this._volumetricLightScatteringRTT.renderList = null;
  46533. this._volumetricLightScatteringRTT.renderParticles = false;
  46534. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  46535. // Custom render function for submeshes
  46536. var renderSubMesh = function (subMesh) {
  46537. var mesh = subMesh.getRenderingMesh();
  46538. if (_this._meshExcluded(mesh)) {
  46539. return;
  46540. }
  46541. var scene = mesh.getScene();
  46542. var engine = scene.getEngine();
  46543. // Culling
  46544. engine.setState(subMesh.getMaterial().backFaceCulling);
  46545. // Managing instances
  46546. var batch = mesh._getInstancesRenderList(subMesh._id);
  46547. if (batch.mustReturn) {
  46548. return;
  46549. }
  46550. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  46551. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  46552. var effect = _this._volumetricLightScatteringPass;
  46553. if (mesh === _this.mesh) {
  46554. effect = subMesh.getMaterial().getEffect();
  46555. }
  46556. engine.enableEffect(effect);
  46557. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  46558. if (mesh === _this.mesh) {
  46559. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  46560. }
  46561. else {
  46562. var material = subMesh.getMaterial();
  46563. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  46564. // Alpha test
  46565. if (material && material.needAlphaTesting()) {
  46566. var alphaTexture = material.getAlphaTestTexture();
  46567. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  46568. if (alphaTexture) {
  46569. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  46570. }
  46571. }
  46572. // Bones
  46573. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46574. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  46575. }
  46576. }
  46577. // Draw
  46578. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  46579. }
  46580. };
  46581. // Render target texture callbacks
  46582. var savedSceneClearColor;
  46583. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  46584. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  46585. savedSceneClearColor = scene.clearColor;
  46586. scene.clearColor = sceneClearColor;
  46587. });
  46588. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  46589. scene.clearColor = savedSceneClearColor;
  46590. });
  46591. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  46592. var engine = scene.getEngine();
  46593. var index;
  46594. for (index = 0; index < opaqueSubMeshes.length; index++) {
  46595. renderSubMesh(opaqueSubMeshes.data[index]);
  46596. }
  46597. engine.setAlphaTesting(true);
  46598. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  46599. renderSubMesh(alphaTestSubMeshes.data[index]);
  46600. }
  46601. engine.setAlphaTesting(false);
  46602. if (transparentSubMeshes.length) {
  46603. // Sort sub meshes
  46604. for (index = 0; index < transparentSubMeshes.length; index++) {
  46605. var submesh = transparentSubMeshes.data[index];
  46606. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  46607. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  46608. }
  46609. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  46610. sortedArray.sort(function (a, b) {
  46611. // Alpha index first
  46612. if (a._alphaIndex > b._alphaIndex) {
  46613. return 1;
  46614. }
  46615. if (a._alphaIndex < b._alphaIndex) {
  46616. return -1;
  46617. }
  46618. // Then distance to camera
  46619. if (a._distanceToCamera < b._distanceToCamera) {
  46620. return 1;
  46621. }
  46622. if (a._distanceToCamera > b._distanceToCamera) {
  46623. return -1;
  46624. }
  46625. return 0;
  46626. });
  46627. // Render sub meshes
  46628. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46629. for (index = 0; index < sortedArray.length; index++) {
  46630. renderSubMesh(sortedArray[index]);
  46631. }
  46632. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46633. }
  46634. };
  46635. };
  46636. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  46637. var transform = scene.getTransformMatrix();
  46638. var meshPosition;
  46639. if (this.useCustomMeshPosition) {
  46640. meshPosition = this.customMeshPosition;
  46641. }
  46642. else if (this.attachedNode) {
  46643. meshPosition = this.attachedNode.position;
  46644. }
  46645. else {
  46646. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  46647. }
  46648. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  46649. this._screenCoordinates.x = pos.x / this._viewPort.width;
  46650. this._screenCoordinates.y = pos.y / this._viewPort.height;
  46651. if (this.invert)
  46652. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  46653. };
  46654. // Static methods
  46655. /**
  46656. * Creates a default mesh for the Volumeric Light Scattering post-process
  46657. * @param {string} The mesh name
  46658. * @param {BABYLON.Scene} The scene where to create the mesh
  46659. * @return {BABYLON.Mesh} the default mesh
  46660. */
  46661. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  46662. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  46663. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  46664. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  46665. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  46666. mesh.material = material;
  46667. return mesh;
  46668. };
  46669. __decorate([
  46670. BABYLON.serializeAsVector3()
  46671. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  46672. __decorate([
  46673. BABYLON.serialize()
  46674. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  46675. __decorate([
  46676. BABYLON.serialize()
  46677. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  46678. __decorate([
  46679. BABYLON.serializeAsMeshReference()
  46680. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  46681. __decorate([
  46682. BABYLON.serialize()
  46683. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  46684. __decorate([
  46685. BABYLON.serialize()
  46686. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  46687. __decorate([
  46688. BABYLON.serialize()
  46689. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  46690. __decorate([
  46691. BABYLON.serialize()
  46692. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  46693. __decorate([
  46694. BABYLON.serialize()
  46695. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  46696. return VolumetricLightScatteringPostProcess;
  46697. }(BABYLON.PostProcess));
  46698. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  46699. })(BABYLON || (BABYLON = {}));
  46700. // BABYLON.JS Chromatic Aberration GLSL Shader
  46701. // Author: Olivier Guyot
  46702. // Separates very slightly R, G and B colors on the edges of the screen
  46703. // Inspired by Francois Tarlier & Martins Upitis
  46704. var BABYLON;
  46705. (function (BABYLON) {
  46706. var LensRenderingPipeline = (function (_super) {
  46707. __extends(LensRenderingPipeline, _super);
  46708. /**
  46709. * @constructor
  46710. *
  46711. * Effect parameters are as follow:
  46712. * {
  46713. * chromatic_aberration: number; // from 0 to x (1 for realism)
  46714. * edge_blur: number; // from 0 to x (1 for realism)
  46715. * distortion: number; // from 0 to x (1 for realism)
  46716. * grain_amount: number; // from 0 to 1
  46717. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  46718. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  46719. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  46720. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  46721. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  46722. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  46723. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  46724. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  46725. * }
  46726. * Note: if an effect parameter is unset, effect is disabled
  46727. *
  46728. * @param {string} name - The rendering pipeline name
  46729. * @param {object} parameters - An object containing all parameters (see above)
  46730. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46731. * @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)
  46732. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  46733. */
  46734. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  46735. var _this = this;
  46736. if (ratio === void 0) { ratio = 1.0; }
  46737. _super.call(this, scene.getEngine(), name);
  46738. // Lens effects can be of the following:
  46739. // - chromatic aberration (slight shift of RGB colors)
  46740. // - blur on the edge of the lens
  46741. // - lens distortion
  46742. // - depth-of-field blur & highlights enhancing
  46743. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  46744. // - grain effect (noise or custom texture)
  46745. // Two additional texture samplers are needed:
  46746. // - depth map (for depth-of-field)
  46747. // - grain texture
  46748. /**
  46749. * The chromatic aberration PostProcess id in the pipeline
  46750. * @type {string}
  46751. */
  46752. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  46753. /**
  46754. * The highlights enhancing PostProcess id in the pipeline
  46755. * @type {string}
  46756. */
  46757. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  46758. /**
  46759. * The depth-of-field PostProcess id in the pipeline
  46760. * @type {string}
  46761. */
  46762. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  46763. this._scene = scene;
  46764. // Fetch texture samplers
  46765. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  46766. if (parameters.grain_texture) {
  46767. this._grainTexture = parameters.grain_texture;
  46768. }
  46769. else {
  46770. this._createGrainTexture();
  46771. }
  46772. // save parameters
  46773. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  46774. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  46775. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  46776. this._distortion = parameters.distortion ? parameters.distortion : 0;
  46777. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  46778. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  46779. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  46780. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  46781. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  46782. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  46783. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  46784. // Create effects
  46785. this._createChromaticAberrationPostProcess(ratio);
  46786. this._createHighlightsPostProcess(ratio);
  46787. this._createDepthOfFieldPostProcess(ratio / 4);
  46788. // Set up pipeline
  46789. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  46790. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  46791. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  46792. if (this._highlightsGain === -1) {
  46793. this._disableEffect(this.HighlightsEnhancingEffect, null);
  46794. }
  46795. // Finish
  46796. scene.postProcessRenderPipelineManager.addPipeline(this);
  46797. if (cameras) {
  46798. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  46799. }
  46800. }
  46801. // public methods (self explanatory)
  46802. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  46803. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  46804. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  46805. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  46806. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  46807. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  46808. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  46809. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  46810. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  46811. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  46812. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  46813. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  46814. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  46815. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  46816. };
  46817. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  46818. this._highlightsPostProcess.updateEffect();
  46819. };
  46820. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  46821. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  46822. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  46823. this._highlightsGain = amount;
  46824. };
  46825. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  46826. if (this._highlightsGain === -1) {
  46827. this._highlightsGain = 1.0;
  46828. }
  46829. this._highlightsThreshold = amount;
  46830. };
  46831. LensRenderingPipeline.prototype.disableHighlights = function () {
  46832. this._highlightsGain = -1;
  46833. };
  46834. /**
  46835. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  46836. */
  46837. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  46838. if (disableDepthRender === void 0) { disableDepthRender = false; }
  46839. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  46840. this._chromaticAberrationPostProcess = undefined;
  46841. this._highlightsPostProcess = undefined;
  46842. this._depthOfFieldPostProcess = undefined;
  46843. this._grainTexture.dispose();
  46844. if (disableDepthRender)
  46845. this._scene.disableDepthRenderer();
  46846. };
  46847. // colors shifting and distortion
  46848. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  46849. var _this = this;
  46850. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  46851. [], // samplers
  46852. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  46853. this._chromaticAberrationPostProcess.onApply = function (effect) {
  46854. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  46855. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  46856. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  46857. };
  46858. };
  46859. // highlights enhancing
  46860. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  46861. var _this = this;
  46862. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  46863. [], // samplers
  46864. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  46865. this._highlightsPostProcess.onApply = function (effect) {
  46866. effect.setFloat('gain', _this._highlightsGain);
  46867. effect.setFloat('threshold', _this._highlightsThreshold);
  46868. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  46869. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  46870. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  46871. };
  46872. };
  46873. // colors shifting and distortion
  46874. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  46875. var _this = this;
  46876. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  46877. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  46878. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  46879. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  46880. this._depthOfFieldPostProcess.onApply = function (effect) {
  46881. effect.setTexture("depthSampler", _this._depthTexture);
  46882. effect.setTexture("grainSampler", _this._grainTexture);
  46883. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  46884. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  46885. effect.setFloat('grain_amount', _this._grainAmount);
  46886. effect.setBool('blur_noise', _this._blurNoise);
  46887. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  46888. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  46889. effect.setFloat('distortion', _this._distortion);
  46890. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  46891. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  46892. effect.setFloat('aperture', _this._dofAperture);
  46893. effect.setFloat('darken', _this._dofDarken);
  46894. effect.setFloat('edge_blur', _this._edgeBlur);
  46895. effect.setBool('highlights', (_this._highlightsGain !== -1));
  46896. effect.setFloat('near', _this._scene.activeCamera.minZ);
  46897. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  46898. };
  46899. };
  46900. // creates a black and white random noise texture, 512x512
  46901. LensRenderingPipeline.prototype._createGrainTexture = function () {
  46902. var size = 512;
  46903. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46904. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  46905. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  46906. var context = this._grainTexture.getContext();
  46907. var rand = function (min, max) {
  46908. return Math.random() * (max - min) + min;
  46909. };
  46910. var value;
  46911. for (var x = 0; x < size; x++) {
  46912. for (var y = 0; y < size; y++) {
  46913. value = Math.floor(rand(0.42, 0.58) * 255);
  46914. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  46915. context.fillRect(x, y, 1, 1);
  46916. }
  46917. }
  46918. this._grainTexture.update(false);
  46919. };
  46920. return LensRenderingPipeline;
  46921. }(BABYLON.PostProcessRenderPipeline));
  46922. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  46923. })(BABYLON || (BABYLON = {}));
  46924. //
  46925. // This post-process allows the modification of rendered colors by using
  46926. // a 'look-up table' (LUT). This effect is also called Color Grading.
  46927. //
  46928. // The object needs to be provided an url to a texture containing the color
  46929. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  46930. // Use an image editing software to tweak the LUT to match your needs.
  46931. //
  46932. // For an example of a color LUT, see here:
  46933. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  46934. // For explanations on color grading, see here:
  46935. // http://udn.epicgames.com/Three/ColorGrading.html
  46936. //
  46937. var BABYLON;
  46938. (function (BABYLON) {
  46939. var ColorCorrectionPostProcess = (function (_super) {
  46940. __extends(ColorCorrectionPostProcess, _super);
  46941. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  46942. var _this = this;
  46943. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  46944. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  46945. this._colorTableTexture.anisotropicFilteringLevel = 1;
  46946. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46947. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46948. this.onApply = function (effect) {
  46949. effect.setTexture("colorTable", _this._colorTableTexture);
  46950. };
  46951. }
  46952. return ColorCorrectionPostProcess;
  46953. }(BABYLON.PostProcess));
  46954. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  46955. })(BABYLON || (BABYLON = {}));
  46956. var BABYLON;
  46957. (function (BABYLON) {
  46958. var AnaglyphFreeCamera = (function (_super) {
  46959. __extends(AnaglyphFreeCamera, _super);
  46960. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  46961. _super.call(this, name, position, scene);
  46962. this.interaxialDistance = interaxialDistance;
  46963. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  46964. }
  46965. AnaglyphFreeCamera.prototype.getTypeName = function () {
  46966. return "AnaglyphFreeCamera";
  46967. };
  46968. return AnaglyphFreeCamera;
  46969. }(BABYLON.FreeCamera));
  46970. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  46971. var AnaglyphArcRotateCamera = (function (_super) {
  46972. __extends(AnaglyphArcRotateCamera, _super);
  46973. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  46974. _super.call(this, name, alpha, beta, radius, target, scene);
  46975. this.interaxialDistance = interaxialDistance;
  46976. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  46977. }
  46978. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  46979. return "AnaglyphArcRotateCamera";
  46980. };
  46981. return AnaglyphArcRotateCamera;
  46982. }(BABYLON.ArcRotateCamera));
  46983. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  46984. var AnaglyphGamepadCamera = (function (_super) {
  46985. __extends(AnaglyphGamepadCamera, _super);
  46986. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  46987. _super.call(this, name, position, scene);
  46988. this.interaxialDistance = interaxialDistance;
  46989. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  46990. }
  46991. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  46992. return "AnaglyphGamepadCamera";
  46993. };
  46994. return AnaglyphGamepadCamera;
  46995. }(BABYLON.GamepadCamera));
  46996. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  46997. var AnaglyphUniversalCamera = (function (_super) {
  46998. __extends(AnaglyphUniversalCamera, _super);
  46999. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  47000. _super.call(this, name, position, scene);
  47001. this.interaxialDistance = interaxialDistance;
  47002. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  47003. }
  47004. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  47005. return "AnaglyphUniversalCamera";
  47006. };
  47007. return AnaglyphUniversalCamera;
  47008. }(BABYLON.UniversalCamera));
  47009. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  47010. var StereoscopicFreeCamera = (function (_super) {
  47011. __extends(StereoscopicFreeCamera, _super);
  47012. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  47013. _super.call(this, name, position, scene);
  47014. this.interaxialDistance = interaxialDistance;
  47015. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  47016. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  47017. }
  47018. StereoscopicFreeCamera.prototype.getTypeName = function () {
  47019. return "StereoscopicFreeCamera";
  47020. };
  47021. return StereoscopicFreeCamera;
  47022. }(BABYLON.FreeCamera));
  47023. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  47024. var StereoscopicArcRotateCamera = (function (_super) {
  47025. __extends(StereoscopicArcRotateCamera, _super);
  47026. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  47027. _super.call(this, name, alpha, beta, radius, target, scene);
  47028. this.interaxialDistance = interaxialDistance;
  47029. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  47030. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  47031. }
  47032. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  47033. return "StereoscopicArcRotateCamera";
  47034. };
  47035. return StereoscopicArcRotateCamera;
  47036. }(BABYLON.ArcRotateCamera));
  47037. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  47038. var StereoscopicGamepadCamera = (function (_super) {
  47039. __extends(StereoscopicGamepadCamera, _super);
  47040. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  47041. _super.call(this, name, position, scene);
  47042. this.interaxialDistance = interaxialDistance;
  47043. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  47044. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  47045. }
  47046. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  47047. return "StereoscopicGamepadCamera";
  47048. };
  47049. return StereoscopicGamepadCamera;
  47050. }(BABYLON.GamepadCamera));
  47051. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  47052. var StereoscopicUniversalCamera = (function (_super) {
  47053. __extends(StereoscopicUniversalCamera, _super);
  47054. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  47055. _super.call(this, name, position, scene);
  47056. this.interaxialDistance = interaxialDistance;
  47057. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  47058. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  47059. }
  47060. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  47061. return "StereoscopicUniversalCamera";
  47062. };
  47063. return StereoscopicUniversalCamera;
  47064. }(BABYLON.UniversalCamera));
  47065. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  47066. })(BABYLON || (BABYLON = {}));
  47067. var BABYLON;
  47068. (function (BABYLON) {
  47069. var HDRRenderingPipeline = (function (_super) {
  47070. __extends(HDRRenderingPipeline, _super);
  47071. /**
  47072. * @constructor
  47073. * @param {string} name - The rendering pipeline name
  47074. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47075. * @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)
  47076. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  47077. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47078. */
  47079. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  47080. var _this = this;
  47081. if (originalPostProcess === void 0) { originalPostProcess = null; }
  47082. _super.call(this, scene.getEngine(), name);
  47083. /**
  47084. * Public members
  47085. */
  47086. // Gaussian Blur
  47087. /**
  47088. * Gaussian blur coefficient
  47089. * @type {number}
  47090. */
  47091. this.gaussCoeff = 0.3;
  47092. /**
  47093. * Gaussian blur mean
  47094. * @type {number}
  47095. */
  47096. this.gaussMean = 1.0;
  47097. /**
  47098. * Gaussian blur standard deviation
  47099. * @type {number}
  47100. */
  47101. this.gaussStandDev = 0.8;
  47102. /**
  47103. * Gaussian blur multiplier. Multiplies the blur effect
  47104. * @type {number}
  47105. */
  47106. this.gaussMultiplier = 4.0;
  47107. // HDR
  47108. /**
  47109. * Exposure, controls the overall intensity of the pipeline
  47110. * @type {number}
  47111. */
  47112. this.exposure = 1.0;
  47113. /**
  47114. * Minimum luminance that the post-process can output. Luminance is >= 0
  47115. * @type {number}
  47116. */
  47117. this.minimumLuminance = 1.0;
  47118. /**
  47119. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  47120. * @type {number}
  47121. */
  47122. this.maximumLuminance = 1e20;
  47123. /**
  47124. * Increase rate for luminance: eye adaptation speed to dark
  47125. * @type {number}
  47126. */
  47127. this.luminanceIncreaserate = 0.5;
  47128. /**
  47129. * Decrease rate for luminance: eye adaptation speed to bright
  47130. * @type {number}
  47131. */
  47132. this.luminanceDecreaseRate = 0.5;
  47133. // Bright pass
  47134. /**
  47135. * Minimum luminance needed to compute HDR
  47136. * @type {number}
  47137. */
  47138. this.brightThreshold = 0.8;
  47139. this._needUpdate = true;
  47140. this._scene = scene;
  47141. // Bright pass
  47142. this._createBrightPassPostProcess(scene, ratio);
  47143. // Down sample X4
  47144. this._createDownSampleX4PostProcess(scene, ratio);
  47145. // Create gaussian blur post-processes
  47146. this._createGaussianBlurPostProcess(scene, ratio);
  47147. // Texture adder
  47148. this._createTextureAdderPostProcess(scene, ratio);
  47149. // Luminance generator
  47150. this._createLuminanceGeneratorPostProcess(scene);
  47151. // HDR
  47152. this._createHDRPostProcess(scene, ratio);
  47153. // Pass postprocess
  47154. if (originalPostProcess === null) {
  47155. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  47156. }
  47157. else {
  47158. this._originalPostProcess = originalPostProcess;
  47159. }
  47160. // Configure pipeline
  47161. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  47162. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  47163. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  47164. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  47165. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  47166. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  47167. var addDownSamplerPostProcess = function (id) {
  47168. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  47169. };
  47170. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  47171. addDownSamplerPostProcess(i);
  47172. }
  47173. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  47174. // Finish
  47175. scene.postProcessRenderPipelineManager.addPipeline(this);
  47176. if (cameras !== null) {
  47177. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47178. }
  47179. this.update();
  47180. }
  47181. /**
  47182. * Tells the pipeline to update its post-processes
  47183. */
  47184. HDRRenderingPipeline.prototype.update = function () {
  47185. this._needUpdate = true;
  47186. };
  47187. /**
  47188. * Returns the current calculated luminance
  47189. */
  47190. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  47191. return this._hdrCurrentLuminance;
  47192. };
  47193. /**
  47194. * Returns the currently drawn luminance
  47195. */
  47196. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  47197. return this._hdrOutputLuminance;
  47198. };
  47199. /**
  47200. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  47201. */
  47202. HDRRenderingPipeline.prototype.dispose = function () {
  47203. this._originalPostProcess = undefined;
  47204. this._brightPassPostProcess = undefined;
  47205. this._downSampleX4PostProcess = undefined;
  47206. this._guassianBlurHPostProcess = undefined;
  47207. this._guassianBlurVPostProcess = undefined;
  47208. this._textureAdderPostProcess = undefined;
  47209. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  47210. this._downSamplePostProcesses[i] = undefined;
  47211. }
  47212. this._hdrPostProcess = undefined;
  47213. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47214. };
  47215. /**
  47216. * Creates the HDR post-process and computes the luminance adaptation
  47217. */
  47218. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  47219. var _this = this;
  47220. var hdrLastLuminance = 0.0;
  47221. this._hdrOutputLuminance = -1.0;
  47222. this._hdrCurrentLuminance = 1.0;
  47223. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  47224. this._hdrPostProcess.onApply = function (effect) {
  47225. if (_this._hdrOutputLuminance < 0.0) {
  47226. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  47227. }
  47228. else {
  47229. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  47230. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  47231. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  47232. }
  47233. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  47234. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  47235. }
  47236. else {
  47237. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  47238. }
  47239. }
  47240. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  47241. hdrLastLuminance += scene.getEngine().getDeltaTime();
  47242. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  47243. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  47244. effect.setFloat("exposure", _this.exposure);
  47245. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  47246. _this._needUpdate = false;
  47247. };
  47248. };
  47249. /**
  47250. * Texture Adder post-process
  47251. */
  47252. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  47253. var _this = this;
  47254. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  47255. this._textureAdderPostProcess.onApply = function (effect) {
  47256. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  47257. };
  47258. };
  47259. /**
  47260. * Down sample X4 post-process
  47261. */
  47262. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  47263. var _this = this;
  47264. var downSampleX4Offsets = new Array(32);
  47265. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  47266. this._downSampleX4PostProcess.onApply = function (effect) {
  47267. if (_this._needUpdate) {
  47268. var id = 0;
  47269. for (var i = -2; i < 2; i++) {
  47270. for (var j = -2; j < 2; j++) {
  47271. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  47272. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  47273. id += 2;
  47274. }
  47275. }
  47276. }
  47277. effect.setArray2("dsOffsets", downSampleX4Offsets);
  47278. };
  47279. };
  47280. /**
  47281. * Bright pass post-process
  47282. */
  47283. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  47284. var _this = this;
  47285. var brightOffsets = new Array(8);
  47286. var brightPassCallback = function (effect) {
  47287. if (_this._needUpdate) {
  47288. var sU = (1.0 / _this._brightPassPostProcess.width);
  47289. var sV = (1.0 / _this._brightPassPostProcess.height);
  47290. brightOffsets[0] = -0.5 * sU;
  47291. brightOffsets[1] = 0.5 * sV;
  47292. brightOffsets[2] = 0.5 * sU;
  47293. brightOffsets[3] = 0.5 * sV;
  47294. brightOffsets[4] = -0.5 * sU;
  47295. brightOffsets[5] = -0.5 * sV;
  47296. brightOffsets[6] = 0.5 * sU;
  47297. brightOffsets[7] = -0.5 * sV;
  47298. }
  47299. effect.setArray2("dsOffsets", brightOffsets);
  47300. effect.setFloat("brightThreshold", _this.brightThreshold);
  47301. };
  47302. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  47303. this._brightPassPostProcess.onApply = brightPassCallback;
  47304. };
  47305. /**
  47306. * Luminance generator. Creates the luminance post-process and down sample post-processes
  47307. */
  47308. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  47309. var _this = this;
  47310. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  47311. var luminanceOffsets = new Array(8);
  47312. var downSampleOffsets = new Array(18);
  47313. var halfDestPixelSize;
  47314. this._downSamplePostProcesses = new Array(lumSteps);
  47315. // Utils for luminance
  47316. var luminanceUpdateSourceOffsets = function (width, height) {
  47317. var sU = (1.0 / width);
  47318. var sV = (1.0 / height);
  47319. luminanceOffsets[0] = -0.5 * sU;
  47320. luminanceOffsets[1] = 0.5 * sV;
  47321. luminanceOffsets[2] = 0.5 * sU;
  47322. luminanceOffsets[3] = 0.5 * sV;
  47323. luminanceOffsets[4] = -0.5 * sU;
  47324. luminanceOffsets[5] = -0.5 * sV;
  47325. luminanceOffsets[6] = 0.5 * sU;
  47326. luminanceOffsets[7] = -0.5 * sV;
  47327. };
  47328. var luminanceUpdateDestOffsets = function (width, height) {
  47329. var id = 0;
  47330. for (var x = -1; x < 2; x++) {
  47331. for (var y = -1; y < 2; y++) {
  47332. downSampleOffsets[id] = (x) / width;
  47333. downSampleOffsets[id + 1] = (y) / height;
  47334. id += 2;
  47335. }
  47336. }
  47337. };
  47338. // Luminance callback
  47339. var luminanceCallback = function (effect) {
  47340. if (_this._needUpdate) {
  47341. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  47342. }
  47343. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  47344. effect.setArray2("lumOffsets", luminanceOffsets);
  47345. };
  47346. // Down sample callbacks
  47347. var downSampleCallback = function (indice) {
  47348. var i = indice;
  47349. return function (effect) {
  47350. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  47351. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  47352. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  47353. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  47354. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  47355. effect.setArray2("dsOffsets", downSampleOffsets);
  47356. };
  47357. };
  47358. var downSampleAfterRenderCallback = function (effect) {
  47359. // Unpack result
  47360. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  47361. 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);
  47362. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  47363. };
  47364. // Create luminance post-process
  47365. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  47366. 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);
  47367. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  47368. // Create down sample post-processes
  47369. for (var i = lumSteps - 2; i >= 0; i--) {
  47370. var length = Math.pow(3, i);
  47371. ratio = { width: length, height: length };
  47372. var defines = "#define DOWN_SAMPLE\n";
  47373. if (i === 0) {
  47374. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  47375. }
  47376. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  47377. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  47378. if (i === 0) {
  47379. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  47380. }
  47381. }
  47382. };
  47383. /**
  47384. * Gaussian blur post-processes. Horizontal and Vertical
  47385. */
  47386. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  47387. var _this = this;
  47388. var blurOffsetsW = new Array(9);
  47389. var blurOffsetsH = new Array(9);
  47390. var blurWeights = new Array(9);
  47391. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  47392. // Utils for gaussian blur
  47393. var calculateBlurOffsets = function (height) {
  47394. var lastOutputDimensions = {
  47395. width: scene.getEngine().getRenderWidth(),
  47396. height: scene.getEngine().getRenderHeight()
  47397. };
  47398. for (var i = 0; i < 9; i++) {
  47399. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  47400. if (height) {
  47401. blurOffsetsH[i] = value;
  47402. }
  47403. else {
  47404. blurOffsetsW[i] = value;
  47405. }
  47406. }
  47407. };
  47408. var calculateWeights = function () {
  47409. var x = 0.0;
  47410. for (var i = 0; i < 9; i++) {
  47411. x = (i - 4.0) / 4.0;
  47412. 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));
  47413. }
  47414. };
  47415. // Callback
  47416. var gaussianBlurCallback = function (height) {
  47417. return function (effect) {
  47418. if (_this._needUpdate) {
  47419. calculateWeights();
  47420. calculateBlurOffsets(height);
  47421. }
  47422. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  47423. effect.setArray("blurWeights", blurWeights);
  47424. effect.setFloat("multiplier", _this.gaussMultiplier);
  47425. };
  47426. };
  47427. // Create horizontal gaussian blur post-processes
  47428. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  47429. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  47430. // Create vertical gaussian blur post-process
  47431. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  47432. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  47433. };
  47434. // Luminance generator
  47435. HDRRenderingPipeline.LUM_STEPS = 6;
  47436. return HDRRenderingPipeline;
  47437. }(BABYLON.PostProcessRenderPipeline));
  47438. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  47439. })(BABYLON || (BABYLON = {}));
  47440. var BABYLON;
  47441. (function (BABYLON) {
  47442. var FaceAdjacencies = (function () {
  47443. function FaceAdjacencies() {
  47444. this.edges = new Array();
  47445. this.edgesConnectedCount = 0;
  47446. }
  47447. return FaceAdjacencies;
  47448. }());
  47449. var EdgesRenderer = (function () {
  47450. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  47451. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  47452. if (epsilon === void 0) { epsilon = 0.95; }
  47453. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  47454. this.edgesWidthScalerForOrthographic = 1000.0;
  47455. this.edgesWidthScalerForPerspective = 50.0;
  47456. this._linesPositions = new Array();
  47457. this._linesNormals = new Array();
  47458. this._linesIndices = new Array();
  47459. this._buffers = {};
  47460. this._checkVerticesInsteadOfIndices = false;
  47461. this._source = source;
  47462. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  47463. this._epsilon = epsilon;
  47464. this._prepareRessources();
  47465. this._generateEdgesLines();
  47466. }
  47467. EdgesRenderer.prototype._prepareRessources = function () {
  47468. if (this._lineShader) {
  47469. return;
  47470. }
  47471. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  47472. attributes: ["position", "normal"],
  47473. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  47474. });
  47475. this._lineShader.disableDepthWrite = true;
  47476. this._lineShader.backFaceCulling = false;
  47477. };
  47478. EdgesRenderer.prototype.dispose = function () {
  47479. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  47480. if (buffer) {
  47481. buffer.dispose();
  47482. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  47483. }
  47484. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  47485. if (buffer) {
  47486. buffer.dispose();
  47487. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  47488. }
  47489. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  47490. this._lineShader.dispose();
  47491. };
  47492. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  47493. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  47494. return 0;
  47495. }
  47496. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  47497. return 1;
  47498. }
  47499. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  47500. return 2;
  47501. }
  47502. return -1;
  47503. };
  47504. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  47505. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  47506. return 0;
  47507. }
  47508. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  47509. return 1;
  47510. }
  47511. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  47512. return 2;
  47513. }
  47514. return -1;
  47515. };
  47516. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  47517. var needToCreateLine;
  47518. if (edge === undefined) {
  47519. needToCreateLine = true;
  47520. }
  47521. else {
  47522. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  47523. needToCreateLine = dotProduct < this._epsilon;
  47524. }
  47525. if (needToCreateLine) {
  47526. var offset = this._linesPositions.length / 3;
  47527. var normal = p0.subtract(p1);
  47528. normal.normalize();
  47529. // Positions
  47530. this._linesPositions.push(p0.x);
  47531. this._linesPositions.push(p0.y);
  47532. this._linesPositions.push(p0.z);
  47533. this._linesPositions.push(p0.x);
  47534. this._linesPositions.push(p0.y);
  47535. this._linesPositions.push(p0.z);
  47536. this._linesPositions.push(p1.x);
  47537. this._linesPositions.push(p1.y);
  47538. this._linesPositions.push(p1.z);
  47539. this._linesPositions.push(p1.x);
  47540. this._linesPositions.push(p1.y);
  47541. this._linesPositions.push(p1.z);
  47542. // Normals
  47543. this._linesNormals.push(p1.x);
  47544. this._linesNormals.push(p1.y);
  47545. this._linesNormals.push(p1.z);
  47546. this._linesNormals.push(-1);
  47547. this._linesNormals.push(p1.x);
  47548. this._linesNormals.push(p1.y);
  47549. this._linesNormals.push(p1.z);
  47550. this._linesNormals.push(1);
  47551. this._linesNormals.push(p0.x);
  47552. this._linesNormals.push(p0.y);
  47553. this._linesNormals.push(p0.z);
  47554. this._linesNormals.push(-1);
  47555. this._linesNormals.push(p0.x);
  47556. this._linesNormals.push(p0.y);
  47557. this._linesNormals.push(p0.z);
  47558. this._linesNormals.push(1);
  47559. // Indices
  47560. this._linesIndices.push(offset);
  47561. this._linesIndices.push(offset + 1);
  47562. this._linesIndices.push(offset + 2);
  47563. this._linesIndices.push(offset);
  47564. this._linesIndices.push(offset + 2);
  47565. this._linesIndices.push(offset + 3);
  47566. }
  47567. };
  47568. EdgesRenderer.prototype._generateEdgesLines = function () {
  47569. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47570. var indices = this._source.getIndices();
  47571. // First let's find adjacencies
  47572. var adjacencies = new Array();
  47573. var faceNormals = new Array();
  47574. var index;
  47575. var faceAdjacencies;
  47576. // Prepare faces
  47577. for (index = 0; index < indices.length; index += 3) {
  47578. faceAdjacencies = new FaceAdjacencies();
  47579. var p0Index = indices[index];
  47580. var p1Index = indices[index + 1];
  47581. var p2Index = indices[index + 2];
  47582. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  47583. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  47584. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  47585. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  47586. faceNormal.normalize();
  47587. faceNormals.push(faceNormal);
  47588. adjacencies.push(faceAdjacencies);
  47589. }
  47590. // Scan
  47591. for (index = 0; index < adjacencies.length; index++) {
  47592. faceAdjacencies = adjacencies[index];
  47593. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  47594. var otherFaceAdjacencies = adjacencies[otherIndex];
  47595. if (faceAdjacencies.edgesConnectedCount === 3) {
  47596. break;
  47597. }
  47598. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  47599. continue;
  47600. }
  47601. var otherP0 = indices[otherIndex * 3];
  47602. var otherP1 = indices[otherIndex * 3 + 1];
  47603. var otherP2 = indices[otherIndex * 3 + 2];
  47604. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  47605. var otherEdgeIndex;
  47606. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  47607. continue;
  47608. }
  47609. switch (edgeIndex) {
  47610. case 0:
  47611. if (this._checkVerticesInsteadOfIndices) {
  47612. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  47613. }
  47614. else {
  47615. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  47616. }
  47617. break;
  47618. case 1:
  47619. if (this._checkVerticesInsteadOfIndices) {
  47620. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  47621. }
  47622. else {
  47623. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  47624. }
  47625. break;
  47626. case 2:
  47627. if (this._checkVerticesInsteadOfIndices) {
  47628. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  47629. }
  47630. else {
  47631. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  47632. }
  47633. break;
  47634. }
  47635. if (otherEdgeIndex === -1) {
  47636. continue;
  47637. }
  47638. faceAdjacencies.edges[edgeIndex] = otherIndex;
  47639. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  47640. faceAdjacencies.edgesConnectedCount++;
  47641. otherFaceAdjacencies.edgesConnectedCount++;
  47642. if (faceAdjacencies.edgesConnectedCount === 3) {
  47643. break;
  47644. }
  47645. }
  47646. }
  47647. }
  47648. // Create lines
  47649. for (index = 0; index < adjacencies.length; index++) {
  47650. // 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
  47651. var current = adjacencies[index];
  47652. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  47653. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  47654. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  47655. }
  47656. // Merge into a single mesh
  47657. var engine = this._source.getScene().getEngine();
  47658. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  47659. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  47660. this._ib = engine.createIndexBuffer(this._linesIndices);
  47661. this._indicesCount = this._linesIndices.length;
  47662. };
  47663. EdgesRenderer.prototype.render = function () {
  47664. if (!this._lineShader.isReady()) {
  47665. return;
  47666. }
  47667. var scene = this._source.getScene();
  47668. var engine = scene.getEngine();
  47669. this._lineShader._preBind();
  47670. // VBOs
  47671. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  47672. scene.resetCachedMaterial();
  47673. this._lineShader.setColor4("color", this._source.edgesColor);
  47674. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  47675. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  47676. }
  47677. else {
  47678. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  47679. }
  47680. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  47681. this._lineShader.bind(this._source.getWorldMatrix());
  47682. // Draw order
  47683. engine.draw(true, 0, this._indicesCount);
  47684. this._lineShader.unbind();
  47685. engine.setDepthWrite(true);
  47686. };
  47687. return EdgesRenderer;
  47688. }());
  47689. BABYLON.EdgesRenderer = EdgesRenderer;
  47690. })(BABYLON || (BABYLON = {}));
  47691. var BABYLON;
  47692. (function (BABYLON) {
  47693. (function (TonemappingOperator) {
  47694. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  47695. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  47696. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  47697. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  47698. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  47699. var TonemappingOperator = BABYLON.TonemappingOperator;
  47700. ;
  47701. var TonemapPostProcess = (function (_super) {
  47702. __extends(TonemapPostProcess, _super);
  47703. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  47704. var _this = this;
  47705. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  47706. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  47707. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  47708. this._operator = _operator;
  47709. this.exposureAdjustment = exposureAdjustment;
  47710. var defines = "#define ";
  47711. if (this._operator === TonemappingOperator.Hable)
  47712. defines += "HABLE_TONEMAPPING";
  47713. else if (this._operator === TonemappingOperator.Reinhard)
  47714. defines += "REINHARD_TONEMAPPING";
  47715. else if (this._operator === TonemappingOperator.HejiDawson)
  47716. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  47717. else if (this._operator === TonemappingOperator.Photographic)
  47718. defines += "PHOTOGRAPHIC_TONEMAPPING";
  47719. //sadly a second call to create the effect.
  47720. this.updateEffect(defines);
  47721. this.onApply = function (effect) {
  47722. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  47723. };
  47724. }
  47725. return TonemapPostProcess;
  47726. }(BABYLON.PostProcess));
  47727. BABYLON.TonemapPostProcess = TonemapPostProcess;
  47728. })(BABYLON || (BABYLON = {}));
  47729. var BABYLON;
  47730. (function (BABYLON) {
  47731. var ReflectionProbe = (function () {
  47732. function ReflectionProbe(name, size, scene, generateMipMaps) {
  47733. var _this = this;
  47734. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47735. this.name = name;
  47736. this._viewMatrix = BABYLON.Matrix.Identity();
  47737. this._target = BABYLON.Vector3.Zero();
  47738. this._add = BABYLON.Vector3.Zero();
  47739. this.invertYAxis = false;
  47740. this.position = BABYLON.Vector3.Zero();
  47741. this._scene = scene;
  47742. this._scene.reflectionProbes.push(this);
  47743. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  47744. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  47745. switch (faceIndex) {
  47746. case 0:
  47747. _this._add.copyFromFloats(1, 0, 0);
  47748. break;
  47749. case 1:
  47750. _this._add.copyFromFloats(-1, 0, 0);
  47751. break;
  47752. case 2:
  47753. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  47754. break;
  47755. case 3:
  47756. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  47757. break;
  47758. case 4:
  47759. _this._add.copyFromFloats(0, 0, 1);
  47760. break;
  47761. case 5:
  47762. _this._add.copyFromFloats(0, 0, -1);
  47763. break;
  47764. }
  47765. if (_this._attachedMesh) {
  47766. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  47767. }
  47768. _this.position.addToRef(_this._add, _this._target);
  47769. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  47770. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  47771. });
  47772. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  47773. scene.updateTransformMatrix(true);
  47774. });
  47775. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  47776. }
  47777. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  47778. get: function () {
  47779. return this._renderTargetTexture.refreshRate;
  47780. },
  47781. set: function (value) {
  47782. this._renderTargetTexture.refreshRate = value;
  47783. },
  47784. enumerable: true,
  47785. configurable: true
  47786. });
  47787. ReflectionProbe.prototype.getScene = function () {
  47788. return this._scene;
  47789. };
  47790. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  47791. get: function () {
  47792. return this._renderTargetTexture;
  47793. },
  47794. enumerable: true,
  47795. configurable: true
  47796. });
  47797. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  47798. get: function () {
  47799. return this._renderTargetTexture.renderList;
  47800. },
  47801. enumerable: true,
  47802. configurable: true
  47803. });
  47804. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  47805. this._attachedMesh = mesh;
  47806. };
  47807. ReflectionProbe.prototype.dispose = function () {
  47808. var index = this._scene.reflectionProbes.indexOf(this);
  47809. if (index !== -1) {
  47810. // Remove from the scene if found
  47811. this._scene.reflectionProbes.splice(index, 1);
  47812. }
  47813. if (this._renderTargetTexture) {
  47814. this._renderTargetTexture.dispose();
  47815. this._renderTargetTexture = null;
  47816. }
  47817. };
  47818. return ReflectionProbe;
  47819. }());
  47820. BABYLON.ReflectionProbe = ReflectionProbe;
  47821. })(BABYLON || (BABYLON = {}));
  47822. var BABYLON;
  47823. (function (BABYLON) {
  47824. var SolidParticle = (function () {
  47825. /**
  47826. * Creates a Solid Particle object.
  47827. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  47828. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  47829. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  47830. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  47831. * `shapeId` (integer) is the model shape identifier in the SPS.
  47832. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  47833. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  47834. */
  47835. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  47836. this.idx = 0; // particle global index
  47837. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  47838. this.position = BABYLON.Vector3.Zero(); // position
  47839. this.rotation = BABYLON.Vector3.Zero(); // rotation
  47840. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  47841. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  47842. this.velocity = BABYLON.Vector3.Zero(); // velocity
  47843. this.alive = true; // alive
  47844. this.isVisible = true; // visibility
  47845. this._pos = 0; // index of this particle in the global "positions" array
  47846. this.shapeId = 0; // model shape id
  47847. this.idxInShape = 0; // index of the particle in its shape id
  47848. this.idx = particleIndex;
  47849. this._pos = positionIndex;
  47850. this._model = model;
  47851. this.shapeId = shapeId;
  47852. this.idxInShape = idxInShape;
  47853. this._sps = sps;
  47854. if (modelBoundingInfo) {
  47855. this._modelBoundingInfo = modelBoundingInfo;
  47856. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  47857. }
  47858. }
  47859. Object.defineProperty(SolidParticle.prototype, "scale", {
  47860. /**
  47861. * legacy support, changed scale to scaling
  47862. */
  47863. get: function () {
  47864. return this.scaling;
  47865. },
  47866. set: function (scale) {
  47867. this.scaling = scale;
  47868. },
  47869. enumerable: true,
  47870. configurable: true
  47871. });
  47872. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  47873. /**
  47874. * legacy support, changed quaternion to rotationQuaternion
  47875. */
  47876. get: function () {
  47877. return this.rotationQuaternion;
  47878. },
  47879. set: function (q) {
  47880. this.rotationQuaternion = q;
  47881. },
  47882. enumerable: true,
  47883. configurable: true
  47884. });
  47885. /**
  47886. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  47887. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  47888. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  47889. */
  47890. SolidParticle.prototype.intersectsMesh = function (target) {
  47891. if (!this._boundingInfo || !target._boundingInfo) {
  47892. return false;
  47893. }
  47894. if (this._sps._bSphereOnly) {
  47895. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  47896. }
  47897. return this._boundingInfo.intersects(target._boundingInfo, false);
  47898. };
  47899. return SolidParticle;
  47900. }());
  47901. BABYLON.SolidParticle = SolidParticle;
  47902. var ModelShape = (function () {
  47903. /**
  47904. * 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.
  47905. * SPS internal tool, don't use it manually.
  47906. */
  47907. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  47908. this.shapeID = id;
  47909. this._shape = shape;
  47910. this._shapeUV = shapeUV;
  47911. this._positionFunction = posFunction;
  47912. this._vertexFunction = vtxFunction;
  47913. }
  47914. return ModelShape;
  47915. }());
  47916. BABYLON.ModelShape = ModelShape;
  47917. })(BABYLON || (BABYLON = {}));
  47918. var BABYLON;
  47919. (function (BABYLON) {
  47920. /**
  47921. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  47922. */
  47923. var SolidParticleSystem = (function () {
  47924. /**
  47925. * Creates a SPS (Solid Particle System) object.
  47926. * `name` (String) is the SPS name, this will be the underlying mesh name.
  47927. * `scene` (Scene) is the scene in which the SPS is added.
  47928. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  47929. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  47930. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  47931. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  47932. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  47933. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  47934. */
  47935. function SolidParticleSystem(name, scene, options) {
  47936. // public members
  47937. /**
  47938. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  47939. * Example : var p = SPS.particles[i];
  47940. */
  47941. this.particles = new Array();
  47942. /**
  47943. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  47944. */
  47945. this.nbParticles = 0;
  47946. /**
  47947. * If the particles must ever face the camera (default false). Useful for planar particles.
  47948. */
  47949. this.billboard = false;
  47950. /**
  47951. * Recompute normals when adding a shape
  47952. */
  47953. this.recomputeNormals = true;
  47954. /**
  47955. * This a counter ofr your own usage. It's not set by any SPS functions.
  47956. */
  47957. this.counter = 0;
  47958. /**
  47959. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  47960. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  47961. */
  47962. this.vars = {};
  47963. this._positions = new Array();
  47964. this._indices = new Array();
  47965. this._normals = new Array();
  47966. this._colors = new Array();
  47967. this._uvs = new Array();
  47968. this._index = 0; // indices index
  47969. this._updatable = true;
  47970. this._pickable = false;
  47971. this._isVisibilityBoxLocked = false;
  47972. this._alwaysVisible = false;
  47973. this._shapeCounter = 0;
  47974. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  47975. this._color = new BABYLON.Color4(0, 0, 0, 0);
  47976. this._computeParticleColor = true;
  47977. this._computeParticleTexture = true;
  47978. this._computeParticleRotation = true;
  47979. this._computeParticleVertex = false;
  47980. this._computeBoundingBox = false;
  47981. this._cam_axisZ = BABYLON.Vector3.Zero();
  47982. this._cam_axisY = BABYLON.Vector3.Zero();
  47983. this._cam_axisX = BABYLON.Vector3.Zero();
  47984. this._axisX = BABYLON.Axis.X;
  47985. this._axisY = BABYLON.Axis.Y;
  47986. this._axisZ = BABYLON.Axis.Z;
  47987. this._camDir = BABYLON.Vector3.Zero();
  47988. this._rotMatrix = new BABYLON.Matrix();
  47989. this._invertMatrix = new BABYLON.Matrix();
  47990. this._rotated = BABYLON.Vector3.Zero();
  47991. this._quaternion = new BABYLON.Quaternion();
  47992. this._vertex = BABYLON.Vector3.Zero();
  47993. this._normal = BABYLON.Vector3.Zero();
  47994. this._yaw = 0.0;
  47995. this._pitch = 0.0;
  47996. this._roll = 0.0;
  47997. this._halfroll = 0.0;
  47998. this._halfpitch = 0.0;
  47999. this._halfyaw = 0.0;
  48000. this._sinRoll = 0.0;
  48001. this._cosRoll = 0.0;
  48002. this._sinPitch = 0.0;
  48003. this._cosPitch = 0.0;
  48004. this._sinYaw = 0.0;
  48005. this._cosYaw = 0.0;
  48006. this._w = 0.0;
  48007. this._minimum = BABYLON.Tmp.Vector3[0];
  48008. this._maximum = BABYLON.Tmp.Vector3[1];
  48009. this._scale = BABYLON.Tmp.Vector3[2];
  48010. this._translation = BABYLON.Tmp.Vector3[3];
  48011. this._minBbox = BABYLON.Tmp.Vector3[4];
  48012. this._maxBbox = BABYLON.Tmp.Vector3[5];
  48013. this._particlesIntersect = false;
  48014. this._bSphereOnly = false;
  48015. this._bSphereRadiusFactor = 1.0;
  48016. this.name = name;
  48017. this._scene = scene;
  48018. this._camera = scene.activeCamera;
  48019. this._pickable = options ? options.isPickable : false;
  48020. this._particlesIntersect = options ? options.particleIntersection : false;
  48021. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  48022. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  48023. if (options && options.updatable) {
  48024. this._updatable = options.updatable;
  48025. }
  48026. else {
  48027. this._updatable = true;
  48028. }
  48029. if (this._pickable) {
  48030. this.pickedParticles = [];
  48031. }
  48032. }
  48033. /**
  48034. * Builds the SPS underlying mesh. Returns a standard Mesh.
  48035. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  48036. */
  48037. SolidParticleSystem.prototype.buildMesh = function () {
  48038. if (this.nbParticles === 0) {
  48039. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  48040. this.addShape(triangle, 1);
  48041. triangle.dispose();
  48042. }
  48043. this._positions32 = new Float32Array(this._positions);
  48044. this._uvs32 = new Float32Array(this._uvs);
  48045. this._colors32 = new Float32Array(this._colors);
  48046. if (this.recomputeNormals) {
  48047. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  48048. }
  48049. this._normals32 = new Float32Array(this._normals);
  48050. this._fixedNormal32 = new Float32Array(this._normals);
  48051. var vertexData = new BABYLON.VertexData();
  48052. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  48053. vertexData.indices = this._indices;
  48054. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  48055. if (this._uvs32) {
  48056. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  48057. ;
  48058. }
  48059. if (this._colors32) {
  48060. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  48061. }
  48062. var mesh = new BABYLON.Mesh(this.name, this._scene);
  48063. vertexData.applyToMesh(mesh, this._updatable);
  48064. this.mesh = mesh;
  48065. this.mesh.isPickable = this._pickable;
  48066. // free memory
  48067. this._positions = null;
  48068. this._normals = null;
  48069. this._uvs = null;
  48070. this._colors = null;
  48071. if (!this._updatable) {
  48072. this.particles.length = 0;
  48073. }
  48074. return mesh;
  48075. };
  48076. /**
  48077. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  48078. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  48079. * Thus the particles generated from `digest()` have their property `position` set yet.
  48080. * `mesh` ( Mesh ) is the mesh to be digested
  48081. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  48082. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  48083. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  48084. */
  48085. SolidParticleSystem.prototype.digest = function (mesh, options) {
  48086. var size = (options && options.facetNb) || 1;
  48087. var number = (options && options.number);
  48088. var delta = (options && options.delta) || 0;
  48089. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48090. var meshInd = mesh.getIndices();
  48091. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48092. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48093. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48094. var f = 0; // facet counter
  48095. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  48096. // compute size from number
  48097. if (number) {
  48098. number = (number > totalFacets) ? totalFacets : number;
  48099. size = Math.round(totalFacets / number);
  48100. delta = 0;
  48101. }
  48102. else {
  48103. size = (size > totalFacets) ? totalFacets : size;
  48104. }
  48105. var facetPos = []; // submesh positions
  48106. var facetInd = []; // submesh indices
  48107. var facetUV = []; // submesh UV
  48108. var facetCol = []; // submesh colors
  48109. var barycenter = BABYLON.Tmp.Vector3[0];
  48110. var rand;
  48111. var sizeO = size;
  48112. while (f < totalFacets) {
  48113. size = sizeO + Math.floor((1 + delta) * Math.random());
  48114. if (f > totalFacets - size) {
  48115. size = totalFacets - f;
  48116. }
  48117. // reset temp arrays
  48118. facetPos.length = 0;
  48119. facetInd.length = 0;
  48120. facetUV.length = 0;
  48121. facetCol.length = 0;
  48122. // iterate over "size" facets
  48123. var fi = 0;
  48124. for (var j = f * 3; j < (f + size) * 3; j++) {
  48125. facetInd.push(fi);
  48126. var i = meshInd[j];
  48127. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  48128. if (meshUV) {
  48129. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  48130. }
  48131. if (meshCol) {
  48132. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  48133. }
  48134. fi++;
  48135. }
  48136. // create a model shape for each single particle
  48137. var idx = this.nbParticles;
  48138. var shape = this._posToShape(facetPos);
  48139. var shapeUV = this._uvsToShapeUV(facetUV);
  48140. // compute the barycenter of the shape
  48141. var v;
  48142. for (v = 0; v < shape.length; v++) {
  48143. barycenter.addInPlace(shape[v]);
  48144. }
  48145. barycenter.scaleInPlace(1 / shape.length);
  48146. // shift the shape from its barycenter to the origin
  48147. for (v = 0; v < shape.length; v++) {
  48148. shape[v].subtractInPlace(barycenter);
  48149. }
  48150. var bInfo;
  48151. if (this._particlesIntersect) {
  48152. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  48153. }
  48154. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  48155. // add the particle in the SPS
  48156. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  48157. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0, bInfo);
  48158. // initialize the particle position
  48159. this.particles[this.nbParticles].position.addInPlace(barycenter);
  48160. this._index += shape.length;
  48161. idx++;
  48162. this.nbParticles++;
  48163. this._shapeCounter++;
  48164. f += size;
  48165. }
  48166. return this;
  48167. };
  48168. //reset copy
  48169. SolidParticleSystem.prototype._resetCopy = function () {
  48170. this._copy.position.x = 0;
  48171. this._copy.position.y = 0;
  48172. this._copy.position.z = 0;
  48173. this._copy.rotation.x = 0;
  48174. this._copy.rotation.y = 0;
  48175. this._copy.rotation.z = 0;
  48176. this._copy.rotationQuaternion = null;
  48177. this._copy.scaling.x = 1;
  48178. this._copy.scaling.y = 1;
  48179. this._copy.scaling.z = 1;
  48180. this._copy.uvs.x = 0;
  48181. this._copy.uvs.y = 0;
  48182. this._copy.uvs.z = 1;
  48183. this._copy.uvs.w = 1;
  48184. this._copy.color = null;
  48185. };
  48186. // _meshBuilder : inserts the shape model in the global SPS mesh
  48187. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  48188. var i;
  48189. var u = 0;
  48190. var c = 0;
  48191. var n = 0;
  48192. this._resetCopy();
  48193. if (options && options.positionFunction) {
  48194. options.positionFunction(this._copy, idx, idxInShape);
  48195. }
  48196. if (this._copy.rotationQuaternion) {
  48197. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  48198. }
  48199. else {
  48200. this._yaw = this._copy.rotation.y;
  48201. this._pitch = this._copy.rotation.x;
  48202. this._roll = this._copy.rotation.z;
  48203. this._quaternionRotationYPR();
  48204. }
  48205. this._quaternionToRotationMatrix();
  48206. for (i = 0; i < shape.length; i++) {
  48207. this._vertex.x = shape[i].x;
  48208. this._vertex.y = shape[i].y;
  48209. this._vertex.z = shape[i].z;
  48210. if (options && options.vertexFunction) {
  48211. options.vertexFunction(this._copy, this._vertex, i);
  48212. }
  48213. this._vertex.x *= this._copy.scaling.x;
  48214. this._vertex.y *= this._copy.scaling.y;
  48215. this._vertex.z *= this._copy.scaling.z;
  48216. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  48217. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  48218. if (meshUV) {
  48219. 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);
  48220. u += 2;
  48221. }
  48222. if (this._copy.color) {
  48223. this._color = this._copy.color;
  48224. }
  48225. else if (meshCol && meshCol[c] !== undefined) {
  48226. this._color.r = meshCol[c];
  48227. this._color.g = meshCol[c + 1];
  48228. this._color.b = meshCol[c + 2];
  48229. this._color.a = meshCol[c + 3];
  48230. }
  48231. else {
  48232. this._color.r = 1;
  48233. this._color.g = 1;
  48234. this._color.b = 1;
  48235. this._color.a = 1;
  48236. }
  48237. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  48238. c += 4;
  48239. if (!this.recomputeNormals && meshNor) {
  48240. this._normal.x = meshNor[n];
  48241. this._normal.y = meshNor[n + 1];
  48242. this._normal.z = meshNor[n + 2];
  48243. BABYLON.Vector3.TransformCoordinatesToRef(this._normal, this._rotMatrix, this._normal);
  48244. normals.push(this._normal.x, this._normal.y, this._normal.z);
  48245. n += 3;
  48246. }
  48247. }
  48248. for (i = 0; i < meshInd.length; i++) {
  48249. indices.push(p + meshInd[i]);
  48250. }
  48251. if (this._pickable) {
  48252. var nbfaces = meshInd.length / 3;
  48253. for (i = 0; i < nbfaces; i++) {
  48254. this.pickedParticles.push({ idx: idx, faceId: i });
  48255. }
  48256. }
  48257. };
  48258. // returns a shape array from positions array
  48259. SolidParticleSystem.prototype._posToShape = function (positions) {
  48260. var shape = [];
  48261. for (var i = 0; i < positions.length; i += 3) {
  48262. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  48263. }
  48264. return shape;
  48265. };
  48266. // returns a shapeUV array from a Vector4 uvs
  48267. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  48268. var shapeUV = [];
  48269. if (uvs) {
  48270. for (var i = 0; i < uvs.length; i++)
  48271. shapeUV.push(uvs[i]);
  48272. }
  48273. return shapeUV;
  48274. };
  48275. // adds a new particle object in the particles array
  48276. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  48277. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo));
  48278. };
  48279. /**
  48280. * Adds some particles to the SPS from the model shape. Returns the shape id.
  48281. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  48282. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  48283. * `nb` (positive integer) the number of particles to be created from this model
  48284. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  48285. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  48286. */
  48287. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  48288. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48289. var meshInd = mesh.getIndices();
  48290. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48291. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48292. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48293. var bbInfo;
  48294. if (this._particlesIntersect) {
  48295. bbInfo = mesh.getBoundingInfo();
  48296. }
  48297. var shape = this._posToShape(meshPos);
  48298. var shapeUV = this._uvsToShapeUV(meshUV);
  48299. var posfunc = options ? options.positionFunction : null;
  48300. var vtxfunc = options ? options.vertexFunction : null;
  48301. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  48302. // particles
  48303. var idx = this.nbParticles;
  48304. for (var i = 0; i < nb; i++) {
  48305. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  48306. if (this._updatable) {
  48307. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i, bbInfo);
  48308. }
  48309. this._index += shape.length;
  48310. idx++;
  48311. }
  48312. this.nbParticles += nb;
  48313. this._shapeCounter++;
  48314. return this._shapeCounter - 1;
  48315. };
  48316. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  48317. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  48318. this._resetCopy();
  48319. if (particle._model._positionFunction) {
  48320. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  48321. }
  48322. if (this._copy.rotationQuaternion) {
  48323. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  48324. }
  48325. else {
  48326. this._yaw = this._copy.rotation.y;
  48327. this._pitch = this._copy.rotation.x;
  48328. this._roll = this._copy.rotation.z;
  48329. this._quaternionRotationYPR();
  48330. }
  48331. this._quaternionToRotationMatrix();
  48332. this._shape = particle._model._shape;
  48333. for (var pt = 0; pt < this._shape.length; pt++) {
  48334. this._vertex.x = this._shape[pt].x;
  48335. this._vertex.y = this._shape[pt].y;
  48336. this._vertex.z = this._shape[pt].z;
  48337. if (particle._model._vertexFunction) {
  48338. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  48339. }
  48340. this._vertex.x *= this._copy.scaling.x;
  48341. this._vertex.y *= this._copy.scaling.y;
  48342. this._vertex.z *= this._copy.scaling.z;
  48343. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  48344. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  48345. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  48346. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  48347. }
  48348. particle.position.x = 0.0;
  48349. particle.position.y = 0.0;
  48350. particle.position.z = 0.0;
  48351. particle.rotation.x = 0.0;
  48352. particle.rotation.y = 0.0;
  48353. particle.rotation.z = 0.0;
  48354. particle.rotationQuaternion = null;
  48355. particle.scaling.x = 1.0;
  48356. particle.scaling.y = 1.0;
  48357. particle.scaling.z = 1.0;
  48358. };
  48359. /**
  48360. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  48361. */
  48362. SolidParticleSystem.prototype.rebuildMesh = function () {
  48363. for (var p = 0; p < this.particles.length; p++) {
  48364. this._rebuildParticle(this.particles[p]);
  48365. }
  48366. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  48367. };
  48368. /**
  48369. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  48370. * This method calls `updateParticle()` for each particle of the SPS.
  48371. * For an animated SPS, it is usually called within the render loop.
  48372. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  48373. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  48374. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  48375. */
  48376. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  48377. if (start === void 0) { start = 0; }
  48378. if (end === void 0) { end = this.nbParticles - 1; }
  48379. if (update === void 0) { update = true; }
  48380. if (!this._updatable) {
  48381. return;
  48382. }
  48383. // custom beforeUpdate
  48384. this.beforeUpdateParticles(start, end, update);
  48385. this._cam_axisX.x = 1.0;
  48386. this._cam_axisX.y = 0.0;
  48387. this._cam_axisX.z = 0.0;
  48388. this._cam_axisY.x = 0.0;
  48389. this._cam_axisY.y = 1.0;
  48390. this._cam_axisY.z = 0.0;
  48391. this._cam_axisZ.x = 0.0;
  48392. this._cam_axisZ.y = 0.0;
  48393. this._cam_axisZ.z = 1.0;
  48394. // if the particles will always face the camera
  48395. if (this.billboard) {
  48396. // compute the camera position and un-rotate it by the current mesh rotation
  48397. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  48398. this._quaternionToRotationMatrix();
  48399. this._rotMatrix.invertToRef(this._invertMatrix);
  48400. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  48401. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  48402. this._cam_axisZ.normalize();
  48403. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  48404. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  48405. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  48406. this._cam_axisY.normalize();
  48407. this._cam_axisX.normalize();
  48408. }
  48409. }
  48410. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  48411. var idx = 0;
  48412. var index = 0;
  48413. var colidx = 0;
  48414. var colorIndex = 0;
  48415. var uvidx = 0;
  48416. var uvIndex = 0;
  48417. var pt = 0;
  48418. if (this._computeBoundingBox) {
  48419. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  48420. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  48421. }
  48422. // particle loop
  48423. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  48424. for (var p = start; p <= end; p++) {
  48425. this._particle = this.particles[p];
  48426. this._shape = this._particle._model._shape;
  48427. this._shapeUV = this._particle._model._shapeUV;
  48428. // call to custom user function to update the particle properties
  48429. this.updateParticle(this._particle);
  48430. if (this._particle.isVisible) {
  48431. // particle rotation matrix
  48432. if (this.billboard) {
  48433. this._particle.rotation.x = 0.0;
  48434. this._particle.rotation.y = 0.0;
  48435. }
  48436. if (this._computeParticleRotation || this.billboard) {
  48437. if (this._particle.rotationQuaternion) {
  48438. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  48439. }
  48440. else {
  48441. this._yaw = this._particle.rotation.y;
  48442. this._pitch = this._particle.rotation.x;
  48443. this._roll = this._particle.rotation.z;
  48444. this._quaternionRotationYPR();
  48445. }
  48446. this._quaternionToRotationMatrix();
  48447. }
  48448. // particle vertex loop
  48449. for (pt = 0; pt < this._shape.length; pt++) {
  48450. idx = index + pt * 3;
  48451. colidx = colorIndex + pt * 4;
  48452. uvidx = uvIndex + pt * 2;
  48453. this._vertex.x = this._shape[pt].x;
  48454. this._vertex.y = this._shape[pt].y;
  48455. this._vertex.z = this._shape[pt].z;
  48456. if (this._computeParticleVertex) {
  48457. this.updateParticleVertex(this._particle, this._vertex, pt);
  48458. }
  48459. // positions
  48460. this._vertex.x *= this._particle.scaling.x;
  48461. this._vertex.y *= this._particle.scaling.y;
  48462. this._vertex.z *= this._particle.scaling.z;
  48463. 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];
  48464. 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;
  48465. 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;
  48466. 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;
  48467. 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;
  48468. 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;
  48469. 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;
  48470. if (this._computeBoundingBox) {
  48471. if (this._positions32[idx] < this._minimum.x) {
  48472. this._minimum.x = this._positions32[idx];
  48473. }
  48474. if (this._positions32[idx] > this._maximum.x) {
  48475. this._maximum.x = this._positions32[idx];
  48476. }
  48477. if (this._positions32[idx + 1] < this._minimum.y) {
  48478. this._minimum.y = this._positions32[idx + 1];
  48479. }
  48480. if (this._positions32[idx + 1] > this._maximum.y) {
  48481. this._maximum.y = this._positions32[idx + 1];
  48482. }
  48483. if (this._positions32[idx + 2] < this._minimum.z) {
  48484. this._minimum.z = this._positions32[idx + 2];
  48485. }
  48486. if (this._positions32[idx + 2] > this._maximum.z) {
  48487. this._maximum.z = this._positions32[idx + 2];
  48488. }
  48489. }
  48490. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  48491. if (!this._computeParticleVertex) {
  48492. this._normal.x = this._fixedNormal32[idx];
  48493. this._normal.y = this._fixedNormal32[idx + 1];
  48494. this._normal.z = this._fixedNormal32[idx + 2];
  48495. 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];
  48496. 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;
  48497. 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;
  48498. 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;
  48499. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  48500. 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;
  48501. 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;
  48502. }
  48503. if (this._computeParticleColor) {
  48504. this._colors32[colidx] = this._particle.color.r;
  48505. this._colors32[colidx + 1] = this._particle.color.g;
  48506. this._colors32[colidx + 2] = this._particle.color.b;
  48507. this._colors32[colidx + 3] = this._particle.color.a;
  48508. }
  48509. if (this._computeParticleTexture) {
  48510. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  48511. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  48512. }
  48513. }
  48514. }
  48515. else {
  48516. for (pt = 0; pt < this._shape.length; pt++) {
  48517. idx = index + pt * 3;
  48518. colidx = colorIndex + pt * 4;
  48519. uvidx = uvIndex + pt * 2;
  48520. this._positions32[idx] = this._camera.position.x;
  48521. this._positions32[idx + 1] = this._camera.position.y;
  48522. this._positions32[idx + 2] = this._camera.position.z;
  48523. this._normals32[idx] = 0.0;
  48524. this._normals32[idx + 1] = 0.0;
  48525. this._normals32[idx + 2] = 0.0;
  48526. if (this._computeParticleColor) {
  48527. this._colors32[colidx] = this._particle.color.r;
  48528. this._colors32[colidx + 1] = this._particle.color.g;
  48529. this._colors32[colidx + 2] = this._particle.color.b;
  48530. this._colors32[colidx + 3] = this._particle.color.a;
  48531. }
  48532. if (this._computeParticleTexture) {
  48533. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  48534. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  48535. }
  48536. }
  48537. }
  48538. // if the particle intersections must be computed : update the bbInfo
  48539. if (this._particlesIntersect) {
  48540. var bInfo = this._particle._boundingInfo;
  48541. var bBox = bInfo.boundingBox;
  48542. var bSphere = bInfo.boundingSphere;
  48543. if (!this._bSphereOnly) {
  48544. // place, scale and rotate the particle bbox within the SPS local system, then update it
  48545. for (var b = 0; b < bBox.vectors.length; b++) {
  48546. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  48547. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  48548. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  48549. 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];
  48550. 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;
  48551. 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;
  48552. 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;
  48553. 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;
  48554. 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;
  48555. 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;
  48556. }
  48557. bBox._update(this.mesh._worldMatrix);
  48558. }
  48559. // place and scale the particle bouding sphere in the SPS local system, then update it
  48560. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  48561. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  48562. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  48563. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  48564. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  48565. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  48566. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  48567. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  48568. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  48569. 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));
  48570. bSphere._update(this.mesh._worldMatrix);
  48571. }
  48572. // increment indexes for the next particle
  48573. index = idx + 3;
  48574. colorIndex = colidx + 4;
  48575. uvIndex = uvidx + 2;
  48576. }
  48577. // if the VBO must be updated
  48578. if (update) {
  48579. if (this._computeParticleColor) {
  48580. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  48581. }
  48582. if (this._computeParticleTexture) {
  48583. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  48584. }
  48585. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  48586. if (!this.mesh.areNormalsFrozen) {
  48587. if (this._computeParticleVertex) {
  48588. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  48589. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  48590. for (var i = 0; i < this._normals32.length; i++) {
  48591. this._fixedNormal32[i] = this._normals32[i];
  48592. }
  48593. }
  48594. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  48595. }
  48596. }
  48597. if (this._computeBoundingBox) {
  48598. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  48599. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  48600. }
  48601. this.afterUpdateParticles(start, end, update);
  48602. };
  48603. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  48604. this._halfroll = this._roll * 0.5;
  48605. this._halfpitch = this._pitch * 0.5;
  48606. this._halfyaw = this._yaw * 0.5;
  48607. this._sinRoll = Math.sin(this._halfroll);
  48608. this._cosRoll = Math.cos(this._halfroll);
  48609. this._sinPitch = Math.sin(this._halfpitch);
  48610. this._cosPitch = Math.cos(this._halfpitch);
  48611. this._sinYaw = Math.sin(this._halfyaw);
  48612. this._cosYaw = Math.cos(this._halfyaw);
  48613. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  48614. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  48615. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  48616. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  48617. };
  48618. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  48619. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  48620. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  48621. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  48622. this._rotMatrix.m[3] = 0;
  48623. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  48624. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  48625. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  48626. this._rotMatrix.m[7] = 0;
  48627. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  48628. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  48629. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  48630. this._rotMatrix.m[11] = 0;
  48631. this._rotMatrix.m[12] = 0;
  48632. this._rotMatrix.m[13] = 0;
  48633. this._rotMatrix.m[14] = 0;
  48634. this._rotMatrix.m[15] = 1.0;
  48635. };
  48636. /**
  48637. * Disposes the SPS
  48638. */
  48639. SolidParticleSystem.prototype.dispose = function () {
  48640. this.mesh.dispose();
  48641. this.vars = null;
  48642. // drop references to internal big arrays for the GC
  48643. this._positions = null;
  48644. this._indices = null;
  48645. this._normals = null;
  48646. this._uvs = null;
  48647. this._colors = null;
  48648. this._positions32 = null;
  48649. this._normals32 = null;
  48650. this._fixedNormal32 = null;
  48651. this._uvs32 = null;
  48652. this._colors32 = null;
  48653. this.pickedParticles = null;
  48654. };
  48655. /**
  48656. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  48657. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48658. */
  48659. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  48660. if (!this._isVisibilityBoxLocked) {
  48661. this.mesh.refreshBoundingInfo();
  48662. }
  48663. };
  48664. /**
  48665. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  48666. * @param size the size (float) of the visibility box
  48667. * note : this doesn't lock the SPS mesh bounding box.
  48668. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48669. */
  48670. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  48671. var vis = size / 2;
  48672. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  48673. };
  48674. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  48675. // getter and setter
  48676. get: function () {
  48677. return this._alwaysVisible;
  48678. },
  48679. /**
  48680. * Sets the SPS as always visible or not
  48681. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48682. */
  48683. set: function (val) {
  48684. this._alwaysVisible = val;
  48685. this.mesh.alwaysSelectAsActiveMesh = val;
  48686. },
  48687. enumerable: true,
  48688. configurable: true
  48689. });
  48690. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  48691. get: function () {
  48692. return this._isVisibilityBoxLocked;
  48693. },
  48694. /**
  48695. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  48696. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48697. */
  48698. set: function (val) {
  48699. this._isVisibilityBoxLocked = val;
  48700. this.mesh.getBoundingInfo().isLocked = val;
  48701. },
  48702. enumerable: true,
  48703. configurable: true
  48704. });
  48705. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  48706. // getters
  48707. get: function () {
  48708. return this._computeParticleRotation;
  48709. },
  48710. // Optimizer setters
  48711. /**
  48712. * Tells to `setParticles()` to compute the particle rotations or not.
  48713. * Default value : true. The SPS is faster when it's set to false.
  48714. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  48715. */
  48716. set: function (val) {
  48717. this._computeParticleRotation = val;
  48718. },
  48719. enumerable: true,
  48720. configurable: true
  48721. });
  48722. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  48723. get: function () {
  48724. return this._computeParticleColor;
  48725. },
  48726. /**
  48727. * Tells to `setParticles()` to compute the particle colors or not.
  48728. * Default value : true. The SPS is faster when it's set to false.
  48729. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  48730. */
  48731. set: function (val) {
  48732. this._computeParticleColor = val;
  48733. },
  48734. enumerable: true,
  48735. configurable: true
  48736. });
  48737. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  48738. get: function () {
  48739. return this._computeParticleTexture;
  48740. },
  48741. /**
  48742. * Tells to `setParticles()` to compute the particle textures or not.
  48743. * Default value : true. The SPS is faster when it's set to false.
  48744. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  48745. */
  48746. set: function (val) {
  48747. this._computeParticleTexture = val;
  48748. },
  48749. enumerable: true,
  48750. configurable: true
  48751. });
  48752. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  48753. get: function () {
  48754. return this._computeParticleVertex;
  48755. },
  48756. /**
  48757. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  48758. * Default value : false. The SPS is faster when it's set to false.
  48759. * Note : the particle custom vertex positions aren't stored values.
  48760. */
  48761. set: function (val) {
  48762. this._computeParticleVertex = val;
  48763. },
  48764. enumerable: true,
  48765. configurable: true
  48766. });
  48767. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  48768. get: function () {
  48769. return this._computeBoundingBox;
  48770. },
  48771. /**
  48772. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  48773. */
  48774. set: function (val) {
  48775. this._computeBoundingBox = val;
  48776. },
  48777. enumerable: true,
  48778. configurable: true
  48779. });
  48780. // =======================================================================
  48781. // Particle behavior logic
  48782. // these following methods may be overwritten by the user to fit his needs
  48783. /**
  48784. * This function does nothing. It may be overwritten to set all the particle first values.
  48785. * The SPS doesn't call this function, you may have to call it by your own.
  48786. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48787. */
  48788. SolidParticleSystem.prototype.initParticles = function () {
  48789. };
  48790. /**
  48791. * This function does nothing. It may be overwritten to recycle a particle.
  48792. * The SPS doesn't call this function, you may have to call it by your own.
  48793. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48794. */
  48795. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  48796. return particle;
  48797. };
  48798. /**
  48799. * Updates a particle : this function should be overwritten by the user.
  48800. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  48801. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48802. * ex : just set a particle position or velocity and recycle conditions
  48803. */
  48804. SolidParticleSystem.prototype.updateParticle = function (particle) {
  48805. return particle;
  48806. };
  48807. /**
  48808. * Updates a vertex of a particle : it can be overwritten by the user.
  48809. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  48810. * @param particle the current particle
  48811. * @param vertex the current index of the current particle
  48812. * @param pt the index of the current vertex in the particle shape
  48813. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  48814. * ex : just set a vertex particle position
  48815. */
  48816. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  48817. return vertex;
  48818. };
  48819. /**
  48820. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  48821. * This does nothing and may be overwritten by the user.
  48822. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48823. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48824. * @param update the boolean update value actually passed to setParticles()
  48825. */
  48826. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  48827. };
  48828. /**
  48829. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  48830. * This will be passed three parameters.
  48831. * This does nothing and may be overwritten by the user.
  48832. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48833. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48834. * @param update the boolean update value actually passed to setParticles()
  48835. */
  48836. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  48837. };
  48838. return SolidParticleSystem;
  48839. }());
  48840. BABYLON.SolidParticleSystem = SolidParticleSystem;
  48841. })(BABYLON || (BABYLON = {}));
  48842. var BABYLON;
  48843. (function (BABYLON) {
  48844. var Internals;
  48845. (function (Internals) {
  48846. var FileFaceOrientation = (function () {
  48847. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  48848. this.name = name;
  48849. this.worldAxisForNormal = worldAxisForNormal;
  48850. this.worldAxisForFileX = worldAxisForFileX;
  48851. this.worldAxisForFileY = worldAxisForFileY;
  48852. }
  48853. return FileFaceOrientation;
  48854. }());
  48855. ;
  48856. /**
  48857. * Helper class dealing with the extraction of spherical polynomial dataArray
  48858. * from a cube map.
  48859. */
  48860. var CubeMapToSphericalPolynomialTools = (function () {
  48861. function CubeMapToSphericalPolynomialTools() {
  48862. }
  48863. /**
  48864. * Converts a cubemap to the according Spherical Polynomial data.
  48865. * This extracts the first 3 orders only as they are the only one used in the lighting.
  48866. *
  48867. * @param cubeInfo The Cube map to extract the information from.
  48868. * @return The Spherical Polynomial data.
  48869. */
  48870. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  48871. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  48872. var totalSolidAngle = 0.0;
  48873. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  48874. var du = 2.0 / cubeInfo.size;
  48875. var dv = du;
  48876. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  48877. var minUV = du * 0.5 - 1.0;
  48878. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48879. var fileFace = this.FileFaces[faceIndex];
  48880. var dataArray = cubeInfo[fileFace.name];
  48881. var v = minUV;
  48882. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  48883. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  48884. // Because SP is still linear, so summation is fine in that basis.
  48885. for (var y = 0; y < cubeInfo.size; y++) {
  48886. var u = minUV;
  48887. for (var x = 0; x < cubeInfo.size; x++) {
  48888. // World direction (not normalised)
  48889. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  48890. worldDirection.normalize();
  48891. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  48892. if (1) {
  48893. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  48894. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  48895. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  48896. var color = new BABYLON.Color3(r, g, b);
  48897. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  48898. }
  48899. else {
  48900. if (faceIndex == 0) {
  48901. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  48902. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  48903. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  48904. }
  48905. else if (faceIndex == 1) {
  48906. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  48907. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  48908. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  48909. }
  48910. else if (faceIndex == 2) {
  48911. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  48912. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  48913. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  48914. }
  48915. else if (faceIndex == 3) {
  48916. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  48917. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  48918. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  48919. }
  48920. else if (faceIndex == 4) {
  48921. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  48922. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  48923. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  48924. }
  48925. else if (faceIndex == 5) {
  48926. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  48927. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  48928. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  48929. }
  48930. 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]);
  48931. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  48932. }
  48933. totalSolidAngle += deltaSolidAngle;
  48934. u += du;
  48935. }
  48936. v += dv;
  48937. }
  48938. }
  48939. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  48940. var correction = correctSolidAngle / totalSolidAngle;
  48941. sphericalHarmonics.scale(correction);
  48942. // Additionally scale by pi -- audit needed
  48943. sphericalHarmonics.scale(1.0 / Math.PI);
  48944. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  48945. };
  48946. CubeMapToSphericalPolynomialTools.FileFaces = [
  48947. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  48948. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  48949. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  48950. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  48951. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  48952. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  48953. ];
  48954. return CubeMapToSphericalPolynomialTools;
  48955. }());
  48956. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  48957. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48958. })(BABYLON || (BABYLON = {}));
  48959. var BABYLON;
  48960. (function (BABYLON) {
  48961. var Internals;
  48962. (function (Internals) {
  48963. /**
  48964. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  48965. */
  48966. var PanoramaToCubeMapTools = (function () {
  48967. function PanoramaToCubeMapTools() {
  48968. }
  48969. /**
  48970. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  48971. *
  48972. * @param float32Array The source data.
  48973. * @param inputWidth The width of the input panorama.
  48974. * @param inputhHeight The height of the input panorama.
  48975. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  48976. * @return The cubemap data
  48977. */
  48978. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  48979. if (!float32Array) {
  48980. throw "ConvertPanoramaToCubemap: input cannot be null";
  48981. }
  48982. if (float32Array.length != inputWidth * inputHeight * 3) {
  48983. throw "ConvertPanoramaToCubemap: input size is wrong";
  48984. }
  48985. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  48986. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  48987. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  48988. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  48989. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  48990. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  48991. return {
  48992. front: textureFront,
  48993. back: textureBack,
  48994. left: textureLeft,
  48995. right: textureRight,
  48996. up: textureUp,
  48997. down: textureDown,
  48998. size: size
  48999. };
  49000. };
  49001. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  49002. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  49003. var textureArray = new Float32Array(buffer);
  49004. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  49005. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  49006. var dy = 1 / texSize;
  49007. var fy = 0;
  49008. for (var y = 0; y < texSize; y++) {
  49009. var xv1 = faceData[0];
  49010. var xv2 = faceData[2];
  49011. for (var x = 0; x < texSize; x++) {
  49012. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  49013. v.normalize();
  49014. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  49015. // 3 channels per pixels
  49016. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  49017. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  49018. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  49019. xv1 = xv1.add(rotDX1);
  49020. xv2 = xv2.add(rotDX2);
  49021. }
  49022. fy += dy;
  49023. }
  49024. return textureArray;
  49025. };
  49026. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  49027. var theta = Math.atan2(vDir.z, vDir.x);
  49028. var phi = Math.acos(vDir.y);
  49029. while (theta < -Math.PI)
  49030. theta += 2 * Math.PI;
  49031. while (theta > Math.PI)
  49032. theta -= 2 * Math.PI;
  49033. var dx = theta / Math.PI;
  49034. var dy = phi / Math.PI;
  49035. // recenter.
  49036. dx = dx * 0.5 + 0.5;
  49037. var px = Math.round(dx * inputWidth);
  49038. if (px < 0)
  49039. px = 0;
  49040. else if (px >= inputWidth)
  49041. px = inputWidth - 1;
  49042. var py = Math.round(dy * inputHeight);
  49043. if (py < 0)
  49044. py = 0;
  49045. else if (py >= inputHeight)
  49046. py = inputHeight - 1;
  49047. var inputY = (inputHeight - py - 1);
  49048. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  49049. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  49050. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  49051. return {
  49052. r: r,
  49053. g: g,
  49054. b: b
  49055. };
  49056. };
  49057. PanoramaToCubeMapTools.FACE_FRONT = [
  49058. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  49059. new BABYLON.Vector3(1.0, -1.0, -1.0),
  49060. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  49061. new BABYLON.Vector3(1.0, 1.0, -1.0)
  49062. ];
  49063. PanoramaToCubeMapTools.FACE_BACK = [
  49064. new BABYLON.Vector3(1.0, -1.0, 1.0),
  49065. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  49066. new BABYLON.Vector3(1.0, 1.0, 1.0),
  49067. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  49068. ];
  49069. PanoramaToCubeMapTools.FACE_RIGHT = [
  49070. new BABYLON.Vector3(1.0, -1.0, -1.0),
  49071. new BABYLON.Vector3(1.0, -1.0, 1.0),
  49072. new BABYLON.Vector3(1.0, 1.0, -1.0),
  49073. new BABYLON.Vector3(1.0, 1.0, 1.0)
  49074. ];
  49075. PanoramaToCubeMapTools.FACE_LEFT = [
  49076. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  49077. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  49078. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  49079. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  49080. ];
  49081. PanoramaToCubeMapTools.FACE_DOWN = [
  49082. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  49083. new BABYLON.Vector3(1.0, 1.0, -1.0),
  49084. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  49085. new BABYLON.Vector3(1.0, 1.0, 1.0)
  49086. ];
  49087. PanoramaToCubeMapTools.FACE_UP = [
  49088. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  49089. new BABYLON.Vector3(1.0, -1.0, 1.0),
  49090. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  49091. new BABYLON.Vector3(1.0, -1.0, -1.0)
  49092. ];
  49093. return PanoramaToCubeMapTools;
  49094. }());
  49095. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  49096. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49097. })(BABYLON || (BABYLON = {}));
  49098. var BABYLON;
  49099. (function (BABYLON) {
  49100. var Internals;
  49101. (function (Internals) {
  49102. ;
  49103. /**
  49104. * This groups tools to convert HDR texture to native colors array.
  49105. */
  49106. var HDRTools = (function () {
  49107. function HDRTools() {
  49108. }
  49109. HDRTools.Ldexp = function (mantissa, exponent) {
  49110. if (exponent > 1023) {
  49111. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  49112. }
  49113. if (exponent < -1074) {
  49114. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  49115. }
  49116. return mantissa * Math.pow(2, exponent);
  49117. };
  49118. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  49119. if (exponent > 0) {
  49120. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  49121. float32array[index + 0] = red * exponent;
  49122. float32array[index + 1] = green * exponent;
  49123. float32array[index + 2] = blue * exponent;
  49124. }
  49125. else {
  49126. float32array[index + 0] = 0;
  49127. float32array[index + 1] = 0;
  49128. float32array[index + 2] = 0;
  49129. }
  49130. };
  49131. HDRTools.readStringLine = function (uint8array, startIndex) {
  49132. var line = "";
  49133. var character = "";
  49134. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  49135. character = String.fromCharCode(uint8array[i]);
  49136. if (character == "\n") {
  49137. break;
  49138. }
  49139. line += character;
  49140. }
  49141. return line;
  49142. };
  49143. /**
  49144. * Reads header information from an RGBE texture stored in a native array.
  49145. * More information on this format are available here:
  49146. * https://en.wikipedia.org/wiki/RGBE_image_format
  49147. *
  49148. * @param uint8array The binary file stored in native array.
  49149. * @return The header information.
  49150. */
  49151. HDRTools.RGBE_ReadHeader = function (uint8array) {
  49152. var height = 0;
  49153. var width = 0;
  49154. var line = this.readStringLine(uint8array, 0);
  49155. if (line[0] != '#' || line[1] != '?') {
  49156. throw "Bad HDR Format.";
  49157. }
  49158. var endOfHeader = false;
  49159. var findFormat = false;
  49160. var lineIndex = 0;
  49161. do {
  49162. lineIndex += (line.length + 1);
  49163. line = this.readStringLine(uint8array, lineIndex);
  49164. if (line == "FORMAT=32-bit_rle_rgbe") {
  49165. findFormat = true;
  49166. }
  49167. else if (line.length == 0) {
  49168. endOfHeader = true;
  49169. }
  49170. } while (!endOfHeader);
  49171. if (!findFormat) {
  49172. throw "HDR Bad header format, unsupported FORMAT";
  49173. }
  49174. lineIndex += (line.length + 1);
  49175. line = this.readStringLine(uint8array, lineIndex);
  49176. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  49177. var match = sizeRegexp.exec(line);
  49178. // TODO. Support +Y and -X if needed.
  49179. if (match.length < 3) {
  49180. throw "HDR Bad header format, no size";
  49181. }
  49182. width = parseInt(match[2]);
  49183. height = parseInt(match[1]);
  49184. if (width < 8 || width > 0x7fff) {
  49185. throw "HDR Bad header format, unsupported size";
  49186. }
  49187. lineIndex += (line.length + 1);
  49188. return {
  49189. height: height,
  49190. width: width,
  49191. dataPosition: lineIndex
  49192. };
  49193. };
  49194. /**
  49195. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  49196. * This RGBE texture needs to store the information as a panorama.
  49197. *
  49198. * More information on this format are available here:
  49199. * https://en.wikipedia.org/wiki/RGBE_image_format
  49200. *
  49201. * @param buffer The binary file stored in an array buffer.
  49202. * @param size The expected size of the extracted cubemap.
  49203. * @return The Cube Map information.
  49204. */
  49205. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  49206. var uint8array = new Uint8Array(buffer);
  49207. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  49208. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  49209. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  49210. return cubeMapData;
  49211. };
  49212. /**
  49213. * Returns the pixels data extracted from an RGBE texture.
  49214. * This pixels will be stored left to right up to down in the R G B order in one array.
  49215. *
  49216. * More information on this format are available here:
  49217. * https://en.wikipedia.org/wiki/RGBE_image_format
  49218. *
  49219. * @param uint8array The binary file stored in an array buffer.
  49220. * @param hdrInfo The header information of the file.
  49221. * @return The pixels data in RGB right to left up to down order.
  49222. */
  49223. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  49224. // Keep for multi format supports.
  49225. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  49226. };
  49227. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  49228. var num_scanlines = hdrInfo.height;
  49229. var scanline_width = hdrInfo.width;
  49230. var a, b, c, d, count;
  49231. var dataIndex = hdrInfo.dataPosition;
  49232. var index = 0, endIndex = 0, i = 0;
  49233. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  49234. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  49235. // 3 channels of 4 bytes per pixel in float.
  49236. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  49237. var resultArray = new Float32Array(resultBuffer);
  49238. // read in each successive scanline
  49239. while (num_scanlines > 0) {
  49240. a = uint8array[dataIndex++];
  49241. b = uint8array[dataIndex++];
  49242. c = uint8array[dataIndex++];
  49243. d = uint8array[dataIndex++];
  49244. if (a != 2 || b != 2 || (c & 0x80)) {
  49245. // this file is not run length encoded
  49246. throw "HDR Bad header format, not RLE";
  49247. }
  49248. if (((c << 8) | d) != scanline_width) {
  49249. throw "HDR Bad header format, wrong scan line width";
  49250. }
  49251. index = 0;
  49252. // read each of the four channels for the scanline into the buffer
  49253. for (i = 0; i < 4; i++) {
  49254. endIndex = (i + 1) * scanline_width;
  49255. while (index < endIndex) {
  49256. a = uint8array[dataIndex++];
  49257. b = uint8array[dataIndex++];
  49258. if (a > 128) {
  49259. // a run of the same value
  49260. count = a - 128;
  49261. if ((count == 0) || (count > endIndex - index)) {
  49262. throw "HDR Bad Format, bad scanline data (run)";
  49263. }
  49264. while (count-- > 0) {
  49265. scanLineArray[index++] = b;
  49266. }
  49267. }
  49268. else {
  49269. // a non-run
  49270. count = a;
  49271. if ((count == 0) || (count > endIndex - index)) {
  49272. throw "HDR Bad Format, bad scanline data (non-run)";
  49273. }
  49274. scanLineArray[index++] = b;
  49275. if (--count > 0) {
  49276. for (var j = 0; j < count; j++) {
  49277. scanLineArray[index++] = uint8array[dataIndex++];
  49278. }
  49279. }
  49280. }
  49281. }
  49282. }
  49283. // now convert data from buffer into floats
  49284. for (i = 0; i < scanline_width; i++) {
  49285. a = scanLineArray[i];
  49286. b = scanLineArray[i + scanline_width];
  49287. c = scanLineArray[i + 2 * scanline_width];
  49288. d = scanLineArray[i + 3 * scanline_width];
  49289. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  49290. }
  49291. num_scanlines--;
  49292. }
  49293. return resultArray;
  49294. };
  49295. return HDRTools;
  49296. }());
  49297. Internals.HDRTools = HDRTools;
  49298. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49299. })(BABYLON || (BABYLON = {}));
  49300. //_______________________________________________________________
  49301. // Extracted from CubeMapGen:
  49302. // https://code.google.com/archive/p/cubemapgen/
  49303. //
  49304. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  49305. //_______________________________________________________________
  49306. var BABYLON;
  49307. (function (BABYLON) {
  49308. var Internals;
  49309. (function (Internals) {
  49310. /**
  49311. * The bounding box information used during the conversion process.
  49312. */
  49313. var CMGBoundinBox = (function () {
  49314. function CMGBoundinBox() {
  49315. this.min = new BABYLON.Vector3(0, 0, 0);
  49316. this.max = new BABYLON.Vector3(0, 0, 0);
  49317. this.clear();
  49318. }
  49319. CMGBoundinBox.prototype.clear = function () {
  49320. this.min.x = CMGBoundinBox.MAX;
  49321. this.min.y = CMGBoundinBox.MAX;
  49322. this.min.z = CMGBoundinBox.MAX;
  49323. this.max.x = CMGBoundinBox.MIN;
  49324. this.max.y = CMGBoundinBox.MIN;
  49325. this.max.z = CMGBoundinBox.MIN;
  49326. };
  49327. CMGBoundinBox.prototype.augment = function (x, y, z) {
  49328. this.min.x = Math.min(this.min.x, x);
  49329. this.min.y = Math.min(this.min.y, y);
  49330. this.min.z = Math.min(this.min.z, z);
  49331. this.max.x = Math.max(this.max.x, x);
  49332. this.max.y = Math.max(this.max.y, y);
  49333. this.max.z = Math.max(this.max.z, z);
  49334. };
  49335. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  49336. this.min.x = Math.max(this.min.x, x);
  49337. this.min.y = Math.max(this.min.y, y);
  49338. this.min.z = Math.max(this.min.z, z);
  49339. };
  49340. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  49341. this.max.x = Math.min(this.max.x, x);
  49342. this.max.y = Math.min(this.max.y, y);
  49343. this.max.z = Math.min(this.max.z, z);
  49344. };
  49345. CMGBoundinBox.prototype.empty = function () {
  49346. if ((this.min.x > this.max.y) ||
  49347. (this.min.y > this.max.y) ||
  49348. (this.min.z > this.max.y)) {
  49349. return true;
  49350. }
  49351. else {
  49352. return false;
  49353. }
  49354. };
  49355. CMGBoundinBox.MAX = Number.MAX_VALUE;
  49356. CMGBoundinBox.MIN = Number.MIN_VALUE;
  49357. return CMGBoundinBox;
  49358. }());
  49359. /**
  49360. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  49361. * required by the glossinees of a material.
  49362. *
  49363. * This only supports the cosine drop power as well as Warp fixup generation method.
  49364. *
  49365. * This is using the process from CubeMapGen described here:
  49366. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  49367. */
  49368. var PMREMGenerator = (function () {
  49369. /**
  49370. * Constructor of the generator.
  49371. *
  49372. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  49373. * @param inputSize The size of the cubemap faces
  49374. * @param outputSize The size of the output cubemap faces
  49375. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  49376. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  49377. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  49378. * @param specularPower The max specular level of the desired cubemap
  49379. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  49380. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  49381. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  49382. */
  49383. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  49384. this.input = input;
  49385. this.inputSize = inputSize;
  49386. this.outputSize = outputSize;
  49387. this.maxNumMipLevels = maxNumMipLevels;
  49388. this.numChannels = numChannels;
  49389. this.isFloat = isFloat;
  49390. this.specularPower = specularPower;
  49391. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  49392. this.excludeBase = excludeBase;
  49393. this.fixup = fixup;
  49394. this._outputSurface = [];
  49395. this._numMipLevels = 0;
  49396. }
  49397. /**
  49398. * Launches the filter process and return the result.
  49399. *
  49400. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  49401. */
  49402. PMREMGenerator.prototype.filterCubeMap = function () {
  49403. // Init cubemap processor
  49404. this.init();
  49405. // Filters the cubemap
  49406. this.filterCubeMapMipChain();
  49407. // Returns the filtered mips.
  49408. return this._outputSurface;
  49409. };
  49410. PMREMGenerator.prototype.init = function () {
  49411. var i;
  49412. var j;
  49413. var mipLevelSize;
  49414. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  49415. if (this.maxNumMipLevels == 0) {
  49416. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  49417. }
  49418. //first miplevel size
  49419. mipLevelSize = this.outputSize;
  49420. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  49421. for (j = 0; j < this.maxNumMipLevels; j++) {
  49422. this._outputSurface.length++;
  49423. this._outputSurface[j] = [];
  49424. //Iterate over faces for output images
  49425. for (i = 0; i < 6; i++) {
  49426. this._outputSurface[j].length++;
  49427. // Initializes a new array for the output.
  49428. if (this.isFloat) {
  49429. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  49430. }
  49431. else {
  49432. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  49433. }
  49434. }
  49435. //next mip level is half size
  49436. mipLevelSize >>= 1;
  49437. this._numMipLevels++;
  49438. //terminate if mip chain becomes too small
  49439. if (mipLevelSize == 0) {
  49440. this.maxNumMipLevels = j;
  49441. return;
  49442. }
  49443. }
  49444. };
  49445. //--------------------------------------------------------------------------------------
  49446. //Cube map filtering and mip chain generation.
  49447. // the cube map filtereing is specified using a number of parameters:
  49448. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  49449. // indicates the region of the hemisphere to filter over for each tap.
  49450. //
  49451. // Note that the top mip level is also a filtered version of the original input images
  49452. // as well in order to create mip chains for diffuse environment illumination.
  49453. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  49454. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  49455. //
  49456. // Then the mip angle used to genreate the next level of the mip chain from the first level
  49457. // is a_InitialMipAngle
  49458. //
  49459. // The angle for the subsequent levels of the mip chain are specified by their parents
  49460. // filtering angle and a per-level scale and bias
  49461. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  49462. //
  49463. //--------------------------------------------------------------------------------------
  49464. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  49465. // First, take count of the lighting model to modify SpecularPower
  49466. // 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;
  49467. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  49468. //Cone angle start (for generating subsequent mip levels)
  49469. var currentSpecularPower = this.specularPower;
  49470. //Build filter lookup tables based on the source miplevel size
  49471. this.precomputeFilterLookupTables(this.inputSize);
  49472. // Note that we need to filter the first level before generating mipmap
  49473. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  49474. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  49475. // TODO : Write a function to copy and scale the base mipmap in output
  49476. // I am just lazy here and just put a high specular power value, and do some if.
  49477. if (this.excludeBase && (levelIndex == 0)) {
  49478. // 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).
  49479. currentSpecularPower = 100000.0;
  49480. }
  49481. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  49482. var srcCubeImage = this.input;
  49483. var dstCubeImage = this._outputSurface[levelIndex];
  49484. var dstSize = this.outputSize >> levelIndex;
  49485. // Compute required angle.
  49486. var angle = this.getBaseFilterAngle(currentSpecularPower);
  49487. // filter cube surfaces
  49488. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  49489. // fix seams
  49490. if (this.fixup) {
  49491. this.fixupCubeEdges(dstCubeImage, dstSize);
  49492. }
  49493. // Decrease the specular power to generate the mipmap chain
  49494. // TODO : Use another method for Exclude (see first comment at start of the function
  49495. if (this.excludeBase && (levelIndex == 0)) {
  49496. currentSpecularPower = this.specularPower;
  49497. }
  49498. currentSpecularPower *= this.cosinePowerDropPerMip;
  49499. }
  49500. };
  49501. //--------------------------------------------------------------------------------------
  49502. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  49503. // It allow to optimize the texel to access base on the specular power.
  49504. //--------------------------------------------------------------------------------------
  49505. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  49506. // We want to find the alpha such that:
  49507. // cos(alpha)^cosinePower = epsilon
  49508. // That's: acos(epsilon^(1/cosinePower))
  49509. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  49510. var angle = 180.0;
  49511. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  49512. angle *= 180.0 / Math.PI; // Convert to degree
  49513. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  49514. return angle;
  49515. };
  49516. //--------------------------------------------------------------------------------------
  49517. //Builds the following lookup tables prior to filtering:
  49518. // -normalizer cube map
  49519. // -tap weight lookup table
  49520. //
  49521. //--------------------------------------------------------------------------------------
  49522. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  49523. var srcTexelAngle;
  49524. var iCubeFace;
  49525. //clear pre-existing normalizer cube map
  49526. this._normCubeMap = [];
  49527. //Normalized vectors per cubeface and per-texel solid angle
  49528. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  49529. };
  49530. //--------------------------------------------------------------------------------------
  49531. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  49532. //
  49533. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  49534. //
  49535. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  49536. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  49537. // below
  49538. //--------------------------------------------------------------------------------------
  49539. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  49540. var iCubeFace;
  49541. var u;
  49542. var v;
  49543. //iterate over cube faces
  49544. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  49545. //First three channels for norm cube, and last channel for solid angle
  49546. this._normCubeMap.push(new Float32Array(size * size * 4));
  49547. //fast texture walk, build normalizer cube map
  49548. var facesData = this.input[iCubeFace];
  49549. for (v = 0; v < size; v++) {
  49550. for (u = 0; u < size; u++) {
  49551. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  49552. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  49553. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  49554. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  49555. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  49556. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  49557. }
  49558. }
  49559. }
  49560. };
  49561. //--------------------------------------------------------------------------------------
  49562. // Convert cubemap face texel coordinates and face idx to 3D vector
  49563. // note the U and V coords are integer coords and range from 0 to size-1
  49564. // this routine can be used to generate a normalizer cube map
  49565. //--------------------------------------------------------------------------------------
  49566. // SL BEGIN
  49567. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  49568. var nvcU;
  49569. var nvcV;
  49570. var tempVec;
  49571. // Change from original AMD code
  49572. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  49573. // + 0.5f is for texel center addressing
  49574. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  49575. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  49576. // warp fixup
  49577. if (fixup && size > 1) {
  49578. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  49579. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  49580. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  49581. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  49582. }
  49583. // Get current vector
  49584. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  49585. // U contribution
  49586. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  49587. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  49588. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  49589. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  49590. // V contribution and Sum
  49591. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  49592. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  49593. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  49594. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  49595. //add face axis
  49596. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  49597. PMREMGenerator._vectorTemp.x += faceAxis[0];
  49598. PMREMGenerator._vectorTemp.y += faceAxis[1];
  49599. PMREMGenerator._vectorTemp.z += faceAxis[2];
  49600. //normalize vector
  49601. PMREMGenerator._vectorTemp.normalize();
  49602. return PMREMGenerator._vectorTemp;
  49603. };
  49604. //--------------------------------------------------------------------------------------
  49605. // Convert 3D vector to cubemap face texel coordinates and face idx
  49606. // note the U and V coords are integer coords and range from 0 to size-1
  49607. // this routine can be used to generate a normalizer cube map
  49608. //
  49609. // returns face IDX and texel coords
  49610. //--------------------------------------------------------------------------------------
  49611. // SL BEGIN
  49612. /*
  49613. Mapping Texture Coordinates to Cube Map Faces
  49614. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  49615. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  49616. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  49617. map arrangement in Pixar's RenderMan package.
  49618. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  49619. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  49620. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  49621. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  49622. the major axis direction). The target column in the table below explains how the major axis direction
  49623. maps to the 2D image of a particular cube map target.
  49624. major axis
  49625. direction target sc tc ma
  49626. ---------- --------------------------------- --- --- ---
  49627. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  49628. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  49629. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  49630. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  49631. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  49632. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  49633. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  49634. an updated (s,t) is calculated as follows
  49635. s = ( sc/|ma| + 1 ) / 2
  49636. t = ( tc/|ma| + 1 ) / 2
  49637. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  49638. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  49639. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  49640. */
  49641. // Note this method return U and V in range from 0 to size-1
  49642. // SL END
  49643. // Store the information in vector3 for convenience (faceindex, u, v)
  49644. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  49645. var maxCoord;
  49646. var faceIdx;
  49647. //absolute value 3
  49648. var absX = Math.abs(x);
  49649. var absY = Math.abs(y);
  49650. var absZ = Math.abs(z);
  49651. if (absX >= absY && absX >= absZ) {
  49652. maxCoord = absX;
  49653. if (x >= 0) {
  49654. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  49655. }
  49656. else {
  49657. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  49658. }
  49659. }
  49660. else if (absY >= absX && absY >= absZ) {
  49661. maxCoord = absY;
  49662. if (y >= 0) {
  49663. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  49664. }
  49665. else {
  49666. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  49667. }
  49668. }
  49669. else {
  49670. maxCoord = absZ;
  49671. if (z >= 0) {
  49672. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  49673. }
  49674. else {
  49675. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  49676. }
  49677. }
  49678. //divide through by max coord so face vector lies on cube face
  49679. var scale = 1 / maxCoord;
  49680. x *= scale;
  49681. y *= scale;
  49682. z *= scale;
  49683. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  49684. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  49685. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  49686. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  49687. // Modify original AMD code to return value from 0 to Size - 1
  49688. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  49689. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  49690. PMREMGenerator._vectorTemp.x = faceIdx;
  49691. PMREMGenerator._vectorTemp.y = u;
  49692. PMREMGenerator._vectorTemp.z = v;
  49693. return PMREMGenerator._vectorTemp;
  49694. };
  49695. //--------------------------------------------------------------------------------------
  49696. //Original code from Ignacio CastaÒo
  49697. // This formula is from Manne ÷hrstrˆm's thesis.
  49698. // Take two coordiantes in the range [-1, 1] that define a portion of a
  49699. // cube face and return the area of the projection of that portion on the
  49700. // surface of the sphere.
  49701. //--------------------------------------------------------------------------------------
  49702. PMREMGenerator.prototype.areaElement = function (x, y) {
  49703. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  49704. };
  49705. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  49706. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  49707. // (+ 0.5f is for texel center addressing)
  49708. u = (2.0 * (u + 0.5) / size) - 1.0;
  49709. v = (2.0 * (v + 0.5) / size) - 1.0;
  49710. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  49711. var invResolution = 1.0 / size;
  49712. // U and V are the -1..1 texture coordinate on the current face.
  49713. // Get projected area for this texel
  49714. var x0 = u - invResolution;
  49715. var y0 = v - invResolution;
  49716. var x1 = u + invResolution;
  49717. var y1 = v + invResolution;
  49718. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  49719. return solidAngle;
  49720. };
  49721. //--------------------------------------------------------------------------------------
  49722. //The key to the speed of these filtering routines is to quickly define a per-face
  49723. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  49724. // Later these pixels are selectively processed based on their dot products to see if
  49725. // they reside within the filtering cone.
  49726. //
  49727. //This is done by computing the smallest per-texel angle to get a conservative estimate
  49728. // of the number of texels needed to be covered in width and height order to filter the
  49729. // region. the bounding box for the center taps face is defined first, and if the
  49730. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  49731. // defined next
  49732. //--------------------------------------------------------------------------------------
  49733. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  49734. // note that pixels within these regions may be rejected
  49735. // based on the anlge
  49736. var iCubeFace;
  49737. var u;
  49738. var v;
  49739. // bounding box per face to specify region to process
  49740. var filterExtents = [];
  49741. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  49742. filterExtents.push(new CMGBoundinBox());
  49743. }
  49744. // min angle a src texel can cover (in degrees)
  49745. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  49746. // angle about center tap to define filter cone
  49747. // filter angle is 1/2 the cone angle
  49748. var filterAngle = filterConeAngle / 2.0;
  49749. //ensure filter angle is larger than a texel
  49750. if (filterAngle < srcTexelAngle) {
  49751. filterAngle = srcTexelAngle;
  49752. }
  49753. //ensure filter cone is always smaller than the hemisphere
  49754. if (filterAngle > 90.0) {
  49755. filterAngle = 90.0;
  49756. }
  49757. // the maximum number of texels in 1D the filter cone angle will cover
  49758. // used to determine bounding box size for filter extents
  49759. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  49760. // ensure conservative region always covers at least one texel
  49761. if (filterSize < 1) {
  49762. filterSize = 1;
  49763. }
  49764. // dotProdThresh threshold based on cone angle to determine whether or not taps
  49765. // reside within the cone angle
  49766. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  49767. // process required faces
  49768. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  49769. //iterate over dst cube map face texel
  49770. for (v = 0; v < dstSize; v++) {
  49771. for (u = 0; u < dstSize; u++) {
  49772. //get center tap direction
  49773. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  49774. //clear old per-face filter extents
  49775. this.clearFilterExtents(filterExtents);
  49776. //define per-face filter extents
  49777. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  49778. //perform filtering of src faces using filter extents
  49779. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  49780. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  49781. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  49782. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  49783. }
  49784. }
  49785. }
  49786. };
  49787. //--------------------------------------------------------------------------------------
  49788. //Clear filter extents for the 6 cube map faces
  49789. //--------------------------------------------------------------------------------------
  49790. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  49791. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  49792. filterExtents[iCubeFaces].clear();
  49793. }
  49794. };
  49795. //--------------------------------------------------------------------------------------
  49796. //Define per-face bounding box filter extents
  49797. //
  49798. // These define conservative texel regions in each of the faces the filter can possibly
  49799. // process. When the pixels in the regions are actually processed, the dot product
  49800. // between the tap vector and the center tap vector is used to determine the weight of
  49801. // the tap and whether or not the tap is within the cone.
  49802. //
  49803. //--------------------------------------------------------------------------------------
  49804. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  49805. //neighboring face and bleed over amount, and width of BBOX for
  49806. // left, right, top, and bottom edges of this face
  49807. var bleedOverAmount = [0, 0, 0, 0];
  49808. var bleedOverBBoxMin = [0, 0, 0, 0];
  49809. var bleedOverBBoxMax = [0, 0, 0, 0];
  49810. var neighborFace;
  49811. var neighborEdge;
  49812. var oppositeFaceIdx;
  49813. //get face idx, and u, v info from center tap dir
  49814. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  49815. var faceIdx = result.x;
  49816. var u = result.y;
  49817. var v = result.z;
  49818. //define bbox size within face
  49819. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  49820. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  49821. filterExtents[faceIdx].clampMin(0, 0, 0);
  49822. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  49823. //u and v extent in face corresponding to center tap
  49824. var minU = filterExtents[faceIdx].min.x;
  49825. var minV = filterExtents[faceIdx].min.y;
  49826. var maxU = filterExtents[faceIdx].max.x;
  49827. var maxV = filterExtents[faceIdx].max.y;
  49828. //bleed over amounts for face across u=0 edge (left)
  49829. bleedOverAmount[0] = (bboxSize - u);
  49830. bleedOverBBoxMin[0] = minV;
  49831. bleedOverBBoxMax[0] = maxV;
  49832. //bleed over amounts for face across u=1 edge (right)
  49833. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  49834. bleedOverBBoxMin[1] = minV;
  49835. bleedOverBBoxMax[1] = maxV;
  49836. //bleed over to face across v=0 edge (up)
  49837. bleedOverAmount[2] = (bboxSize - v);
  49838. bleedOverBBoxMin[2] = minU;
  49839. bleedOverBBoxMax[2] = maxU;
  49840. //bleed over to face across v=1 edge (down)
  49841. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  49842. bleedOverBBoxMin[3] = minU;
  49843. bleedOverBBoxMax[3] = maxU;
  49844. //compute bleed over regions in neighboring faces
  49845. for (var i = 0; i < 4; i++) {
  49846. if (bleedOverAmount[i] > 0) {
  49847. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  49848. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  49849. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  49850. // be flipped: the cases are
  49851. // if a left edge mates with a left or bottom edge on the neighbor
  49852. // if a top edge mates with a top or right edge on the neighbor
  49853. // if a right edge mates with a right or top edge on the neighbor
  49854. // if a bottom edge mates with a bottom or left edge on the neighbor
  49855. //Seeing as the edges are enumerated as follows
  49856. // left =0
  49857. // right =1
  49858. // top =2
  49859. // bottom =3
  49860. //
  49861. // so if the edge enums are the same, or the sum of the enums == 3,
  49862. // the bbox needs to be flipped
  49863. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  49864. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  49865. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  49866. }
  49867. //The way the bounding box is extended onto the neighboring face
  49868. // depends on which edge of neighboring face abuts with this one
  49869. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  49870. case PMREMGenerator.CP_EDGE_LEFT:
  49871. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  49872. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  49873. break;
  49874. case PMREMGenerator.CP_EDGE_RIGHT:
  49875. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  49876. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  49877. break;
  49878. case PMREMGenerator.CP_EDGE_TOP:
  49879. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  49880. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  49881. break;
  49882. case PMREMGenerator.CP_EDGE_BOTTOM:
  49883. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  49884. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  49885. break;
  49886. }
  49887. //clamp filter extents in non-center tap faces to remain within surface
  49888. filterExtents[neighborFace].clampMin(0, 0, 0);
  49889. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  49890. }
  49891. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  49892. // from the center tap face, then process the opposite face entirely for now.
  49893. //Note that the cases in which this happens, what usually happens is that
  49894. // more than one edge bleeds onto the opposite face, and the bounding box
  49895. // encompasses the entire cube map face.
  49896. if (bleedOverAmount[i] > srcSize) {
  49897. //determine opposite face
  49898. switch (faceIdx) {
  49899. case PMREMGenerator.CP_FACE_X_POS:
  49900. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  49901. break;
  49902. case PMREMGenerator.CP_FACE_X_NEG:
  49903. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  49904. break;
  49905. case PMREMGenerator.CP_FACE_Y_POS:
  49906. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  49907. break;
  49908. case PMREMGenerator.CP_FACE_Y_NEG:
  49909. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  49910. break;
  49911. case PMREMGenerator.CP_FACE_Z_POS:
  49912. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  49913. break;
  49914. case PMREMGenerator.CP_FACE_Z_NEG:
  49915. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  49916. break;
  49917. default:
  49918. break;
  49919. }
  49920. //just encompass entire face for now
  49921. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  49922. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  49923. }
  49924. }
  49925. };
  49926. //--------------------------------------------------------------------------------------
  49927. //ProcessFilterExtents
  49928. // Process bounding box in each cube face
  49929. //
  49930. //--------------------------------------------------------------------------------------
  49931. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  49932. //accumulators are 64-bit floats in order to have the precision needed
  49933. // over a summation of a large number of pixels
  49934. var dstAccum = [0, 0, 0, 0];
  49935. var weightAccum = 0;
  49936. var k = 0;
  49937. var nSrcChannels = this.numChannels;
  49938. // norm cube map and srcCubeMap have same face width
  49939. var faceWidth = srcSize;
  49940. //amount to add to pointer to move to next scanline in images
  49941. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  49942. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  49943. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  49944. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  49945. // iterate over cubefaces
  49946. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  49947. //if bbox is non empty
  49948. if (!filterExtents[iFaceIdx].empty()) {
  49949. var uStart = filterExtents[iFaceIdx].min.x;
  49950. var vStart = filterExtents[iFaceIdx].min.y;
  49951. var uEnd = filterExtents[iFaceIdx].max.x;
  49952. var vEnd = filterExtents[iFaceIdx].max.y;
  49953. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  49954. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  49955. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  49956. for (var v = vStart; v <= vEnd; v++) {
  49957. var normCubeRowWalk = 0;
  49958. var srcCubeRowWalk = 0;
  49959. for (var u = uStart; u <= uEnd; u++) {
  49960. //pointer to direction in cube map associated with texel
  49961. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  49962. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  49963. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  49964. //check dot product to see if texel is within cone
  49965. var tapDotProd = texelVectX * centerTapDir.x +
  49966. texelVectY * centerTapDir.y +
  49967. texelVectZ * centerTapDir.z;
  49968. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  49969. //solid angle stored in 4th channel of normalizer/solid angle cube map
  49970. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  49971. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  49972. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  49973. // so just adding one to specularpower do the trick.
  49974. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  49975. //iterate over channels
  49976. for (k = 0; k < nSrcChannels; k++) {
  49977. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  49978. srcCubeRowWalk++;
  49979. }
  49980. weightAccum += weight; //accumulate weight
  49981. }
  49982. else {
  49983. //step across source pixel
  49984. srcCubeRowWalk += nSrcChannels;
  49985. }
  49986. normCubeRowWalk += 4; // 4 channels per norm cube map.
  49987. }
  49988. startIndexNormCubeMap += normCubePitch;
  49989. startIndexSrcCubeMap += srcCubePitch;
  49990. }
  49991. }
  49992. }
  49993. //divide through by weights if weight is non zero
  49994. if (weightAccum != 0.0) {
  49995. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  49996. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  49997. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  49998. if (this.numChannels > 3) {
  49999. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  50000. }
  50001. }
  50002. else {
  50003. // otherwise sample nearest
  50004. // get face idx and u, v texel coordinate in face
  50005. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  50006. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  50007. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  50008. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  50009. if (this.numChannels > 3) {
  50010. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  50011. }
  50012. }
  50013. return PMREMGenerator._vectorTemp;
  50014. };
  50015. //--------------------------------------------------------------------------------------
  50016. // Fixup cube edges
  50017. //
  50018. // average texels on cube map faces across the edges
  50019. // WARP/BENT Method Only.
  50020. //--------------------------------------------------------------------------------------
  50021. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  50022. var k;
  50023. var j;
  50024. var i;
  50025. var iFace;
  50026. var iCorner = 0;
  50027. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  50028. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  50029. // note that if functionality to filter across the three texels for each corner, then
  50030. //indexed by corner and face idx. the array contains the face the start points belongs to.
  50031. var cornerPtr = [
  50032. [[], [], []],
  50033. [[], [], []],
  50034. [[], [], []],
  50035. [[], [], []],
  50036. [[], [], []],
  50037. [[], [], []],
  50038. [[], [], []],
  50039. [[], [], []]
  50040. ];
  50041. //if there is no fixup, or fixup width = 0, do nothing
  50042. if (cubeMapSize < 1) {
  50043. return;
  50044. }
  50045. //special case 1x1 cubemap, average face colors
  50046. if (cubeMapSize == 1) {
  50047. //iterate over channels
  50048. for (k = 0; k < this.numChannels; k++) {
  50049. var accum = 0.0;
  50050. //iterate over faces to accumulate face colors
  50051. for (iFace = 0; iFace < 6; iFace++) {
  50052. accum += cubeMap[iFace][k];
  50053. }
  50054. //compute average over 6 face colors
  50055. accum /= 6.0;
  50056. //iterate over faces to distribute face colors
  50057. for (iFace = 0; iFace < 6; iFace++) {
  50058. cubeMap[iFace][k] = accum;
  50059. }
  50060. }
  50061. return;
  50062. }
  50063. //iterate over faces to collect list of corner texel pointers
  50064. for (iFace = 0; iFace < 6; iFace++) {
  50065. //the 4 corner pointers for this face
  50066. faceCornerStartIndicies[0] = [iFace, 0];
  50067. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  50068. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  50069. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  50070. //iterate over face corners to collect cube corner pointers
  50071. for (iCorner = 0; iCorner < 4; iCorner++) {
  50072. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  50073. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  50074. cornerNumPtrs[corner]++;
  50075. }
  50076. }
  50077. //iterate over corners to average across corner tap values
  50078. for (iCorner = 0; iCorner < 8; iCorner++) {
  50079. for (k = 0; k < this.numChannels; k++) {
  50080. var cornerTapAccum = 0.0;
  50081. //iterate over corner texels and average results
  50082. for (i = 0; i < 3; i++) {
  50083. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  50084. }
  50085. //divide by 3 to compute average of corner tap values
  50086. cornerTapAccum *= (1.0 / 3.0);
  50087. //iterate over corner texels and average results
  50088. for (i = 0; i < 3; i++) {
  50089. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  50090. }
  50091. }
  50092. }
  50093. //iterate over the twelve edges of the cube to average across edges
  50094. for (i = 0; i < 12; i++) {
  50095. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  50096. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  50097. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  50098. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  50099. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  50100. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  50101. var edgeWalk = 0;
  50102. var neighborEdgeWalk = 0;
  50103. //Determine walking pointers based on edge type
  50104. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  50105. switch (edge) {
  50106. case PMREMGenerator.CP_EDGE_LEFT:
  50107. // no change to faceEdgeStartPtr
  50108. edgeWalk = this.numChannels * cubeMapSize;
  50109. break;
  50110. case PMREMGenerator.CP_EDGE_RIGHT:
  50111. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  50112. edgeWalk = this.numChannels * cubeMapSize;
  50113. break;
  50114. case PMREMGenerator.CP_EDGE_TOP:
  50115. // no change to faceEdgeStartPtr
  50116. edgeWalk = this.numChannels;
  50117. break;
  50118. case PMREMGenerator.CP_EDGE_BOTTOM:
  50119. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  50120. edgeWalk = this.numChannels;
  50121. break;
  50122. }
  50123. //For certain types of edge abutments, the neighbor edge walk needs to
  50124. // be flipped: the cases are
  50125. // if a left edge mates with a left or bottom edge on the neighbor
  50126. // if a top edge mates with a top or right edge on the neighbor
  50127. // if a right edge mates with a right or top edge on the neighbor
  50128. // if a bottom edge mates with a bottom or left edge on the neighbor
  50129. //Seeing as the edges are enumerated as follows
  50130. // left =0
  50131. // right =1
  50132. // top =2
  50133. // bottom =3
  50134. //
  50135. //If the edge enums are the same, or the sum of the enums == 3,
  50136. // the neighbor edge walk needs to be flipped
  50137. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  50138. switch (neighborEdge) {
  50139. case PMREMGenerator.CP_EDGE_LEFT:
  50140. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  50141. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  50142. break;
  50143. case PMREMGenerator.CP_EDGE_RIGHT:
  50144. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  50145. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  50146. break;
  50147. case PMREMGenerator.CP_EDGE_TOP:
  50148. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  50149. neighborEdgeWalk = -this.numChannels;
  50150. break;
  50151. case PMREMGenerator.CP_EDGE_BOTTOM:
  50152. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  50153. neighborEdgeWalk = -this.numChannels;
  50154. break;
  50155. }
  50156. }
  50157. else {
  50158. //swapped direction neighbor edge walk
  50159. switch (neighborEdge) {
  50160. case PMREMGenerator.CP_EDGE_LEFT:
  50161. //no change to neighborEdgeStartPtr for this case since it points
  50162. // to the upper left corner already
  50163. neighborEdgeWalk = this.numChannels * cubeMapSize;
  50164. break;
  50165. case PMREMGenerator.CP_EDGE_RIGHT:
  50166. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  50167. neighborEdgeWalk = this.numChannels * cubeMapSize;
  50168. break;
  50169. case PMREMGenerator.CP_EDGE_TOP:
  50170. //no change to neighborEdgeStartPtr for this case since it points
  50171. // to the upper left corner already
  50172. neighborEdgeWalk = this.numChannels;
  50173. break;
  50174. case PMREMGenerator.CP_EDGE_BOTTOM:
  50175. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  50176. neighborEdgeWalk = this.numChannels;
  50177. break;
  50178. }
  50179. }
  50180. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  50181. //nearby neighborhood
  50182. //step ahead one texel on edge
  50183. edgeStartIndex += edgeWalk;
  50184. neighborEdgeStartIndex += neighborEdgeWalk;
  50185. // note that this loop does not process the corner texels, since they have already been
  50186. // averaged across faces across earlier
  50187. for (j = 1; j < (cubeMapSize - 1); j++) {
  50188. //for each set of taps along edge, average them
  50189. // and rewrite the results into the edges
  50190. for (k = 0; k < this.numChannels; k++) {
  50191. var edgeTap = cubeMap[face][edgeStartIndex + k];
  50192. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  50193. //compute average of tap intensity values
  50194. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  50195. //propagate average of taps to edge taps
  50196. cubeMap[face][edgeStartIndex + k] = avgTap;
  50197. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  50198. }
  50199. edgeStartIndex += edgeWalk;
  50200. neighborEdgeStartIndex += neighborEdgeWalk;
  50201. }
  50202. }
  50203. };
  50204. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  50205. PMREMGenerator.CP_UDIR = 0;
  50206. PMREMGenerator.CP_VDIR = 1;
  50207. PMREMGenerator.CP_FACEAXIS = 2;
  50208. //used to index cube faces
  50209. PMREMGenerator.CP_FACE_X_POS = 0;
  50210. PMREMGenerator.CP_FACE_X_NEG = 1;
  50211. PMREMGenerator.CP_FACE_Y_POS = 2;
  50212. PMREMGenerator.CP_FACE_Y_NEG = 3;
  50213. PMREMGenerator.CP_FACE_Z_POS = 4;
  50214. PMREMGenerator.CP_FACE_Z_NEG = 5;
  50215. //used to index image edges
  50216. // NOTE.. the actual number corresponding to the edge is important
  50217. // do not change these, or the code will break
  50218. //
  50219. // CP_EDGE_LEFT is u = 0
  50220. // CP_EDGE_RIGHT is u = width-1
  50221. // CP_EDGE_TOP is v = 0
  50222. // CP_EDGE_BOTTOM is v = height-1
  50223. PMREMGenerator.CP_EDGE_LEFT = 0;
  50224. PMREMGenerator.CP_EDGE_RIGHT = 1;
  50225. PMREMGenerator.CP_EDGE_TOP = 2;
  50226. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  50227. //corners of CUBE map (P or N specifys if it corresponds to the
  50228. // positive or negative direction each of X, Y, and Z
  50229. PMREMGenerator.CP_CORNER_NNN = 0;
  50230. PMREMGenerator.CP_CORNER_NNP = 1;
  50231. PMREMGenerator.CP_CORNER_NPN = 2;
  50232. PMREMGenerator.CP_CORNER_NPP = 3;
  50233. PMREMGenerator.CP_CORNER_PNN = 4;
  50234. PMREMGenerator.CP_CORNER_PNP = 5;
  50235. PMREMGenerator.CP_CORNER_PPN = 6;
  50236. PMREMGenerator.CP_CORNER_PPP = 7;
  50237. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  50238. //3x2 matrices that map cube map indexing vectors in 3d
  50239. // (after face selection and divide through by the
  50240. // _ABSOLUTE VALUE_ of the max coord)
  50241. // into NVC space
  50242. //Note this currently assumes the D3D cube face ordering and orientation
  50243. PMREMGenerator._sgFace2DMapping = [
  50244. //XPOS face
  50245. [[0, 0, -1],
  50246. [0, -1, 0],
  50247. [1, 0, 0]],
  50248. //XNEG face
  50249. [[0, 0, 1],
  50250. [0, -1, 0],
  50251. [-1, 0, 0]],
  50252. //YPOS face
  50253. [[1, 0, 0],
  50254. [0, 0, 1],
  50255. [0, 1, 0]],
  50256. //YNEG face
  50257. [[1, 0, 0],
  50258. [0, 0, -1],
  50259. [0, -1, 0]],
  50260. //ZPOS face
  50261. [[1, 0, 0],
  50262. [0, -1, 0],
  50263. [0, 0, 1]],
  50264. //ZNEG face
  50265. [[-1, 0, 0],
  50266. [0, -1, 0],
  50267. [0, 0, -1]],
  50268. ];
  50269. //------------------------------------------------------------------------------
  50270. // D3D cube map face specification
  50271. // mapping from 3D x,y,z cube map lookup coordinates
  50272. // to 2D within face u,v coordinates
  50273. //
  50274. // --------------------> U direction
  50275. // | (within-face texture space)
  50276. // | _____
  50277. // | | |
  50278. // | | +Y |
  50279. // | _____|_____|_____ _____
  50280. // | | | | | |
  50281. // | | -X | +Z | +X | -Z |
  50282. // | |_____|_____|_____|_____|
  50283. // | | |
  50284. // | | -Y |
  50285. // | |_____|
  50286. // |
  50287. // v V direction
  50288. // (within-face texture space)
  50289. //------------------------------------------------------------------------------
  50290. //Information about neighbors and how texture coorrdinates change across faces
  50291. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  50292. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  50293. //Note this currently assumes the D3D cube face ordering and orientation
  50294. PMREMGenerator._sgCubeNgh = [
  50295. //XPOS face
  50296. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  50297. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  50298. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  50299. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  50300. //XNEG face
  50301. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  50302. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  50303. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  50304. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  50305. //YPOS face
  50306. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  50307. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  50308. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  50309. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  50310. //YNEG face
  50311. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  50312. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  50313. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  50314. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  50315. //ZPOS face
  50316. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  50317. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  50318. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  50319. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  50320. //ZNEG face
  50321. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  50322. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  50323. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  50324. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  50325. ];
  50326. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  50327. // this table is used to average over the edges.
  50328. PMREMGenerator._sgCubeEdgeList = [
  50329. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  50330. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  50331. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  50332. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  50333. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  50334. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  50335. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  50336. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  50337. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  50338. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  50339. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  50340. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  50341. ];
  50342. //Information about which of the 8 cube corners are correspond to the
  50343. // the 4 corners in each cube face
  50344. // the order is upper left, upper right, lower left, lower right
  50345. PMREMGenerator._sgCubeCornerList = [
  50346. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  50347. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  50348. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  50349. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  50350. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  50351. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  50352. ];
  50353. return PMREMGenerator;
  50354. }());
  50355. Internals.PMREMGenerator = PMREMGenerator;
  50356. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50357. })(BABYLON || (BABYLON = {}));
  50358. var BABYLON;
  50359. (function (BABYLON) {
  50360. /**
  50361. * This represents a texture coming from an HDR input.
  50362. *
  50363. * The only supported format is currently panorama picture stored in RGBE format.
  50364. * Example of such files can be found on HDRLib: http://hdrlib.com/
  50365. */
  50366. var HDRCubeTexture = (function (_super) {
  50367. __extends(HDRCubeTexture, _super);
  50368. /**
  50369. * Instantiates an HDRTexture from the following parameters.
  50370. *
  50371. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  50372. * @param scene The scene the texture will be used in
  50373. * @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.
  50374. * @param noMipmap Forces to not generate the mipmap if true
  50375. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  50376. * @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)
  50377. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  50378. */
  50379. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  50380. if (noMipmap === void 0) { noMipmap = false; }
  50381. if (generateHarmonics === void 0) { generateHarmonics = true; }
  50382. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  50383. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  50384. _super.call(this, scene);
  50385. this._useInGammaSpace = false;
  50386. this._generateHarmonics = true;
  50387. this._isBABYLONPreprocessed = false;
  50388. /**
  50389. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  50390. */
  50391. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  50392. /**
  50393. * The spherical polynomial data extracted from the texture.
  50394. */
  50395. this.sphericalPolynomial = null;
  50396. /**
  50397. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  50398. * This is usefull at run time to apply the good shader.
  50399. */
  50400. this.isPMREM = false;
  50401. if (!url) {
  50402. return;
  50403. }
  50404. this.name = url;
  50405. this.url = url;
  50406. this.hasAlpha = false;
  50407. this.isCube = true;
  50408. this._textureMatrix = BABYLON.Matrix.Identity();
  50409. if (size) {
  50410. this._isBABYLONPreprocessed = false;
  50411. this._noMipmap = noMipmap;
  50412. this._size = size;
  50413. this._useInGammaSpace = useInGammaSpace;
  50414. this._usePMREMGenerator = usePMREMGenerator &&
  50415. scene.getEngine().getCaps().textureLOD &&
  50416. this.getScene().getEngine().getCaps().textureFloat &&
  50417. !this._useInGammaSpace;
  50418. }
  50419. else {
  50420. this._isBABYLONPreprocessed = true;
  50421. this._noMipmap = false;
  50422. this._useInGammaSpace = false;
  50423. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  50424. this.getScene().getEngine().getCaps().textureFloat &&
  50425. !this._useInGammaSpace;
  50426. }
  50427. this.isPMREM = this._usePMREMGenerator;
  50428. this._texture = this._getFromCache(url, this._noMipmap);
  50429. if (!this._texture) {
  50430. if (!scene.useDelayedTextureLoading) {
  50431. this.loadTexture();
  50432. }
  50433. else {
  50434. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  50435. }
  50436. }
  50437. }
  50438. /**
  50439. * Occurs when the file is a preprocessed .babylon.hdr file.
  50440. */
  50441. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  50442. var _this = this;
  50443. var mipLevels = 0;
  50444. var floatArrayView = null;
  50445. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  50446. var mips = [];
  50447. var startIndex = 30;
  50448. for (var level = 0; level < mipLevels; level++) {
  50449. mips.push([]);
  50450. // Fill each pixel of the mip level.
  50451. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  50452. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50453. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  50454. mips[level].push(faceData);
  50455. startIndex += faceSize;
  50456. }
  50457. }
  50458. return mips;
  50459. } : null;
  50460. var callback = function (buffer) {
  50461. // Create Native Array Views
  50462. var intArrayView = new Int32Array(buffer);
  50463. floatArrayView = new Float32Array(buffer);
  50464. // Fill header.
  50465. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  50466. _this._size = intArrayView[1]; // CubeMap max mip face size.
  50467. // Update Texture Information.
  50468. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  50469. // Fill polynomial information.
  50470. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  50471. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  50472. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  50473. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  50474. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  50475. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  50476. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  50477. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  50478. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  50479. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  50480. // Fill pixel data.
  50481. mipLevels = intArrayView[29]; // Number of mip levels.
  50482. var startIndex = 30;
  50483. var data = [];
  50484. var faceSize = Math.pow(_this._size, 2) * 3;
  50485. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50486. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  50487. startIndex += faceSize;
  50488. }
  50489. var results = [];
  50490. var byteArray = null;
  50491. // Push each faces.
  50492. for (var k = 0; k < 6; k++) {
  50493. var dataFace = null;
  50494. // If special cases.
  50495. if (!mipmapGenerator) {
  50496. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  50497. dataFace = data[j];
  50498. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  50499. // 3 channels of 1 bytes per pixel in bytes.
  50500. var byteBuffer = new ArrayBuffer(faceSize);
  50501. byteArray = new Uint8Array(byteBuffer);
  50502. }
  50503. for (var i = 0; i < _this._size * _this._size; i++) {
  50504. // Put in gamma space if requested.
  50505. if (_this._useInGammaSpace) {
  50506. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  50507. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  50508. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  50509. }
  50510. // Convert to int texture for fallback.
  50511. if (byteArray) {
  50512. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  50513. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  50514. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  50515. // May use luminance instead if the result is not accurate.
  50516. var max = Math.max(Math.max(r, g), b);
  50517. if (max > 255) {
  50518. var scale = 255 / max;
  50519. r *= scale;
  50520. g *= scale;
  50521. b *= scale;
  50522. }
  50523. byteArray[(i * 3) + 0] = r;
  50524. byteArray[(i * 3) + 1] = g;
  50525. byteArray[(i * 3) + 2] = b;
  50526. }
  50527. }
  50528. }
  50529. else {
  50530. dataFace = data[k];
  50531. }
  50532. // Fill the array accordingly.
  50533. if (byteArray) {
  50534. results.push(byteArray);
  50535. }
  50536. else {
  50537. results.push(dataFace);
  50538. }
  50539. }
  50540. return results;
  50541. };
  50542. 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);
  50543. };
  50544. /**
  50545. * Occurs when the file is raw .hdr file.
  50546. */
  50547. HDRCubeTexture.prototype.loadHDRTexture = function () {
  50548. var _this = this;
  50549. var callback = function (buffer) {
  50550. // Extract the raw linear data.
  50551. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  50552. // Generate harmonics if needed.
  50553. if (_this._generateHarmonics) {
  50554. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  50555. }
  50556. var results = [];
  50557. var byteArray = null;
  50558. // Push each faces.
  50559. for (var j = 0; j < 6; j++) {
  50560. // Create uintarray fallback.
  50561. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  50562. // 3 channels of 1 bytes per pixel in bytes.
  50563. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  50564. byteArray = new Uint8Array(byteBuffer);
  50565. }
  50566. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  50567. // If special cases.
  50568. if (_this._useInGammaSpace || byteArray) {
  50569. for (var i = 0; i < _this._size * _this._size; i++) {
  50570. // Put in gamma space if requested.
  50571. if (_this._useInGammaSpace) {
  50572. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  50573. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  50574. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  50575. }
  50576. // Convert to int texture for fallback.
  50577. if (byteArray) {
  50578. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  50579. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  50580. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  50581. // May use luminance instead if the result is not accurate.
  50582. var max = Math.max(Math.max(r, g), b);
  50583. if (max > 255) {
  50584. var scale = 255 / max;
  50585. r *= scale;
  50586. g *= scale;
  50587. b *= scale;
  50588. }
  50589. byteArray[(i * 3) + 0] = r;
  50590. byteArray[(i * 3) + 1] = g;
  50591. byteArray[(i * 3) + 2] = b;
  50592. }
  50593. }
  50594. }
  50595. if (byteArray) {
  50596. results.push(byteArray);
  50597. }
  50598. else {
  50599. results.push(dataFace);
  50600. }
  50601. }
  50602. return results;
  50603. };
  50604. var mipmapGenerator = null;
  50605. if (!this._noMipmap &&
  50606. this._usePMREMGenerator) {
  50607. mipmapGenerator = function (data) {
  50608. // Custom setup of the generator matching with the PBR shader values.
  50609. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  50610. return generator.filterCubeMap();
  50611. };
  50612. }
  50613. 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);
  50614. };
  50615. /**
  50616. * Starts the loading process of the texture.
  50617. */
  50618. HDRCubeTexture.prototype.loadTexture = function () {
  50619. if (this._isBABYLONPreprocessed) {
  50620. this.loadBabylonTexture();
  50621. }
  50622. else {
  50623. this.loadHDRTexture();
  50624. }
  50625. };
  50626. HDRCubeTexture.prototype.clone = function () {
  50627. var size = this._isBABYLONPreprocessed ? null : this._size;
  50628. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  50629. // Base texture
  50630. newTexture.level = this.level;
  50631. newTexture.wrapU = this.wrapU;
  50632. newTexture.wrapV = this.wrapV;
  50633. newTexture.coordinatesIndex = this.coordinatesIndex;
  50634. newTexture.coordinatesMode = this.coordinatesMode;
  50635. return newTexture;
  50636. };
  50637. // Methods
  50638. HDRCubeTexture.prototype.delayLoad = function () {
  50639. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  50640. return;
  50641. }
  50642. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  50643. this._texture = this._getFromCache(this.url, this._noMipmap);
  50644. if (!this._texture) {
  50645. this.loadTexture();
  50646. }
  50647. };
  50648. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  50649. return this._textureMatrix;
  50650. };
  50651. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  50652. var texture = null;
  50653. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  50654. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  50655. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  50656. texture.name = parsedTexture.name;
  50657. texture.hasAlpha = parsedTexture.hasAlpha;
  50658. texture.level = parsedTexture.level;
  50659. texture.coordinatesMode = parsedTexture.coordinatesMode;
  50660. }
  50661. return texture;
  50662. };
  50663. HDRCubeTexture.prototype.serialize = function () {
  50664. if (!this.name) {
  50665. return null;
  50666. }
  50667. var serializationObject = {};
  50668. serializationObject.name = this.name;
  50669. serializationObject.hasAlpha = this.hasAlpha;
  50670. serializationObject.isCube = true;
  50671. serializationObject.level = this.level;
  50672. serializationObject.size = this._size;
  50673. serializationObject.coordinatesMode = this.coordinatesMode;
  50674. serializationObject.useInGammaSpace = this._useInGammaSpace;
  50675. serializationObject.generateHarmonics = this._generateHarmonics;
  50676. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  50677. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  50678. serializationObject.customType = "BABYLON.HDRCubeTexture";
  50679. return serializationObject;
  50680. };
  50681. /**
  50682. * Saves as a file the data contained in the texture in a binary format.
  50683. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  50684. * as the spherical used in the lighting.
  50685. * @param url The HDR file url.
  50686. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  50687. * @param onError Method called if any error happens during download.
  50688. * @return The packed binary data.
  50689. */
  50690. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  50691. if (onError === void 0) { onError = null; }
  50692. var callback = function (buffer) {
  50693. var data = new Blob([buffer], { type: 'application/octet-stream' });
  50694. // Returns a URL you can use as a href.
  50695. var objUrl = window.URL.createObjectURL(data);
  50696. // Simulates a link to it and click to dowload.
  50697. var a = document.createElement("a");
  50698. document.body.appendChild(a);
  50699. a.style.display = "none";
  50700. a.href = objUrl;
  50701. a.download = "envmap.babylon.hdr";
  50702. a.click();
  50703. };
  50704. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  50705. };
  50706. /**
  50707. * Serializes the data contained in the texture in a binary format.
  50708. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  50709. * as the spherical used in the lighting.
  50710. * @param url The HDR file url.
  50711. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  50712. * @param onError Method called if any error happens during download.
  50713. * @return The packed binary data.
  50714. */
  50715. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  50716. if (onError === void 0) { onError = null; }
  50717. // Needs the url tho create the texture.
  50718. if (!url) {
  50719. return null;
  50720. }
  50721. // Check Power of two size.
  50722. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  50723. return null;
  50724. }
  50725. var getDataCallback = function (dataBuffer) {
  50726. // Extract the raw linear data.
  50727. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  50728. // Generate harmonics if needed.
  50729. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  50730. // Generate seamless faces
  50731. var mipGeneratorArray = [];
  50732. // Data are known to be in +X +Y +Z -X -Y -Z
  50733. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  50734. mipGeneratorArray.push(cubeData.right); // +X
  50735. mipGeneratorArray.push(cubeData.left); // -X
  50736. mipGeneratorArray.push(cubeData.up); // +Y
  50737. mipGeneratorArray.push(cubeData.down); // -Y
  50738. mipGeneratorArray.push(cubeData.front); // +Z
  50739. mipGeneratorArray.push(cubeData.back); // -Z
  50740. // Custom setup of the generator matching with the PBR shader values.
  50741. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  50742. var mippedData = generator.filterCubeMap();
  50743. // Compute required byte length.
  50744. var byteLength = 1 * 4; // Raw Data Version int32.
  50745. byteLength += 4; // CubeMap max mip face size int32.
  50746. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  50747. // Add data size.
  50748. byteLength += 4; // Number of mip levels int32.
  50749. for (var level = 0; level < mippedData.length; level++) {
  50750. var mipSize = size >> level;
  50751. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  50752. }
  50753. // Prepare binary structure.
  50754. var buffer = new ArrayBuffer(byteLength);
  50755. var intArrayView = new Int32Array(buffer);
  50756. var floatArrayView = new Float32Array(buffer);
  50757. // Fill header.
  50758. intArrayView[0] = 1; // Version 1.
  50759. intArrayView[1] = size; // CubeMap max mip face size.
  50760. // Fill polynomial information.
  50761. sphericalPolynomial.x.toArray(floatArrayView, 2);
  50762. sphericalPolynomial.y.toArray(floatArrayView, 5);
  50763. sphericalPolynomial.z.toArray(floatArrayView, 8);
  50764. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  50765. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  50766. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  50767. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  50768. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  50769. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  50770. // Fill pixel data.
  50771. intArrayView[29] = mippedData.length; // Number of mip levels.
  50772. var startIndex = 30;
  50773. for (var level = 0; level < mippedData.length; level++) {
  50774. // Fill each pixel of the mip level.
  50775. var faceSize = Math.pow(size >> level, 2) * 3;
  50776. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50777. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  50778. startIndex += faceSize;
  50779. }
  50780. }
  50781. // Callback.
  50782. callback(buffer);
  50783. };
  50784. // Download and process.
  50785. BABYLON.Tools.LoadFile(url, function (data) {
  50786. getDataCallback(data);
  50787. }, null, null, true, onError);
  50788. };
  50789. HDRCubeTexture._facesMapping = [
  50790. "right",
  50791. "up",
  50792. "front",
  50793. "left",
  50794. "down",
  50795. "back"
  50796. ];
  50797. return HDRCubeTexture;
  50798. }(BABYLON.BaseTexture));
  50799. BABYLON.HDRCubeTexture = HDRCubeTexture;
  50800. })(BABYLON || (BABYLON = {}));
  50801. var BABYLON;
  50802. (function (BABYLON) {
  50803. var Debug;
  50804. (function (Debug) {
  50805. /**
  50806. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  50807. */
  50808. var SkeletonViewer = (function () {
  50809. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  50810. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  50811. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  50812. this.skeleton = skeleton;
  50813. this.mesh = mesh;
  50814. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  50815. this.renderingGroupId = renderingGroupId;
  50816. this.color = BABYLON.Color3.White();
  50817. this._debugLines = [];
  50818. this._isEnabled = false;
  50819. this._scene = scene;
  50820. this.update();
  50821. this._renderFunction = this.update.bind(this);
  50822. }
  50823. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  50824. get: function () {
  50825. return this._isEnabled;
  50826. },
  50827. set: function (value) {
  50828. if (this._isEnabled === value) {
  50829. return;
  50830. }
  50831. this._isEnabled = value;
  50832. if (value) {
  50833. this._scene.registerBeforeRender(this._renderFunction);
  50834. }
  50835. else {
  50836. this._scene.unregisterBeforeRender(this._renderFunction);
  50837. }
  50838. },
  50839. enumerable: true,
  50840. configurable: true
  50841. });
  50842. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  50843. if (x === void 0) { x = 0; }
  50844. if (y === void 0) { y = 0; }
  50845. if (z === void 0) { z = 0; }
  50846. var tmat = BABYLON.Tmp.Matrix[0];
  50847. var parentBone = bone.getParent();
  50848. tmat.copyFrom(bone.getLocalMatrix());
  50849. if (x !== 0 || y !== 0 || z !== 0) {
  50850. var tmat2 = BABYLON.Tmp.Matrix[1];
  50851. BABYLON.Matrix.IdentityToRef(tmat2);
  50852. tmat2.m[12] = x;
  50853. tmat2.m[13] = y;
  50854. tmat2.m[14] = z;
  50855. tmat2.multiplyToRef(tmat, tmat);
  50856. }
  50857. if (parentBone) {
  50858. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  50859. }
  50860. tmat.multiplyToRef(meshMat, tmat);
  50861. position.x = tmat.m[12];
  50862. position.y = tmat.m[13];
  50863. position.z = tmat.m[14];
  50864. };
  50865. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  50866. var len = bones.length;
  50867. for (var i = 0; i < len; i++) {
  50868. var bone = bones[i];
  50869. var points = this._debugLines[i];
  50870. if (!points) {
  50871. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  50872. this._debugLines[i] = points;
  50873. }
  50874. this._getBonePosition(points[0], bone, meshMat);
  50875. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  50876. }
  50877. };
  50878. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  50879. var len = bones.length;
  50880. var boneNum = 0;
  50881. for (var i = len - 1; i >= 0; i--) {
  50882. var childBone = bones[i];
  50883. var parentBone = childBone.getParent();
  50884. if (!parentBone) {
  50885. continue;
  50886. }
  50887. var points = this._debugLines[boneNum];
  50888. if (!points) {
  50889. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  50890. this._debugLines[boneNum] = points;
  50891. }
  50892. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  50893. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  50894. boneNum++;
  50895. }
  50896. };
  50897. SkeletonViewer.prototype.update = function () {
  50898. if (this.autoUpdateBonesMatrices) {
  50899. this.skeleton.computeAbsoluteTransforms();
  50900. }
  50901. if (this.skeleton.bones[0].length === undefined) {
  50902. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  50903. }
  50904. else {
  50905. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  50906. }
  50907. if (!this._debugMesh) {
  50908. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  50909. this._debugMesh.renderingGroupId = this.renderingGroupId;
  50910. }
  50911. else {
  50912. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  50913. }
  50914. this._debugMesh.color = this.color;
  50915. };
  50916. SkeletonViewer.prototype.dispose = function () {
  50917. if (this._debugMesh) {
  50918. this.isEnabled = false;
  50919. this._debugMesh.dispose();
  50920. this._debugMesh = null;
  50921. }
  50922. };
  50923. return SkeletonViewer;
  50924. }());
  50925. Debug.SkeletonViewer = SkeletonViewer;
  50926. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  50927. })(BABYLON || (BABYLON = {}));
  50928. var BABYLON;
  50929. (function (BABYLON) {
  50930. /**
  50931. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  50932. * It can help converting any input color in a desired output one. This can then be used to create effects
  50933. * from sepia, black and white to sixties or futuristic rendering...
  50934. *
  50935. * The only supported format is currently 3dl.
  50936. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  50937. */
  50938. var ColorGradingTexture = (function (_super) {
  50939. __extends(ColorGradingTexture, _super);
  50940. /**
  50941. * Instantiates a ColorGradingTexture from the following parameters.
  50942. *
  50943. * @param url The location of the color gradind data (currently only supporting 3dl)
  50944. * @param scene The scene the texture will be used in
  50945. */
  50946. function ColorGradingTexture(url, scene) {
  50947. _super.call(this, scene);
  50948. if (!url) {
  50949. return;
  50950. }
  50951. this._textureMatrix = BABYLON.Matrix.Identity();
  50952. this.name = url;
  50953. this.url = url;
  50954. this.hasAlpha = false;
  50955. this.isCube = false;
  50956. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50957. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50958. this.anisotropicFilteringLevel = 1;
  50959. this._texture = this._getFromCache(url, true);
  50960. if (!this._texture) {
  50961. if (!scene.useDelayedTextureLoading) {
  50962. this.loadTexture();
  50963. }
  50964. else {
  50965. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  50966. }
  50967. }
  50968. }
  50969. /**
  50970. * Returns the texture matrix used in most of the material.
  50971. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  50972. */
  50973. ColorGradingTexture.prototype.getTextureMatrix = function () {
  50974. return this._textureMatrix;
  50975. };
  50976. /**
  50977. * Occurs when the file being loaded is a .3dl LUT file.
  50978. */
  50979. ColorGradingTexture.prototype.load3dlTexture = function () {
  50980. var _this = this;
  50981. var mipLevels = 0;
  50982. var floatArrayView = null;
  50983. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  50984. this._texture = texture;
  50985. var callback = function (text) {
  50986. var data;
  50987. var tempData;
  50988. var line;
  50989. var lines = text.split('\n');
  50990. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  50991. var maxColor = 0;
  50992. for (var i = 0; i < lines.length; i++) {
  50993. line = lines[i];
  50994. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  50995. continue;
  50996. if (line.indexOf('#') === 0)
  50997. continue;
  50998. var words = line.split(" ");
  50999. if (size === 0) {
  51000. // Number of space + one
  51001. size = words.length;
  51002. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  51003. tempData = new Float32Array(size * size * size * 4);
  51004. continue;
  51005. }
  51006. if (size != 0) {
  51007. var r = Math.max(parseInt(words[0]), 0);
  51008. var g = Math.max(parseInt(words[1]), 0);
  51009. var b = Math.max(parseInt(words[2]), 0);
  51010. maxColor = Math.max(r, maxColor);
  51011. maxColor = Math.max(g, maxColor);
  51012. maxColor = Math.max(b, maxColor);
  51013. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  51014. tempData[pixelStorageIndex + 0] = r;
  51015. tempData[pixelStorageIndex + 1] = g;
  51016. tempData[pixelStorageIndex + 2] = b;
  51017. tempData[pixelStorageIndex + 3] = 0;
  51018. pixelIndexSlice++;
  51019. if (pixelIndexSlice % size == 0) {
  51020. pixelIndexH++;
  51021. pixelIndexSlice = 0;
  51022. if (pixelIndexH % size == 0) {
  51023. pixelIndexW++;
  51024. pixelIndexH = 0;
  51025. }
  51026. }
  51027. }
  51028. }
  51029. for (var i = 0; i < tempData.length; i++) {
  51030. var value = tempData[i];
  51031. data[i] = (value / maxColor * 255);
  51032. }
  51033. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  51034. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  51035. };
  51036. BABYLON.Tools.LoadFile(this.url, callback);
  51037. return this._texture;
  51038. };
  51039. /**
  51040. * Starts the loading process of the texture.
  51041. */
  51042. ColorGradingTexture.prototype.loadTexture = function () {
  51043. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  51044. this.load3dlTexture();
  51045. }
  51046. };
  51047. /**
  51048. * Clones the color gradind texture.
  51049. */
  51050. ColorGradingTexture.prototype.clone = function () {
  51051. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  51052. // Base texture
  51053. newTexture.level = this.level;
  51054. return newTexture;
  51055. };
  51056. /**
  51057. * Called during delayed load for textures.
  51058. */
  51059. ColorGradingTexture.prototype.delayLoad = function () {
  51060. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  51061. return;
  51062. }
  51063. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  51064. this._texture = this._getFromCache(this.url, true);
  51065. if (!this._texture) {
  51066. this.loadTexture();
  51067. }
  51068. };
  51069. /**
  51070. * Binds the color grading to the shader.
  51071. * @param colorGrading The texture to bind
  51072. * @param effect The effect to bind to
  51073. */
  51074. ColorGradingTexture.Bind = function (colorGrading, effect) {
  51075. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  51076. var x = colorGrading.level; // Texture Level
  51077. var y = colorGrading.getSize().height; // Texture Size example with 8
  51078. var z = y - 1.0; // SizeMinusOne 8 - 1
  51079. var w = 1 / y; // Space of 1 slice 1 / 8
  51080. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  51081. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  51082. 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
  51083. 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
  51084. 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
  51085. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  51086. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  51087. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  51088. };
  51089. /**
  51090. * Prepare the list of uniforms associated with the ColorGrading effects.
  51091. * @param uniformsList The list of uniforms used in the effect
  51092. * @param samplersList The list of samplers used in the effect
  51093. */
  51094. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  51095. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  51096. samplersList.push("cameraColorGrading2DSampler");
  51097. };
  51098. /**
  51099. * Parses a color grading texture serialized by Babylon.
  51100. * @param parsedTexture The texture information being parsedTexture
  51101. * @param scene The scene to load the texture in
  51102. * @param rootUrl The root url of the data assets to load
  51103. * @return A color gradind texture
  51104. */
  51105. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  51106. var texture = null;
  51107. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  51108. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  51109. texture.name = parsedTexture.name;
  51110. texture.level = parsedTexture.level;
  51111. }
  51112. return texture;
  51113. };
  51114. /**
  51115. * Serializes the LUT texture to json format.
  51116. */
  51117. ColorGradingTexture.prototype.serialize = function () {
  51118. if (!this.name) {
  51119. return null;
  51120. }
  51121. var serializationObject = {};
  51122. serializationObject.name = this.name;
  51123. serializationObject.level = this.level;
  51124. serializationObject.customType = "BABYLON.ColorGradingTexture";
  51125. return serializationObject;
  51126. };
  51127. /**
  51128. * Empty line regex stored for GC.
  51129. */
  51130. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  51131. return ColorGradingTexture;
  51132. }(BABYLON.BaseTexture));
  51133. BABYLON.ColorGradingTexture = ColorGradingTexture;
  51134. })(BABYLON || (BABYLON = {}));
  51135. var BABYLON;
  51136. (function (BABYLON) {
  51137. /**
  51138. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  51139. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  51140. * 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;
  51141. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  51142. */
  51143. var ColorCurves = (function () {
  51144. function ColorCurves() {
  51145. this._dirty = true;
  51146. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  51147. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  51148. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  51149. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  51150. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  51151. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  51152. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  51153. this._globalHue = 30;
  51154. this._globalDensity = 0;
  51155. this._globalSaturation = 0;
  51156. this._globalExposure = 0;
  51157. this._highlightsHue = 30;
  51158. this._highlightsDensity = 0;
  51159. this._highlightsSaturation = 0;
  51160. this._highlightsExposure = 0;
  51161. this._midtonesHue = 30;
  51162. this._midtonesDensity = 0;
  51163. this._midtonesSaturation = 0;
  51164. this._midtonesExposure = 0;
  51165. this._shadowsHue = 30;
  51166. this._shadowsDensity = 0;
  51167. this._shadowsSaturation = 0;
  51168. this._shadowsExposure = 0;
  51169. }
  51170. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  51171. /**
  51172. * Gets the global Hue value.
  51173. * 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).
  51174. */
  51175. get: function () {
  51176. return this._globalHue;
  51177. },
  51178. /**
  51179. * Sets the global Hue value.
  51180. * 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).
  51181. */
  51182. set: function (value) {
  51183. this._globalHue = value;
  51184. this._dirty = true;
  51185. },
  51186. enumerable: true,
  51187. configurable: true
  51188. });
  51189. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  51190. /**
  51191. * Gets the global Density value.
  51192. * 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.
  51193. * Values less than zero provide a filter of opposite hue.
  51194. */
  51195. get: function () {
  51196. return this._globalDensity;
  51197. },
  51198. /**
  51199. * Sets the global Density value.
  51200. * 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.
  51201. * Values less than zero provide a filter of opposite hue.
  51202. */
  51203. set: function (value) {
  51204. this._globalDensity = value;
  51205. this._dirty = true;
  51206. },
  51207. enumerable: true,
  51208. configurable: true
  51209. });
  51210. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  51211. /**
  51212. * Gets the global Saturation value.
  51213. * 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.
  51214. */
  51215. get: function () {
  51216. return this._globalSaturation;
  51217. },
  51218. /**
  51219. * Sets the global Saturation value.
  51220. * 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.
  51221. */
  51222. set: function (value) {
  51223. this._globalSaturation = value;
  51224. this._dirty = true;
  51225. },
  51226. enumerable: true,
  51227. configurable: true
  51228. });
  51229. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  51230. /**
  51231. * Gets the highlights Hue value.
  51232. * 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).
  51233. */
  51234. get: function () {
  51235. return this._highlightsHue;
  51236. },
  51237. /**
  51238. * Sets the highlights Hue value.
  51239. * 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).
  51240. */
  51241. set: function (value) {
  51242. this._highlightsHue = value;
  51243. this._dirty = true;
  51244. },
  51245. enumerable: true,
  51246. configurable: true
  51247. });
  51248. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  51249. /**
  51250. * Gets the highlights Density value.
  51251. * 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.
  51252. * Values less than zero provide a filter of opposite hue.
  51253. */
  51254. get: function () {
  51255. return this._highlightsDensity;
  51256. },
  51257. /**
  51258. * Sets the highlights Density value.
  51259. * 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.
  51260. * Values less than zero provide a filter of opposite hue.
  51261. */
  51262. set: function (value) {
  51263. this._highlightsDensity = value;
  51264. this._dirty = true;
  51265. },
  51266. enumerable: true,
  51267. configurable: true
  51268. });
  51269. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  51270. /**
  51271. * Gets the highlights Saturation value.
  51272. * 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.
  51273. */
  51274. get: function () {
  51275. return this._highlightsSaturation;
  51276. },
  51277. /**
  51278. * Sets the highlights Saturation value.
  51279. * 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.
  51280. */
  51281. set: function (value) {
  51282. this._highlightsSaturation = value;
  51283. this._dirty = true;
  51284. },
  51285. enumerable: true,
  51286. configurable: true
  51287. });
  51288. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  51289. /**
  51290. * Gets the highlights Exposure value.
  51291. * 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.
  51292. */
  51293. get: function () {
  51294. return this._highlightsExposure;
  51295. },
  51296. /**
  51297. * Sets the highlights Exposure value.
  51298. * 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.
  51299. */
  51300. set: function (value) {
  51301. this._highlightsExposure = value;
  51302. this._dirty = true;
  51303. },
  51304. enumerable: true,
  51305. configurable: true
  51306. });
  51307. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  51308. /**
  51309. * Gets the midtones Hue value.
  51310. * 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).
  51311. */
  51312. get: function () {
  51313. return this._midtonesHue;
  51314. },
  51315. /**
  51316. * Sets the midtones Hue value.
  51317. * 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).
  51318. */
  51319. set: function (value) {
  51320. this._midtonesHue = value;
  51321. this._dirty = true;
  51322. },
  51323. enumerable: true,
  51324. configurable: true
  51325. });
  51326. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  51327. /**
  51328. * Gets the midtones Density value.
  51329. * 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.
  51330. * Values less than zero provide a filter of opposite hue.
  51331. */
  51332. get: function () {
  51333. return this._midtonesDensity;
  51334. },
  51335. /**
  51336. * Sets the midtones Density value.
  51337. * 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.
  51338. * Values less than zero provide a filter of opposite hue.
  51339. */
  51340. set: function (value) {
  51341. this._midtonesDensity = value;
  51342. this._dirty = true;
  51343. },
  51344. enumerable: true,
  51345. configurable: true
  51346. });
  51347. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  51348. /**
  51349. * Gets the midtones Saturation value.
  51350. * 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.
  51351. */
  51352. get: function () {
  51353. return this._midtonesSaturation;
  51354. },
  51355. /**
  51356. * Sets the midtones Saturation value.
  51357. * 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.
  51358. */
  51359. set: function (value) {
  51360. this._midtonesSaturation = value;
  51361. this._dirty = true;
  51362. },
  51363. enumerable: true,
  51364. configurable: true
  51365. });
  51366. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  51367. /**
  51368. * Gets the midtones Exposure value.
  51369. * 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.
  51370. */
  51371. get: function () {
  51372. return this._midtonesExposure;
  51373. },
  51374. /**
  51375. * Sets the midtones Exposure value.
  51376. * 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.
  51377. */
  51378. set: function (value) {
  51379. this._midtonesExposure = value;
  51380. this._dirty = true;
  51381. },
  51382. enumerable: true,
  51383. configurable: true
  51384. });
  51385. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  51386. /**
  51387. * Gets the shadows Hue value.
  51388. * 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).
  51389. */
  51390. get: function () {
  51391. return this._shadowsHue;
  51392. },
  51393. /**
  51394. * Sets the shadows Hue value.
  51395. * 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).
  51396. */
  51397. set: function (value) {
  51398. this._shadowsHue = value;
  51399. this._dirty = true;
  51400. },
  51401. enumerable: true,
  51402. configurable: true
  51403. });
  51404. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  51405. /**
  51406. * Gets the shadows Density value.
  51407. * 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.
  51408. * Values less than zero provide a filter of opposite hue.
  51409. */
  51410. get: function () {
  51411. return this._shadowsDensity;
  51412. },
  51413. /**
  51414. * Sets the shadows Density value.
  51415. * 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.
  51416. * Values less than zero provide a filter of opposite hue.
  51417. */
  51418. set: function (value) {
  51419. this._shadowsDensity = value;
  51420. this._dirty = true;
  51421. },
  51422. enumerable: true,
  51423. configurable: true
  51424. });
  51425. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  51426. /**
  51427. * Gets the shadows Saturation value.
  51428. * 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.
  51429. */
  51430. get: function () {
  51431. return this._shadowsSaturation;
  51432. },
  51433. /**
  51434. * Sets the shadows Saturation value.
  51435. * 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.
  51436. */
  51437. set: function (value) {
  51438. this._shadowsSaturation = value;
  51439. this._dirty = true;
  51440. },
  51441. enumerable: true,
  51442. configurable: true
  51443. });
  51444. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  51445. /**
  51446. * Gets the shadows Exposure value.
  51447. * 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.
  51448. */
  51449. get: function () {
  51450. return this._shadowsExposure;
  51451. },
  51452. /**
  51453. * Sets the shadows Exposure value.
  51454. * 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.
  51455. */
  51456. set: function (value) {
  51457. this._shadowsExposure = value;
  51458. this._dirty = true;
  51459. },
  51460. enumerable: true,
  51461. configurable: true
  51462. });
  51463. /**
  51464. * Binds the color curves to the shader.
  51465. * @param colorCurves The color curve to bind
  51466. * @param effect The effect to bind to
  51467. */
  51468. ColorCurves.Bind = function (colorCurves, effect) {
  51469. if (colorCurves._dirty) {
  51470. colorCurves._dirty = false;
  51471. // Fill in global info.
  51472. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  51473. // Compute highlights info.
  51474. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  51475. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  51476. // Compute midtones info.
  51477. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  51478. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  51479. // Compute shadows info.
  51480. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  51481. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  51482. // Compute deltas (neutral is midtones).
  51483. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  51484. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  51485. }
  51486. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  51487. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  51488. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  51489. };
  51490. /**
  51491. * Prepare the list of uniforms associated with the ColorCurves effects.
  51492. * @param uniformsList The list of uniforms used in the effect
  51493. */
  51494. ColorCurves.PrepareUniforms = function (uniformsList) {
  51495. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  51496. };
  51497. /**
  51498. * Returns color grading data based on a hue, density, saturation and exposure value.
  51499. * @param filterHue The hue of the color filter.
  51500. * @param filterDensity The density of the color filter.
  51501. * @param saturation The saturation.
  51502. * @param exposure The exposure.
  51503. * @param result The result data container.
  51504. */
  51505. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  51506. if (hue == null) {
  51507. return;
  51508. }
  51509. hue = ColorCurves.clamp(hue, 0, 360);
  51510. density = ColorCurves.clamp(density, -100, 100);
  51511. saturation = ColorCurves.clamp(saturation, -100, 100);
  51512. exposure = ColorCurves.clamp(exposure, -100, 100);
  51513. // Remap the slider/config filter density with non-linear mapping and also scale by half
  51514. // so that the maximum filter density is only 50% control. This provides fine control
  51515. // for small values and reasonable range.
  51516. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  51517. density *= 0.5;
  51518. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  51519. if (density < 0) {
  51520. density *= -1;
  51521. hue = (hue + 180) % 360;
  51522. }
  51523. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  51524. result.scaleToRef(2, result);
  51525. result.a = 1 + 0.01 * saturation;
  51526. };
  51527. /**
  51528. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  51529. * @param value The input slider value in range [-100,100].
  51530. * @returns Adjusted value.
  51531. */
  51532. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  51533. value /= 100;
  51534. var x = Math.abs(value);
  51535. x = Math.pow(x, 2);
  51536. if (value < 0) {
  51537. x *= -1;
  51538. }
  51539. x *= 100;
  51540. return x;
  51541. };
  51542. /**
  51543. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  51544. * @param hue The hue (H) input.
  51545. * @param saturation The saturation (S) input.
  51546. * @param brightness The brightness (B) input.
  51547. * @result An RGBA color represented as Vector4.
  51548. */
  51549. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  51550. var h = ColorCurves.clamp(hue, 0, 360);
  51551. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  51552. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  51553. if (s === 0) {
  51554. result.r = v;
  51555. result.g = v;
  51556. result.b = v;
  51557. }
  51558. else {
  51559. // sector 0 to 5
  51560. h /= 60;
  51561. var i = Math.floor(h);
  51562. // fractional part of h
  51563. var f = h - i;
  51564. var p = v * (1 - s);
  51565. var q = v * (1 - s * f);
  51566. var t = v * (1 - s * (1 - f));
  51567. switch (i) {
  51568. case 0:
  51569. result.r = v;
  51570. result.g = t;
  51571. result.b = p;
  51572. break;
  51573. case 1:
  51574. result.r = q;
  51575. result.g = v;
  51576. result.b = p;
  51577. break;
  51578. case 2:
  51579. result.r = p;
  51580. result.g = v;
  51581. result.b = t;
  51582. break;
  51583. case 3:
  51584. result.r = p;
  51585. result.g = q;
  51586. result.b = v;
  51587. break;
  51588. case 4:
  51589. result.r = t;
  51590. result.g = p;
  51591. result.b = v;
  51592. break;
  51593. default:
  51594. result.r = v;
  51595. result.g = p;
  51596. result.b = q;
  51597. break;
  51598. }
  51599. }
  51600. result.a = 1;
  51601. };
  51602. /**
  51603. * Returns a value clamped between min and max
  51604. * @param value The value to clamp
  51605. * @param min The minimum of value
  51606. * @param max The maximum of value
  51607. * @returns The clamped value.
  51608. */
  51609. ColorCurves.clamp = function (value, min, max) {
  51610. return Math.min(Math.max(value, min), max);
  51611. };
  51612. /**
  51613. * Clones the current color curve instance.
  51614. * @return The cloned curves
  51615. */
  51616. ColorCurves.prototype.clone = function () {
  51617. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  51618. };
  51619. /**
  51620. * Serializes the current color curve instance to a json representation.
  51621. * @return a JSON representation
  51622. */
  51623. ColorCurves.prototype.serialize = function () {
  51624. return BABYLON.SerializationHelper.Serialize(this);
  51625. };
  51626. /**
  51627. * Parses the color curve from a json representation.
  51628. * @param source the JSON source to parse
  51629. * @return The parsed curves
  51630. */
  51631. ColorCurves.Parse = function (source) {
  51632. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  51633. };
  51634. __decorate([
  51635. BABYLON.serialize()
  51636. ], ColorCurves.prototype, "_globalHue", void 0);
  51637. __decorate([
  51638. BABYLON.serialize()
  51639. ], ColorCurves.prototype, "_globalDensity", void 0);
  51640. __decorate([
  51641. BABYLON.serialize()
  51642. ], ColorCurves.prototype, "_globalSaturation", void 0);
  51643. __decorate([
  51644. BABYLON.serialize()
  51645. ], ColorCurves.prototype, "_globalExposure", void 0);
  51646. __decorate([
  51647. BABYLON.serialize()
  51648. ], ColorCurves.prototype, "_highlightsHue", void 0);
  51649. __decorate([
  51650. BABYLON.serialize()
  51651. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  51652. __decorate([
  51653. BABYLON.serialize()
  51654. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  51655. __decorate([
  51656. BABYLON.serialize()
  51657. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  51658. __decorate([
  51659. BABYLON.serialize()
  51660. ], ColorCurves.prototype, "_midtonesHue", void 0);
  51661. __decorate([
  51662. BABYLON.serialize()
  51663. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  51664. __decorate([
  51665. BABYLON.serialize()
  51666. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  51667. __decorate([
  51668. BABYLON.serialize()
  51669. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  51670. return ColorCurves;
  51671. }());
  51672. BABYLON.ColorCurves = ColorCurves;
  51673. })(BABYLON || (BABYLON = {}));
  51674. var BABYLON;
  51675. (function (BABYLON) {
  51676. var PBRMaterialDefines = (function (_super) {
  51677. __extends(PBRMaterialDefines, _super);
  51678. function PBRMaterialDefines() {
  51679. _super.call(this);
  51680. this.ALBEDO = false;
  51681. this.AMBIENT = false;
  51682. this.OPACITY = false;
  51683. this.OPACITYRGB = false;
  51684. this.REFLECTION = false;
  51685. this.EMISSIVE = false;
  51686. this.REFLECTIVITY = false;
  51687. this.BUMP = false;
  51688. this.PARALLAX = false;
  51689. this.PARALLAXOCCLUSION = false;
  51690. this.SPECULAROVERALPHA = false;
  51691. this.CLIPPLANE = false;
  51692. this.ALPHATEST = false;
  51693. this.ALPHAFROMALBEDO = false;
  51694. this.POINTSIZE = false;
  51695. this.FOG = false;
  51696. this.SPECULARTERM = false;
  51697. this.OPACITYFRESNEL = false;
  51698. this.EMISSIVEFRESNEL = false;
  51699. this.FRESNEL = false;
  51700. this.NORMAL = false;
  51701. this.UV1 = false;
  51702. this.UV2 = false;
  51703. this.VERTEXCOLOR = false;
  51704. this.VERTEXALPHA = false;
  51705. this.NUM_BONE_INFLUENCERS = 0;
  51706. this.BonesPerMesh = 0;
  51707. this.INSTANCES = false;
  51708. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  51709. this.MICROSURFACEAUTOMATIC = false;
  51710. this.EMISSIVEASILLUMINATION = false;
  51711. this.LINKEMISSIVEWITHALBEDO = false;
  51712. this.LIGHTMAP = false;
  51713. this.USELIGHTMAPASSHADOWMAP = false;
  51714. this.REFLECTIONMAP_3D = false;
  51715. this.REFLECTIONMAP_SPHERICAL = false;
  51716. this.REFLECTIONMAP_PLANAR = false;
  51717. this.REFLECTIONMAP_CUBIC = false;
  51718. this.REFLECTIONMAP_PROJECTION = false;
  51719. this.REFLECTIONMAP_SKYBOX = false;
  51720. this.REFLECTIONMAP_EXPLICIT = false;
  51721. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  51722. this.INVERTCUBICMAP = false;
  51723. this.LOGARITHMICDEPTH = false;
  51724. this.CAMERATONEMAP = false;
  51725. this.CAMERACONTRAST = false;
  51726. this.CAMERACOLORGRADING = false;
  51727. this.CAMERACOLORCURVES = false;
  51728. this.OVERLOADEDVALUES = false;
  51729. this.OVERLOADEDSHADOWVALUES = false;
  51730. this.USESPHERICALFROMREFLECTIONMAP = false;
  51731. this.REFRACTION = false;
  51732. this.REFRACTIONMAP_3D = false;
  51733. this.LINKREFRACTIONTOTRANSPARENCY = false;
  51734. this.REFRACTIONMAPINLINEARSPACE = false;
  51735. this.LODBASEDMICROSFURACE = false;
  51736. this.USEPHYSICALLIGHTFALLOFF = false;
  51737. this.RADIANCEOVERALPHA = false;
  51738. this.USEPMREMREFLECTION = false;
  51739. this.USEPMREMREFRACTION = false;
  51740. this.OPENGLNORMALMAP = false;
  51741. this.INVERTNORMALMAPX = false;
  51742. this.INVERTNORMALMAPY = false;
  51743. this.SHADOWFULLFLOAT = false;
  51744. this.rebuild();
  51745. }
  51746. return PBRMaterialDefines;
  51747. }(BABYLON.MaterialDefines));
  51748. /**
  51749. * The Physically based material of BJS.
  51750. *
  51751. * This offers the main features of a standard PBR material.
  51752. * For more information, please refer to the documentation :
  51753. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  51754. */
  51755. var PBRMaterial = (function (_super) {
  51756. __extends(PBRMaterial, _super);
  51757. /**
  51758. * Instantiates a new PBRMaterial instance.
  51759. *
  51760. * @param name The material name
  51761. * @param scene The scene the material will be use in.
  51762. */
  51763. function PBRMaterial(name, scene) {
  51764. var _this = this;
  51765. _super.call(this, name, scene);
  51766. /**
  51767. * Intensity of the direct lights e.g. the four lights available in your scene.
  51768. * This impacts both the direct diffuse and specular highlights.
  51769. */
  51770. this.directIntensity = 1.0;
  51771. /**
  51772. * Intensity of the emissive part of the material.
  51773. * This helps controlling the emissive effect without modifying the emissive color.
  51774. */
  51775. this.emissiveIntensity = 1.0;
  51776. /**
  51777. * Intensity of the environment e.g. how much the environment will light the object
  51778. * either through harmonics for rough material or through the refelction for shiny ones.
  51779. */
  51780. this.environmentIntensity = 1.0;
  51781. /**
  51782. * This is a special control allowing the reduction of the specular highlights coming from the
  51783. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  51784. */
  51785. this.specularIntensity = 1.0;
  51786. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  51787. /**
  51788. * Debug Control allowing disabling the bump map on this material.
  51789. */
  51790. this.disableBumpMap = false;
  51791. /**
  51792. * Debug Control helping enforcing or dropping the darkness of shadows.
  51793. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  51794. */
  51795. this.overloadedShadowIntensity = 1.0;
  51796. /**
  51797. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  51798. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  51799. */
  51800. this.overloadedShadeIntensity = 1.0;
  51801. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  51802. /**
  51803. * The camera exposure used on this material.
  51804. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  51805. * This corresponds to a photographic exposure.
  51806. */
  51807. this.cameraExposure = 1.0;
  51808. /**
  51809. * The camera contrast used on this material.
  51810. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  51811. */
  51812. this.cameraContrast = 1.0;
  51813. /**
  51814. * Color Grading 2D Lookup Texture.
  51815. * This allows special effects like sepia, black and white to sixties rendering style.
  51816. */
  51817. this.cameraColorGradingTexture = null;
  51818. /**
  51819. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  51820. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  51821. * 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;
  51822. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  51823. */
  51824. this.cameraColorCurves = null;
  51825. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  51826. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  51827. /**
  51828. * Debug Control allowing to overload the ambient color.
  51829. * This as to be use with the overloadedAmbientIntensity parameter.
  51830. */
  51831. this.overloadedAmbient = BABYLON.Color3.White();
  51832. /**
  51833. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  51834. */
  51835. this.overloadedAmbientIntensity = 0.0;
  51836. /**
  51837. * Debug Control allowing to overload the albedo color.
  51838. * This as to be use with the overloadedAlbedoIntensity parameter.
  51839. */
  51840. this.overloadedAlbedo = BABYLON.Color3.White();
  51841. /**
  51842. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  51843. */
  51844. this.overloadedAlbedoIntensity = 0.0;
  51845. /**
  51846. * Debug Control allowing to overload the reflectivity color.
  51847. * This as to be use with the overloadedReflectivityIntensity parameter.
  51848. */
  51849. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  51850. /**
  51851. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  51852. */
  51853. this.overloadedReflectivityIntensity = 0.0;
  51854. /**
  51855. * Debug Control allowing to overload the emissive color.
  51856. * This as to be use with the overloadedEmissiveIntensity parameter.
  51857. */
  51858. this.overloadedEmissive = BABYLON.Color3.White();
  51859. /**
  51860. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  51861. */
  51862. this.overloadedEmissiveIntensity = 0.0;
  51863. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  51864. /**
  51865. * Debug Control allowing to overload the reflection color.
  51866. * This as to be use with the overloadedReflectionIntensity parameter.
  51867. */
  51868. this.overloadedReflection = BABYLON.Color3.White();
  51869. /**
  51870. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  51871. */
  51872. this.overloadedReflectionIntensity = 0.0;
  51873. /**
  51874. * Debug Control allowing to overload the microsurface.
  51875. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  51876. */
  51877. this.overloadedMicroSurface = 0.0;
  51878. /**
  51879. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  51880. */
  51881. this.overloadedMicroSurfaceIntensity = 0.0;
  51882. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  51883. /**
  51884. * AKA Occlusion Texture Intensity in other nomenclature.
  51885. */
  51886. this.ambientTextureStrength = 1.0;
  51887. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  51888. /**
  51889. * AKA Diffuse Color in other nomenclature.
  51890. */
  51891. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  51892. /**
  51893. * AKA Specular Color in other nomenclature.
  51894. */
  51895. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  51896. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  51897. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  51898. /**
  51899. * AKA Glossiness in other nomenclature.
  51900. */
  51901. this.microSurface = 0.9;
  51902. /**
  51903. * source material index of refraction (IOR)' / 'destination material IOR.
  51904. */
  51905. this.indexOfRefraction = 0.66;
  51906. /**
  51907. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  51908. */
  51909. this.invertRefractionY = false;
  51910. /**
  51911. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  51912. * Materials half opaque for instance using refraction could benefit from this control.
  51913. */
  51914. this.linkRefractionWithTransparency = false;
  51915. /**
  51916. * The emissive and albedo are linked to never be more than one (Energy conservation).
  51917. */
  51918. this.linkEmissiveWithAlbedo = false;
  51919. this.useLightmapAsShadowmap = false;
  51920. /**
  51921. * In this mode, the emissive informtaion will always be added to the lighting once.
  51922. * A light for instance can be thought as emissive.
  51923. */
  51924. this.useEmissiveAsIllumination = false;
  51925. /**
  51926. * Secifies that the alpha is coming form the albedo channel alpha channel.
  51927. */
  51928. this.useAlphaFromAlbedoTexture = false;
  51929. /**
  51930. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  51931. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  51932. */
  51933. this.useSpecularOverAlpha = true;
  51934. /**
  51935. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  51936. */
  51937. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  51938. /**
  51939. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  51940. * The material will try to infer what glossiness each pixel should be.
  51941. */
  51942. this.useAutoMicroSurfaceFromReflectivityMap = false;
  51943. /**
  51944. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  51945. * the creation of the material.
  51946. */
  51947. this.useScalarInLinearSpace = false;
  51948. /**
  51949. * BJS is using an harcoded light falloff based on a manually sets up range.
  51950. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  51951. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  51952. */
  51953. this.usePhysicalLightFalloff = true;
  51954. /**
  51955. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  51956. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  51957. */
  51958. this.useRadianceOverAlpha = true;
  51959. /**
  51960. * Allows using the bump map in parallax mode.
  51961. */
  51962. this.useParallax = false;
  51963. /**
  51964. * Allows using the bump map in parallax occlusion mode.
  51965. */
  51966. this.useParallaxOcclusion = false;
  51967. /**
  51968. * Controls the scale bias of the parallax mode.
  51969. */
  51970. this.parallaxScaleBias = 0.05;
  51971. /**
  51972. * If sets to true, disables all the lights affecting the material.
  51973. */
  51974. this.disableLighting = false;
  51975. /**
  51976. * Number of Simultaneous lights allowed on the material.
  51977. */
  51978. this.maxSimultaneousLights = 4;
  51979. /**
  51980. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  51981. */
  51982. this.invertNormalMapX = false;
  51983. /**
  51984. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  51985. */
  51986. this.invertNormalMapY = false;
  51987. this._renderTargets = new BABYLON.SmartArray(16);
  51988. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  51989. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  51990. this._tempColor = new BABYLON.Color3();
  51991. this._defines = new PBRMaterialDefines();
  51992. this._cachedDefines = new PBRMaterialDefines();
  51993. this._myScene = null;
  51994. this._myShadowGenerator = null;
  51995. this._cachedDefines.BonesPerMesh = -1;
  51996. this.getRenderTargetTextures = function () {
  51997. _this._renderTargets.reset();
  51998. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  51999. _this._renderTargets.push(_this.reflectionTexture);
  52000. }
  52001. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  52002. _this._renderTargets.push(_this.refractionTexture);
  52003. }
  52004. return _this._renderTargets;
  52005. };
  52006. }
  52007. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  52008. get: function () {
  52009. return this._useLogarithmicDepth;
  52010. },
  52011. set: function (value) {
  52012. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  52013. },
  52014. enumerable: true,
  52015. configurable: true
  52016. });
  52017. PBRMaterial.prototype.needAlphaBlending = function () {
  52018. if (this.linkRefractionWithTransparency) {
  52019. return false;
  52020. }
  52021. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  52022. };
  52023. PBRMaterial.prototype.needAlphaTesting = function () {
  52024. if (this.linkRefractionWithTransparency) {
  52025. return false;
  52026. }
  52027. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  52028. };
  52029. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  52030. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  52031. };
  52032. PBRMaterial.prototype.getAlphaTestTexture = function () {
  52033. return this.albedoTexture;
  52034. };
  52035. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  52036. if (!mesh) {
  52037. return true;
  52038. }
  52039. if (this._defines.INSTANCES !== useInstances) {
  52040. return false;
  52041. }
  52042. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  52043. return true;
  52044. }
  52045. return false;
  52046. };
  52047. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  52048. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  52049. };
  52050. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  52051. if (!useScalarInLinear) {
  52052. color.toLinearSpaceToRef(ref);
  52053. }
  52054. else {
  52055. ref.r = color.r;
  52056. ref.g = color.g;
  52057. ref.b = color.b;
  52058. }
  52059. };
  52060. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  52061. var lightIndex = 0;
  52062. var depthValuesAlreadySet = false;
  52063. for (var index = 0; index < scene.lights.length; index++) {
  52064. var light = scene.lights[index];
  52065. if (!light.isEnabled()) {
  52066. continue;
  52067. }
  52068. if (!light.canAffectMesh(mesh)) {
  52069. continue;
  52070. }
  52071. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  52072. // GAMMA CORRECTION.
  52073. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  52074. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  52075. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  52076. if (defines["SPECULARTERM"]) {
  52077. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  52078. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  52079. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  52080. }
  52081. // Shadows
  52082. if (scene.shadowsEnabled) {
  52083. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  52084. }
  52085. lightIndex++;
  52086. if (lightIndex === maxSimultaneousLights)
  52087. break;
  52088. }
  52089. };
  52090. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  52091. if (this.checkReadyOnlyOnce) {
  52092. if (this._wasPreviouslyReady) {
  52093. return true;
  52094. }
  52095. }
  52096. var scene = this.getScene();
  52097. if (!this.checkReadyOnEveryCall) {
  52098. if (this._renderId === scene.getRenderId()) {
  52099. if (this._checkCache(scene, mesh, useInstances)) {
  52100. return true;
  52101. }
  52102. }
  52103. }
  52104. var engine = scene.getEngine();
  52105. var needNormals = false;
  52106. var needUVs = false;
  52107. this._defines.reset();
  52108. if (scene.texturesEnabled) {
  52109. if (scene.getEngine().getCaps().textureLOD) {
  52110. this._defines.LODBASEDMICROSFURACE = true;
  52111. }
  52112. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  52113. if (!this.albedoTexture.isReady()) {
  52114. return false;
  52115. }
  52116. else {
  52117. needUVs = true;
  52118. this._defines.ALBEDO = true;
  52119. }
  52120. }
  52121. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  52122. if (!this.ambientTexture.isReady()) {
  52123. return false;
  52124. }
  52125. else {
  52126. needUVs = true;
  52127. this._defines.AMBIENT = true;
  52128. }
  52129. }
  52130. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  52131. if (!this.opacityTexture.isReady()) {
  52132. return false;
  52133. }
  52134. else {
  52135. needUVs = true;
  52136. this._defines.OPACITY = true;
  52137. if (this.opacityTexture.getAlphaFromRGB) {
  52138. this._defines.OPACITYRGB = true;
  52139. }
  52140. }
  52141. }
  52142. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  52143. if (!this.reflectionTexture.isReady()) {
  52144. return false;
  52145. }
  52146. else {
  52147. needNormals = true;
  52148. this._defines.REFLECTION = true;
  52149. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  52150. this._defines.INVERTCUBICMAP = true;
  52151. }
  52152. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  52153. switch (this.reflectionTexture.coordinatesMode) {
  52154. case BABYLON.Texture.CUBIC_MODE:
  52155. case BABYLON.Texture.INVCUBIC_MODE:
  52156. this._defines.REFLECTIONMAP_CUBIC = true;
  52157. break;
  52158. case BABYLON.Texture.EXPLICIT_MODE:
  52159. this._defines.REFLECTIONMAP_EXPLICIT = true;
  52160. break;
  52161. case BABYLON.Texture.PLANAR_MODE:
  52162. this._defines.REFLECTIONMAP_PLANAR = true;
  52163. break;
  52164. case BABYLON.Texture.PROJECTION_MODE:
  52165. this._defines.REFLECTIONMAP_PROJECTION = true;
  52166. break;
  52167. case BABYLON.Texture.SKYBOX_MODE:
  52168. this._defines.REFLECTIONMAP_SKYBOX = true;
  52169. break;
  52170. case BABYLON.Texture.SPHERICAL_MODE:
  52171. this._defines.REFLECTIONMAP_SPHERICAL = true;
  52172. break;
  52173. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  52174. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  52175. break;
  52176. }
  52177. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  52178. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  52179. needNormals = true;
  52180. if (this.reflectionTexture.isPMREM) {
  52181. this._defines.USEPMREMREFLECTION = true;
  52182. }
  52183. }
  52184. }
  52185. }
  52186. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  52187. if (!this.lightmapTexture.isReady()) {
  52188. return false;
  52189. }
  52190. else {
  52191. needUVs = true;
  52192. this._defines.LIGHTMAP = true;
  52193. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  52194. }
  52195. }
  52196. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  52197. if (!this.emissiveTexture.isReady()) {
  52198. return false;
  52199. }
  52200. else {
  52201. needUVs = true;
  52202. this._defines.EMISSIVE = true;
  52203. }
  52204. }
  52205. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  52206. if (!this.reflectivityTexture.isReady()) {
  52207. return false;
  52208. }
  52209. else {
  52210. needUVs = true;
  52211. this._defines.REFLECTIVITY = true;
  52212. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  52213. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  52214. }
  52215. }
  52216. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  52217. if (!this.bumpTexture.isReady()) {
  52218. return false;
  52219. }
  52220. else {
  52221. needUVs = true;
  52222. this._defines.BUMP = true;
  52223. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  52224. this._defines.PARALLAX = true;
  52225. if (this.useParallaxOcclusion) {
  52226. this._defines.PARALLAXOCCLUSION = true;
  52227. }
  52228. }
  52229. if (this.invertNormalMapX) {
  52230. this._defines.INVERTNORMALMAPX = true;
  52231. }
  52232. if (this.invertNormalMapY) {
  52233. this._defines.INVERTNORMALMAPY = true;
  52234. }
  52235. }
  52236. }
  52237. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  52238. if (!this.refractionTexture.isReady()) {
  52239. return false;
  52240. }
  52241. else {
  52242. needUVs = true;
  52243. this._defines.REFRACTION = true;
  52244. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  52245. if (this.linkRefractionWithTransparency) {
  52246. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  52247. }
  52248. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  52249. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  52250. if (this.refractionTexture.isPMREM) {
  52251. this._defines.USEPMREMREFRACTION = true;
  52252. }
  52253. }
  52254. }
  52255. }
  52256. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  52257. if (!this.cameraColorGradingTexture.isReady()) {
  52258. return false;
  52259. }
  52260. else {
  52261. this._defines.CAMERACOLORGRADING = true;
  52262. }
  52263. }
  52264. }
  52265. // Effect
  52266. if (scene.clipPlane) {
  52267. this._defines.CLIPPLANE = true;
  52268. }
  52269. if (engine.getAlphaTesting()) {
  52270. this._defines.ALPHATEST = true;
  52271. }
  52272. if (this._shouldUseAlphaFromAlbedoTexture()) {
  52273. this._defines.ALPHAFROMALBEDO = true;
  52274. }
  52275. if (this.useEmissiveAsIllumination) {
  52276. this._defines.EMISSIVEASILLUMINATION = true;
  52277. }
  52278. if (this.linkEmissiveWithAlbedo) {
  52279. this._defines.LINKEMISSIVEWITHALBEDO = true;
  52280. }
  52281. if (this.useLogarithmicDepth) {
  52282. this._defines.LOGARITHMICDEPTH = true;
  52283. }
  52284. if (this.cameraContrast != 1) {
  52285. this._defines.CAMERACONTRAST = true;
  52286. }
  52287. if (this.cameraExposure != 1) {
  52288. this._defines.CAMERATONEMAP = true;
  52289. }
  52290. if (this.cameraColorCurves) {
  52291. this._defines.CAMERACOLORCURVES = true;
  52292. }
  52293. if (this.overloadedShadeIntensity != 1 ||
  52294. this.overloadedShadowIntensity != 1) {
  52295. this._defines.OVERLOADEDSHADOWVALUES = true;
  52296. }
  52297. if (this.overloadedMicroSurfaceIntensity > 0 ||
  52298. this.overloadedEmissiveIntensity > 0 ||
  52299. this.overloadedReflectivityIntensity > 0 ||
  52300. this.overloadedAlbedoIntensity > 0 ||
  52301. this.overloadedAmbientIntensity > 0 ||
  52302. this.overloadedReflectionIntensity > 0) {
  52303. this._defines.OVERLOADEDVALUES = true;
  52304. }
  52305. // Point size
  52306. if (this.pointsCloud || scene.forcePointsCloud) {
  52307. this._defines.POINTSIZE = true;
  52308. }
  52309. // Fog
  52310. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  52311. this._defines.FOG = true;
  52312. }
  52313. if (scene.lightsEnabled && !this.disableLighting) {
  52314. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  52315. }
  52316. if (BABYLON.StandardMaterial.FresnelEnabled) {
  52317. // Fresnel
  52318. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  52319. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  52320. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  52321. this._defines.OPACITYFRESNEL = true;
  52322. }
  52323. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  52324. this._defines.EMISSIVEFRESNEL = true;
  52325. }
  52326. needNormals = true;
  52327. this._defines.FRESNEL = true;
  52328. }
  52329. }
  52330. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  52331. this._defines.SPECULAROVERALPHA = true;
  52332. }
  52333. if (this.usePhysicalLightFalloff) {
  52334. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  52335. }
  52336. if (this.useRadianceOverAlpha) {
  52337. this._defines.RADIANCEOVERALPHA = true;
  52338. }
  52339. // Attribs
  52340. if (mesh) {
  52341. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  52342. this._defines.NORMAL = true;
  52343. }
  52344. if (needUVs) {
  52345. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52346. this._defines.UV1 = true;
  52347. }
  52348. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52349. this._defines.UV2 = true;
  52350. }
  52351. }
  52352. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  52353. this._defines.VERTEXCOLOR = true;
  52354. if (mesh.hasVertexAlpha) {
  52355. this._defines.VERTEXALPHA = true;
  52356. }
  52357. }
  52358. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52359. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  52360. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  52361. }
  52362. // Instances
  52363. if (useInstances) {
  52364. this._defines.INSTANCES = true;
  52365. }
  52366. }
  52367. // Get correct effect
  52368. if (!this._defines.isEqual(this._cachedDefines)) {
  52369. this._defines.cloneTo(this._cachedDefines);
  52370. scene.resetCachedMaterial();
  52371. // Fallbacks
  52372. var fallbacks = new BABYLON.EffectFallbacks();
  52373. if (this._defines.REFLECTION) {
  52374. fallbacks.addFallback(0, "REFLECTION");
  52375. }
  52376. if (this._defines.REFRACTION) {
  52377. fallbacks.addFallback(0, "REFRACTION");
  52378. }
  52379. if (this._defines.REFLECTIVITY) {
  52380. fallbacks.addFallback(0, "REFLECTIVITY");
  52381. }
  52382. if (this._defines.BUMP) {
  52383. fallbacks.addFallback(0, "BUMP");
  52384. }
  52385. if (this._defines.PARALLAX) {
  52386. fallbacks.addFallback(1, "PARALLAX");
  52387. }
  52388. if (this._defines.PARALLAXOCCLUSION) {
  52389. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  52390. }
  52391. if (this._defines.SPECULAROVERALPHA) {
  52392. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  52393. }
  52394. if (this._defines.FOG) {
  52395. fallbacks.addFallback(1, "FOG");
  52396. }
  52397. if (this._defines.POINTSIZE) {
  52398. fallbacks.addFallback(0, "POINTSIZE");
  52399. }
  52400. if (this._defines.LOGARITHMICDEPTH) {
  52401. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  52402. }
  52403. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  52404. if (this._defines.SPECULARTERM) {
  52405. fallbacks.addFallback(0, "SPECULARTERM");
  52406. }
  52407. if (this._defines.OPACITYFRESNEL) {
  52408. fallbacks.addFallback(1, "OPACITYFRESNEL");
  52409. }
  52410. if (this._defines.EMISSIVEFRESNEL) {
  52411. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  52412. }
  52413. if (this._defines.FRESNEL) {
  52414. fallbacks.addFallback(3, "FRESNEL");
  52415. }
  52416. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  52417. fallbacks.addCPUSkinningFallback(0, mesh);
  52418. }
  52419. //Attributes
  52420. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52421. if (this._defines.NORMAL) {
  52422. attribs.push(BABYLON.VertexBuffer.NormalKind);
  52423. }
  52424. if (this._defines.UV1) {
  52425. attribs.push(BABYLON.VertexBuffer.UVKind);
  52426. }
  52427. if (this._defines.UV2) {
  52428. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52429. }
  52430. if (this._defines.VERTEXCOLOR) {
  52431. attribs.push(BABYLON.VertexBuffer.ColorKind);
  52432. }
  52433. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  52434. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  52435. // Legacy browser patch
  52436. var join = this._defines.toString();
  52437. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  52438. "vFogInfos", "vFogColor", "pointSize",
  52439. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  52440. "mBones",
  52441. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  52442. "depthValues",
  52443. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  52444. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  52445. "logarithmicDepthConstant",
  52446. "vSphericalX", "vSphericalY", "vSphericalZ",
  52447. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  52448. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  52449. "vMicrosurfaceTextureLods",
  52450. "vCameraInfos"
  52451. ];
  52452. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  52453. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  52454. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  52455. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  52456. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  52457. }
  52458. if (!this._effect.isReady()) {
  52459. return false;
  52460. }
  52461. this._renderId = scene.getRenderId();
  52462. this._wasPreviouslyReady = true;
  52463. if (mesh) {
  52464. if (!mesh._materialDefines) {
  52465. mesh._materialDefines = new PBRMaterialDefines();
  52466. }
  52467. this._defines.cloneTo(mesh._materialDefines);
  52468. }
  52469. return true;
  52470. };
  52471. PBRMaterial.prototype.unbind = function () {
  52472. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  52473. this._effect.setTexture("reflection2DSampler", null);
  52474. }
  52475. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  52476. this._effect.setTexture("refraction2DSampler", null);
  52477. }
  52478. _super.prototype.unbind.call(this);
  52479. };
  52480. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  52481. this._effect.setMatrix("world", world);
  52482. };
  52483. PBRMaterial.prototype.bind = function (world, mesh) {
  52484. this._myScene = this.getScene();
  52485. // Matrices
  52486. this.bindOnlyWorldMatrix(world);
  52487. // Bones
  52488. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  52489. if (this._myScene.getCachedMaterial() !== this) {
  52490. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  52491. if (BABYLON.StandardMaterial.FresnelEnabled) {
  52492. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  52493. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  52494. }
  52495. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  52496. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  52497. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  52498. }
  52499. }
  52500. // Textures
  52501. if (this._myScene.texturesEnabled) {
  52502. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  52503. this._effect.setTexture("albedoSampler", this.albedoTexture);
  52504. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  52505. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  52506. }
  52507. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  52508. this._effect.setTexture("ambientSampler", this.ambientTexture);
  52509. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  52510. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  52511. }
  52512. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  52513. this._effect.setTexture("opacitySampler", this.opacityTexture);
  52514. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  52515. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  52516. }
  52517. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  52518. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  52519. if (this.reflectionTexture.isCube) {
  52520. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  52521. }
  52522. else {
  52523. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  52524. }
  52525. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  52526. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  52527. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  52528. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  52529. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  52530. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  52531. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  52532. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  52533. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  52534. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  52535. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  52536. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  52537. }
  52538. }
  52539. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  52540. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  52541. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  52542. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  52543. }
  52544. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  52545. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  52546. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  52547. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  52548. }
  52549. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  52550. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  52551. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  52552. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  52553. }
  52554. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  52555. this._effect.setTexture("bumpSampler", this.bumpTexture);
  52556. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  52557. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  52558. }
  52559. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  52560. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  52561. var depth = 1.0;
  52562. if (this.refractionTexture.isCube) {
  52563. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  52564. }
  52565. else {
  52566. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  52567. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  52568. if (this.refractionTexture.depth) {
  52569. depth = this.refractionTexture.depth;
  52570. }
  52571. }
  52572. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  52573. }
  52574. if ((this.reflectionTexture || this.refractionTexture)) {
  52575. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  52576. }
  52577. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  52578. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  52579. }
  52580. }
  52581. // Clip plane
  52582. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  52583. // Point size
  52584. if (this.pointsCloud) {
  52585. this._effect.setFloat("pointSize", this.pointSize);
  52586. }
  52587. // Colors
  52588. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  52589. // GAMMA CORRECTION.
  52590. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  52591. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  52592. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  52593. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  52594. // GAMMA CORRECTION.
  52595. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  52596. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  52597. // GAMMA CORRECTION.
  52598. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  52599. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  52600. }
  52601. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  52602. // GAMMA CORRECTION.
  52603. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  52604. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  52605. // Lights
  52606. if (this._myScene.lightsEnabled && !this.disableLighting) {
  52607. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  52608. }
  52609. // View
  52610. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  52611. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  52612. }
  52613. // Fog
  52614. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  52615. this._lightingInfos.x = this.directIntensity;
  52616. this._lightingInfos.y = this.emissiveIntensity;
  52617. this._lightingInfos.z = this.environmentIntensity;
  52618. this._lightingInfos.w = this.specularIntensity;
  52619. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  52620. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  52621. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  52622. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  52623. this._cameraInfos.x = this.cameraExposure;
  52624. this._cameraInfos.y = this.cameraContrast;
  52625. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  52626. if (this.cameraColorCurves) {
  52627. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  52628. }
  52629. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  52630. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  52631. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  52632. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  52633. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  52634. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  52635. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  52636. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  52637. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  52638. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  52639. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  52640. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  52641. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  52642. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  52643. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  52644. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  52645. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  52646. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  52647. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  52648. // Log. depth
  52649. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  52650. }
  52651. _super.prototype.bind.call(this, world, mesh);
  52652. this._myScene = null;
  52653. };
  52654. PBRMaterial.prototype.getAnimatables = function () {
  52655. var results = [];
  52656. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  52657. results.push(this.albedoTexture);
  52658. }
  52659. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  52660. results.push(this.ambientTexture);
  52661. }
  52662. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  52663. results.push(this.opacityTexture);
  52664. }
  52665. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  52666. results.push(this.reflectionTexture);
  52667. }
  52668. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  52669. results.push(this.emissiveTexture);
  52670. }
  52671. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  52672. results.push(this.reflectivityTexture);
  52673. }
  52674. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  52675. results.push(this.bumpTexture);
  52676. }
  52677. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  52678. results.push(this.lightmapTexture);
  52679. }
  52680. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  52681. results.push(this.refractionTexture);
  52682. }
  52683. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  52684. results.push(this.cameraColorGradingTexture);
  52685. }
  52686. return results;
  52687. };
  52688. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  52689. if (forceDisposeTextures) {
  52690. if (this.albedoTexture) {
  52691. this.albedoTexture.dispose();
  52692. }
  52693. if (this.ambientTexture) {
  52694. this.ambientTexture.dispose();
  52695. }
  52696. if (this.opacityTexture) {
  52697. this.opacityTexture.dispose();
  52698. }
  52699. if (this.reflectionTexture) {
  52700. this.reflectionTexture.dispose();
  52701. }
  52702. if (this.emissiveTexture) {
  52703. this.emissiveTexture.dispose();
  52704. }
  52705. if (this.reflectivityTexture) {
  52706. this.reflectivityTexture.dispose();
  52707. }
  52708. if (this.bumpTexture) {
  52709. this.bumpTexture.dispose();
  52710. }
  52711. if (this.lightmapTexture) {
  52712. this.lightmapTexture.dispose();
  52713. }
  52714. if (this.refractionTexture) {
  52715. this.refractionTexture.dispose();
  52716. }
  52717. if (this.cameraColorGradingTexture) {
  52718. this.cameraColorGradingTexture.dispose();
  52719. }
  52720. }
  52721. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  52722. };
  52723. PBRMaterial.prototype.clone = function (name) {
  52724. var _this = this;
  52725. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  52726. };
  52727. PBRMaterial.prototype.serialize = function () {
  52728. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  52729. serializationObject.customType = "BABYLON.PBRMaterial";
  52730. return serializationObject;
  52731. };
  52732. // Statics
  52733. PBRMaterial.Parse = function (source, scene, rootUrl) {
  52734. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  52735. };
  52736. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  52737. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  52738. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  52739. PBRMaterial._scaledReflection = new BABYLON.Color3();
  52740. __decorate([
  52741. BABYLON.serialize()
  52742. ], PBRMaterial.prototype, "directIntensity", void 0);
  52743. __decorate([
  52744. BABYLON.serialize()
  52745. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  52746. __decorate([
  52747. BABYLON.serialize()
  52748. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  52749. __decorate([
  52750. BABYLON.serialize()
  52751. ], PBRMaterial.prototype, "specularIntensity", void 0);
  52752. __decorate([
  52753. BABYLON.serialize()
  52754. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  52755. __decorate([
  52756. BABYLON.serialize()
  52757. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  52758. __decorate([
  52759. BABYLON.serialize()
  52760. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  52761. __decorate([
  52762. BABYLON.serialize()
  52763. ], PBRMaterial.prototype, "cameraExposure", void 0);
  52764. __decorate([
  52765. BABYLON.serialize()
  52766. ], PBRMaterial.prototype, "cameraContrast", void 0);
  52767. __decorate([
  52768. BABYLON.serializeAsTexture()
  52769. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  52770. __decorate([
  52771. BABYLON.serializeAsColorCurves()
  52772. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  52773. __decorate([
  52774. BABYLON.serializeAsColor3()
  52775. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  52776. __decorate([
  52777. BABYLON.serialize()
  52778. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  52779. __decorate([
  52780. BABYLON.serializeAsColor3()
  52781. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  52782. __decorate([
  52783. BABYLON.serialize()
  52784. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  52785. __decorate([
  52786. BABYLON.serializeAsColor3()
  52787. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  52788. __decorate([
  52789. BABYLON.serialize()
  52790. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  52791. __decorate([
  52792. BABYLON.serializeAsColor3()
  52793. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  52794. __decorate([
  52795. BABYLON.serialize()
  52796. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  52797. __decorate([
  52798. BABYLON.serializeAsColor3()
  52799. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  52800. __decorate([
  52801. BABYLON.serialize()
  52802. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  52803. __decorate([
  52804. BABYLON.serialize()
  52805. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  52806. __decorate([
  52807. BABYLON.serialize()
  52808. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  52809. __decorate([
  52810. BABYLON.serializeAsTexture()
  52811. ], PBRMaterial.prototype, "albedoTexture", void 0);
  52812. __decorate([
  52813. BABYLON.serializeAsTexture()
  52814. ], PBRMaterial.prototype, "ambientTexture", void 0);
  52815. __decorate([
  52816. BABYLON.serialize()
  52817. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  52818. __decorate([
  52819. BABYLON.serializeAsTexture()
  52820. ], PBRMaterial.prototype, "opacityTexture", void 0);
  52821. __decorate([
  52822. BABYLON.serializeAsTexture()
  52823. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  52824. __decorate([
  52825. BABYLON.serializeAsTexture()
  52826. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  52827. __decorate([
  52828. BABYLON.serializeAsTexture()
  52829. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  52830. __decorate([
  52831. BABYLON.serializeAsTexture()
  52832. ], PBRMaterial.prototype, "bumpTexture", void 0);
  52833. __decorate([
  52834. BABYLON.serializeAsTexture()
  52835. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  52836. __decorate([
  52837. BABYLON.serializeAsTexture()
  52838. ], PBRMaterial.prototype, "refractionTexture", void 0);
  52839. __decorate([
  52840. BABYLON.serializeAsColor3("ambient")
  52841. ], PBRMaterial.prototype, "ambientColor", void 0);
  52842. __decorate([
  52843. BABYLON.serializeAsColor3("albedo")
  52844. ], PBRMaterial.prototype, "albedoColor", void 0);
  52845. __decorate([
  52846. BABYLON.serializeAsColor3("reflectivity")
  52847. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  52848. __decorate([
  52849. BABYLON.serializeAsColor3("reflection")
  52850. ], PBRMaterial.prototype, "reflectionColor", void 0);
  52851. __decorate([
  52852. BABYLON.serializeAsColor3("emissive")
  52853. ], PBRMaterial.prototype, "emissiveColor", void 0);
  52854. __decorate([
  52855. BABYLON.serialize()
  52856. ], PBRMaterial.prototype, "microSurface", void 0);
  52857. __decorate([
  52858. BABYLON.serialize()
  52859. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  52860. __decorate([
  52861. BABYLON.serialize()
  52862. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  52863. __decorate([
  52864. BABYLON.serializeAsFresnelParameters()
  52865. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  52866. __decorate([
  52867. BABYLON.serializeAsFresnelParameters()
  52868. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  52869. __decorate([
  52870. BABYLON.serialize()
  52871. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  52872. __decorate([
  52873. BABYLON.serialize()
  52874. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  52875. __decorate([
  52876. BABYLON.serialize()
  52877. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  52878. __decorate([
  52879. BABYLON.serialize()
  52880. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  52881. __decorate([
  52882. BABYLON.serialize()
  52883. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  52884. __decorate([
  52885. BABYLON.serialize()
  52886. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  52887. __decorate([
  52888. BABYLON.serialize()
  52889. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  52890. __decorate([
  52891. BABYLON.serialize()
  52892. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  52893. __decorate([
  52894. BABYLON.serialize()
  52895. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  52896. __decorate([
  52897. BABYLON.serialize()
  52898. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  52899. __decorate([
  52900. BABYLON.serialize()
  52901. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  52902. __decorate([
  52903. BABYLON.serialize()
  52904. ], PBRMaterial.prototype, "useParallax", void 0);
  52905. __decorate([
  52906. BABYLON.serialize()
  52907. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  52908. __decorate([
  52909. BABYLON.serialize()
  52910. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  52911. __decorate([
  52912. BABYLON.serialize()
  52913. ], PBRMaterial.prototype, "disableLighting", void 0);
  52914. __decorate([
  52915. BABYLON.serialize()
  52916. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  52917. __decorate([
  52918. BABYLON.serialize()
  52919. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  52920. __decorate([
  52921. BABYLON.serialize()
  52922. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  52923. __decorate([
  52924. BABYLON.serialize()
  52925. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  52926. return PBRMaterial;
  52927. }(BABYLON.Material));
  52928. BABYLON.PBRMaterial = PBRMaterial;
  52929. })(BABYLON || (BABYLON = {}));
  52930. var BABYLON;
  52931. (function (BABYLON) {
  52932. var DebugLayer = (function () {
  52933. function DebugLayer(scene) {
  52934. var _this = this;
  52935. this._transformationMatrix = BABYLON.Matrix.Identity();
  52936. this._enabled = false;
  52937. this._labelsEnabled = false;
  52938. this._displayStatistics = true;
  52939. this._displayTree = false;
  52940. this._displayLogs = false;
  52941. this._skeletonViewers = new Array();
  52942. this._identityMatrix = BABYLON.Matrix.Identity();
  52943. this.axisRatio = 0.02;
  52944. this.accentColor = "orange";
  52945. this._scene = scene;
  52946. this._syncPositions = function () {
  52947. var engine = _this._scene.getEngine();
  52948. var canvasRect = engine.getRenderingCanvasClientRect();
  52949. if (_this._showUI) {
  52950. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  52951. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  52952. _this._statsDiv.style.width = "400px";
  52953. _this._statsDiv.style.height = "auto";
  52954. _this._statsSubsetDiv.style.maxHeight = "240px";
  52955. _this._optionsDiv.style.left = "0px";
  52956. _this._optionsDiv.style.top = "10px";
  52957. _this._optionsDiv.style.width = "200px";
  52958. _this._optionsDiv.style.height = "auto";
  52959. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  52960. _this._logDiv.style.left = "0px";
  52961. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  52962. _this._logDiv.style.width = "600px";
  52963. _this._logDiv.style.height = "160px";
  52964. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  52965. _this._treeDiv.style.top = "10px";
  52966. _this._treeDiv.style.width = "300px";
  52967. _this._treeDiv.style.height = "auto";
  52968. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  52969. }
  52970. _this._globalDiv.style.left = canvasRect.left + "px";
  52971. _this._globalDiv.style.top = canvasRect.top + "px";
  52972. _this._drawingCanvas.style.left = "0px";
  52973. _this._drawingCanvas.style.top = "0px";
  52974. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  52975. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  52976. var devicePixelRatio = window.devicePixelRatio || 1;
  52977. var context = _this._drawingContext;
  52978. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  52979. context.mozBackingStorePixelRatio ||
  52980. context.msBackingStorePixelRatio ||
  52981. context.oBackingStorePixelRatio ||
  52982. context.backingStorePixelRatio || 1;
  52983. _this._ratio = devicePixelRatio / backingStoreRatio;
  52984. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  52985. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  52986. };
  52987. this._onCanvasClick = function (evt) {
  52988. _this._clickPosition = {
  52989. x: evt.clientX * _this._ratio,
  52990. y: evt.clientY * _this._ratio
  52991. };
  52992. };
  52993. this._syncUI = function () {
  52994. if (_this._showUI) {
  52995. if (_this._displayStatistics) {
  52996. _this._displayStats();
  52997. _this._statsDiv.style.display = "";
  52998. }
  52999. else {
  53000. _this._statsDiv.style.display = "none";
  53001. }
  53002. if (_this._displayLogs) {
  53003. _this._logDiv.style.display = "";
  53004. }
  53005. else {
  53006. _this._logDiv.style.display = "none";
  53007. }
  53008. if (_this._displayTree) {
  53009. _this._treeDiv.style.display = "";
  53010. if (_this._needToRefreshMeshesTree) {
  53011. _this._needToRefreshMeshesTree = false;
  53012. _this._refreshMeshesTreeContent();
  53013. }
  53014. }
  53015. else {
  53016. _this._treeDiv.style.display = "none";
  53017. }
  53018. }
  53019. };
  53020. this._syncData = function () {
  53021. if (_this._labelsEnabled || !_this._showUI) {
  53022. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  53023. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  53024. var engine = _this._scene.getEngine();
  53025. var viewport = _this._camera.viewport;
  53026. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  53027. // Meshes
  53028. var meshes = _this._camera.getActiveMeshes();
  53029. var index;
  53030. var projectedPosition;
  53031. for (index = 0; index < meshes.length; index++) {
  53032. var mesh = meshes.data[index];
  53033. var position = mesh.getBoundingInfo().boundingSphere.center;
  53034. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  53035. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  53036. _this._renderAxis(projectedPosition, mesh, globalViewport);
  53037. }
  53038. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  53039. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  53040. }
  53041. }
  53042. // Cameras
  53043. var cameras = _this._scene.cameras;
  53044. for (index = 0; index < cameras.length; index++) {
  53045. var camera = cameras[index];
  53046. if (camera === _this._camera) {
  53047. continue;
  53048. }
  53049. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  53050. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  53051. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  53052. _this._camera.detachControl(engine.getRenderingCanvas());
  53053. _this._camera = camera;
  53054. _this._camera.attachControl(engine.getRenderingCanvas());
  53055. }, function () { return "purple"; });
  53056. }
  53057. }
  53058. // Lights
  53059. var lights = _this._scene.lights;
  53060. for (index = 0; index < lights.length; index++) {
  53061. var light = lights[index];
  53062. if (light.position) {
  53063. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  53064. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  53065. _this._renderLabel(light.name, projectedPosition, -20, function () {
  53066. light.setEnabled(!light.isEnabled());
  53067. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  53068. }
  53069. }
  53070. }
  53071. }
  53072. _this._clickPosition = undefined;
  53073. };
  53074. }
  53075. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  53076. while (this._treeSubsetDiv.hasChildNodes()) {
  53077. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  53078. }
  53079. // Add meshes
  53080. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  53081. sortedArray.sort(function (a, b) {
  53082. if (a.name === b.name) {
  53083. return 0;
  53084. }
  53085. return (a.name > b.name) ? 1 : -1;
  53086. });
  53087. for (var index = 0; index < sortedArray.length; index++) {
  53088. var mesh = sortedArray[index];
  53089. if (!mesh.isEnabled()) {
  53090. continue;
  53091. }
  53092. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  53093. m.isVisible = element.checked;
  53094. }, mesh);
  53095. }
  53096. };
  53097. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  53098. this._drawingContext.beginPath();
  53099. this._drawingContext.moveTo(zero.x, zero.y);
  53100. this._drawingContext.lineTo(unit.x, unit.y);
  53101. this._drawingContext.strokeStyle = color;
  53102. this._drawingContext.lineWidth = 4;
  53103. this._drawingContext.stroke();
  53104. this._drawingContext.font = "normal 14px Segoe UI";
  53105. this._drawingContext.fillStyle = color;
  53106. this._drawingContext.fillText(label, unitText.x, unitText.y);
  53107. };
  53108. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  53109. var position = mesh.getBoundingInfo().boundingSphere.center;
  53110. var worldMatrix = mesh.getWorldMatrix();
  53111. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  53112. var unit = (unprojectedVector.subtract(position)).length();
  53113. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  53114. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  53115. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  53116. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  53117. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  53118. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  53119. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  53120. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  53121. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  53122. };
  53123. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  53124. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  53125. this._drawingContext.font = "normal 12px Segoe UI";
  53126. var textMetrics = this._drawingContext.measureText(text);
  53127. var centerX = projectedPosition.x - textMetrics.width / 2;
  53128. var centerY = projectedPosition.y;
  53129. var clientRect = this._drawingCanvas.getBoundingClientRect();
  53130. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  53131. onClick();
  53132. }
  53133. this._drawingContext.beginPath();
  53134. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  53135. this._drawingContext.fillStyle = getFillStyle();
  53136. this._drawingContext.globalAlpha = 0.5;
  53137. this._drawingContext.fill();
  53138. this._drawingContext.globalAlpha = 1.0;
  53139. this._drawingContext.strokeStyle = '#FFFFFF';
  53140. this._drawingContext.lineWidth = 1;
  53141. this._drawingContext.stroke();
  53142. this._drawingContext.fillStyle = "#FFFFFF";
  53143. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  53144. this._drawingContext.beginPath();
  53145. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  53146. this._drawingContext.fill();
  53147. }
  53148. };
  53149. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  53150. if (!this._clickPosition) {
  53151. return false;
  53152. }
  53153. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  53154. return false;
  53155. }
  53156. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  53157. return false;
  53158. }
  53159. return true;
  53160. };
  53161. DebugLayer.prototype.isVisible = function () {
  53162. return this._enabled;
  53163. };
  53164. DebugLayer.prototype.hide = function () {
  53165. if (!this._enabled) {
  53166. return;
  53167. }
  53168. this._enabled = false;
  53169. var engine = this._scene.getEngine();
  53170. this._scene.unregisterBeforeRender(this._syncData);
  53171. this._scene.unregisterAfterRender(this._syncUI);
  53172. this._rootElement.removeChild(this._globalDiv);
  53173. this._scene.forceShowBoundingBoxes = false;
  53174. this._scene.forceWireframe = false;
  53175. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  53176. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  53177. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  53178. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  53179. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  53180. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  53181. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  53182. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  53183. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  53184. BABYLON.StandardMaterial.ColorGradingTextureEnabled = true;
  53185. this._scene.shadowsEnabled = true;
  53186. this._scene.particlesEnabled = true;
  53187. this._scene.postProcessesEnabled = true;
  53188. this._scene.collisionsEnabled = true;
  53189. this._scene.lightsEnabled = true;
  53190. this._scene.texturesEnabled = true;
  53191. this._scene.lensFlaresEnabled = true;
  53192. this._scene.proceduralTexturesEnabled = true;
  53193. this._scene.renderTargetsEnabled = true;
  53194. this._scene.probesEnabled = true;
  53195. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  53196. this._clearSkeletonViewers();
  53197. };
  53198. DebugLayer.prototype._clearSkeletonViewers = function () {
  53199. for (var index = 0; index < this._skeletonViewers.length; index++) {
  53200. this._skeletonViewers[index].dispose();
  53201. }
  53202. this._skeletonViewers = [];
  53203. };
  53204. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  53205. if (showUI === void 0) { showUI = true; }
  53206. if (camera === void 0) { camera = null; }
  53207. if (rootElement === void 0) { rootElement = null; }
  53208. if (this._enabled) {
  53209. return;
  53210. }
  53211. this._enabled = true;
  53212. if (camera) {
  53213. this._camera = camera;
  53214. }
  53215. else {
  53216. this._camera = this._scene.activeCamera;
  53217. }
  53218. this._showUI = showUI;
  53219. var engine = this._scene.getEngine();
  53220. this._globalDiv = document.createElement("div");
  53221. this._rootElement = rootElement || document.body;
  53222. this._rootElement.appendChild(this._globalDiv);
  53223. this._generateDOMelements();
  53224. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  53225. this._syncPositions();
  53226. this._scene.registerBeforeRender(this._syncData);
  53227. this._scene.registerAfterRender(this._syncUI);
  53228. };
  53229. DebugLayer.prototype._clearLabels = function () {
  53230. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  53231. for (var index = 0; index < this._scene.meshes.length; index++) {
  53232. var mesh = this._scene.meshes[index];
  53233. mesh.renderOverlay = false;
  53234. }
  53235. };
  53236. DebugLayer.prototype._generateheader = function (root, text) {
  53237. var header = document.createElement("div");
  53238. header.innerHTML = text + "&nbsp;";
  53239. header.style.textAlign = "right";
  53240. header.style.width = "100%";
  53241. header.style.color = "white";
  53242. header.style.backgroundColor = "Black";
  53243. header.style.padding = "5px 5px 4px 0px";
  53244. header.style.marginLeft = "-5px";
  53245. header.style.fontWeight = "bold";
  53246. root.appendChild(header);
  53247. };
  53248. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  53249. var label = document.createElement("label");
  53250. label.style.display = "inline";
  53251. label.innerHTML = title;
  53252. label.style.color = color;
  53253. root.appendChild(label);
  53254. root.appendChild(document.createElement("br"));
  53255. };
  53256. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  53257. if (tag === void 0) { tag = null; }
  53258. var label = document.createElement("label");
  53259. label.style.display = "inline";
  53260. var boundingBoxesCheckbox = document.createElement("input");
  53261. boundingBoxesCheckbox.type = "checkbox";
  53262. boundingBoxesCheckbox.checked = initialState;
  53263. boundingBoxesCheckbox.style.display = "inline";
  53264. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  53265. boundingBoxesCheckbox.style.verticalAlign = "sub";
  53266. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  53267. task(evt.target, tag);
  53268. });
  53269. label.appendChild(boundingBoxesCheckbox);
  53270. var container = document.createElement("span");
  53271. var leftPart = document.createElement("span");
  53272. var rightPart = document.createElement("span");
  53273. rightPart.style.cssFloat = "right";
  53274. leftPart.innerHTML = leftTitle;
  53275. rightPart.innerHTML = rightTitle;
  53276. rightPart.style.fontSize = "12px";
  53277. rightPart.style.maxWidth = "200px";
  53278. container.appendChild(leftPart);
  53279. container.appendChild(rightPart);
  53280. label.appendChild(container);
  53281. root.appendChild(label);
  53282. root.appendChild(document.createElement("br"));
  53283. };
  53284. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  53285. if (tag === void 0) { tag = null; }
  53286. var label = document.createElement("label");
  53287. label.style.display = "inline";
  53288. var checkBox = document.createElement("input");
  53289. checkBox.type = "checkbox";
  53290. checkBox.checked = initialState;
  53291. checkBox.style.display = "inline";
  53292. checkBox.style.margin = "0px 5px 0px 0px";
  53293. checkBox.style.verticalAlign = "sub";
  53294. checkBox.addEventListener("change", function (evt) {
  53295. task(evt.target, tag);
  53296. });
  53297. label.appendChild(checkBox);
  53298. label.appendChild(document.createTextNode(title));
  53299. root.appendChild(label);
  53300. root.appendChild(document.createElement("br"));
  53301. };
  53302. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  53303. if (tag === void 0) { tag = null; }
  53304. var button = document.createElement("button");
  53305. button.innerHTML = title;
  53306. button.style.height = "24px";
  53307. button.style.width = "150px";
  53308. button.style.marginBottom = "5px";
  53309. button.style.color = "#444444";
  53310. button.style.border = "1px solid white";
  53311. button.className = "debugLayerButton";
  53312. button.addEventListener("click", function (evt) {
  53313. task(evt.target, tag);
  53314. });
  53315. root.appendChild(button);
  53316. root.appendChild(document.createElement("br"));
  53317. };
  53318. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  53319. if (tag === void 0) { tag = null; }
  53320. var label = document.createElement("label");
  53321. label.style.display = "inline";
  53322. var boundingBoxesRadio = document.createElement("input");
  53323. boundingBoxesRadio.type = "radio";
  53324. boundingBoxesRadio.name = name;
  53325. boundingBoxesRadio.checked = initialState;
  53326. boundingBoxesRadio.style.display = "inline";
  53327. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  53328. boundingBoxesRadio.style.verticalAlign = "sub";
  53329. boundingBoxesRadio.addEventListener("change", function (evt) {
  53330. task(evt.target, tag);
  53331. });
  53332. label.appendChild(boundingBoxesRadio);
  53333. label.appendChild(document.createTextNode(title));
  53334. root.appendChild(label);
  53335. root.appendChild(document.createElement("br"));
  53336. };
  53337. DebugLayer.prototype._generateDOMelements = function () {
  53338. var _this = this;
  53339. this._globalDiv.id = "DebugLayer";
  53340. this._globalDiv.style.position = "absolute";
  53341. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  53342. this._globalDiv.style.fontSize = "14px";
  53343. this._globalDiv.style.color = "white";
  53344. // Drawing canvas
  53345. this._drawingCanvas = document.createElement("canvas");
  53346. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  53347. this._drawingCanvas.style.position = "absolute";
  53348. this._drawingCanvas.style.pointerEvents = "none";
  53349. this._drawingCanvas.style.backgroundColor = "transparent";
  53350. this._drawingContext = this._drawingCanvas.getContext("2d");
  53351. this._globalDiv.appendChild(this._drawingCanvas);
  53352. if (this._showUI) {
  53353. var background = "rgba(128, 128, 128, 0.4)";
  53354. var border = "rgb(180, 180, 180) solid 1px";
  53355. // Stats
  53356. this._statsDiv = document.createElement("div");
  53357. this._statsDiv.id = "DebugLayerStats";
  53358. this._statsDiv.style.border = border;
  53359. this._statsDiv.style.position = "absolute";
  53360. this._statsDiv.style.background = background;
  53361. this._statsDiv.style.padding = "0px 0px 0px 5px";
  53362. this._generateheader(this._statsDiv, "STATISTICS");
  53363. this._statsSubsetDiv = document.createElement("div");
  53364. this._statsSubsetDiv.style.paddingTop = "5px";
  53365. this._statsSubsetDiv.style.paddingBottom = "5px";
  53366. this._statsSubsetDiv.style.overflowY = "auto";
  53367. this._statsDiv.appendChild(this._statsSubsetDiv);
  53368. // Tree
  53369. this._treeDiv = document.createElement("div");
  53370. this._treeDiv.id = "DebugLayerTree";
  53371. this._treeDiv.style.border = border;
  53372. this._treeDiv.style.position = "absolute";
  53373. this._treeDiv.style.background = background;
  53374. this._treeDiv.style.padding = "0px 0px 0px 5px";
  53375. this._treeDiv.style.display = "none";
  53376. this._generateheader(this._treeDiv, "MESHES TREE");
  53377. this._treeSubsetDiv = document.createElement("div");
  53378. this._treeSubsetDiv.style.paddingTop = "5px";
  53379. this._treeSubsetDiv.style.paddingRight = "5px";
  53380. this._treeSubsetDiv.style.overflowY = "auto";
  53381. this._treeSubsetDiv.style.maxHeight = "300px";
  53382. this._treeDiv.appendChild(this._treeSubsetDiv);
  53383. this._needToRefreshMeshesTree = true;
  53384. // Logs
  53385. this._logDiv = document.createElement("div");
  53386. this._logDiv.style.border = border;
  53387. this._logDiv.id = "DebugLayerLogs";
  53388. this._logDiv.style.position = "absolute";
  53389. this._logDiv.style.background = background;
  53390. this._logDiv.style.padding = "0px 0px 0px 5px";
  53391. this._logDiv.style.display = "none";
  53392. this._generateheader(this._logDiv, "LOGS");
  53393. this._logSubsetDiv = document.createElement("div");
  53394. this._logSubsetDiv.style.height = "127px";
  53395. this._logSubsetDiv.style.paddingTop = "5px";
  53396. this._logSubsetDiv.style.overflowY = "auto";
  53397. this._logSubsetDiv.style.fontSize = "12px";
  53398. this._logSubsetDiv.style.fontFamily = "consolas";
  53399. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  53400. this._logDiv.appendChild(this._logSubsetDiv);
  53401. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  53402. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  53403. };
  53404. // Options
  53405. this._optionsDiv = document.createElement("div");
  53406. this._optionsDiv.id = "DebugLayerOptions";
  53407. this._optionsDiv.style.border = border;
  53408. this._optionsDiv.style.position = "absolute";
  53409. this._optionsDiv.style.background = background;
  53410. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  53411. this._optionsDiv.style.overflowY = "auto";
  53412. this._generateheader(this._optionsDiv, "OPTIONS");
  53413. this._optionsSubsetDiv = document.createElement("div");
  53414. this._optionsSubsetDiv.style.paddingTop = "5px";
  53415. this._optionsSubsetDiv.style.paddingBottom = "5px";
  53416. this._optionsSubsetDiv.style.overflowY = "auto";
  53417. this._optionsSubsetDiv.style.maxHeight = "200px";
  53418. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  53419. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  53420. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  53421. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  53422. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  53423. _this._displayTree = element.checked;
  53424. _this._needToRefreshMeshesTree = true;
  53425. });
  53426. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53427. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  53428. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  53429. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  53430. _this._labelsEnabled = element.checked;
  53431. if (!_this._labelsEnabled) {
  53432. _this._clearLabels();
  53433. }
  53434. });
  53435. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  53436. if (element.checked) {
  53437. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  53438. }
  53439. else {
  53440. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  53441. }
  53442. });
  53443. ;
  53444. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53445. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  53446. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  53447. if (element.checked) {
  53448. _this._scene.forceWireframe = false;
  53449. _this._scene.forcePointsCloud = false;
  53450. }
  53451. });
  53452. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  53453. if (element.checked) {
  53454. _this._scene.forceWireframe = true;
  53455. _this._scene.forcePointsCloud = false;
  53456. }
  53457. });
  53458. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  53459. if (element.checked) {
  53460. _this._scene.forceWireframe = false;
  53461. _this._scene.forcePointsCloud = true;
  53462. }
  53463. });
  53464. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53465. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  53466. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  53467. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  53468. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  53469. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  53470. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  53471. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  53472. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  53473. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  53474. this._generateCheckBox(this._optionsSubsetDiv, "ColorGrading", BABYLON.StandardMaterial.ColorGradingTextureEnabled, function (element) { BABYLON.StandardMaterial.ColorGradingTextureEnabled = element.checked; });
  53475. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  53476. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  53477. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53478. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  53479. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  53480. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  53481. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  53482. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  53483. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  53484. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  53485. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  53486. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  53487. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  53488. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  53489. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  53490. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  53491. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  53492. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  53493. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  53494. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53495. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  53496. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  53497. if (element.checked) {
  53498. _this._scene.headphone = true;
  53499. }
  53500. });
  53501. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  53502. if (element.checked) {
  53503. _this._scene.headphone = false;
  53504. }
  53505. });
  53506. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  53507. _this._scene.audioEnabled = !element.checked;
  53508. });
  53509. }
  53510. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53511. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  53512. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  53513. if (!element.checked) {
  53514. _this._clearSkeletonViewers();
  53515. return;
  53516. }
  53517. for (var index = 0; index < _this._scene.meshes.length; index++) {
  53518. var mesh = _this._scene.meshes[index];
  53519. if (mesh.skeleton) {
  53520. var found = false;
  53521. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  53522. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  53523. found = true;
  53524. break;
  53525. }
  53526. }
  53527. if (found) {
  53528. continue;
  53529. }
  53530. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  53531. viewer.isEnabled = true;
  53532. _this._skeletonViewers.push(viewer);
  53533. }
  53534. }
  53535. });
  53536. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53537. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  53538. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  53539. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  53540. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  53541. if (_this._camera) {
  53542. console.log(_this._camera);
  53543. }
  53544. else {
  53545. console.warn("No camera defined, or debug layer created before camera creation!");
  53546. }
  53547. });
  53548. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53549. this._globalDiv.appendChild(this._statsDiv);
  53550. this._globalDiv.appendChild(this._logDiv);
  53551. this._globalDiv.appendChild(this._optionsDiv);
  53552. this._globalDiv.appendChild(this._treeDiv);
  53553. }
  53554. };
  53555. DebugLayer.prototype._displayStats = function () {
  53556. var scene = this._scene;
  53557. var engine = scene.getEngine();
  53558. var glInfo = engine.getGlInfo();
  53559. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  53560. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  53561. + "<b>Count</b><br>"
  53562. + "Total meshes: " + scene.meshes.length + "<br>"
  53563. + "Total lights: " + scene.lights.length + "<br>"
  53564. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  53565. + "Total materials: " + scene.materials.length + "<br>"
  53566. + "Total textures: " + scene.textures.length + "<br>"
  53567. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  53568. + "Active indices: " + scene.getActiveIndices() + "<br>"
  53569. + "Active bones: " + scene.getActiveBones() + "<br>"
  53570. + "Active particles: " + scene.getActiveParticles() + "<br>"
  53571. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  53572. + "<b>Duration</b><br>"
  53573. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  53574. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  53575. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  53576. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  53577. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  53578. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  53579. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  53580. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  53581. + "</div>"
  53582. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  53583. + "<b>Extensions</b><br>"
  53584. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  53585. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  53586. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  53587. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  53588. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  53589. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  53590. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  53591. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  53592. + "</div><br>"
  53593. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  53594. + "<b>Caps.</b><br>"
  53595. + "Stencil: " + (engine.isStencilEnable ? "Enabled" : "Disabled") + "<br>"
  53596. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  53597. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  53598. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  53599. + "<b>Info</b><br>"
  53600. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  53601. + glInfo.version + "<br>"
  53602. + "</div><br>"
  53603. + glInfo.renderer + "<br>";
  53604. if (this.customStatsFunction) {
  53605. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  53606. }
  53607. };
  53608. return DebugLayer;
  53609. }());
  53610. BABYLON.DebugLayer = DebugLayer;
  53611. })(BABYLON || (BABYLON = {}));
  53612. var BABYLON;
  53613. (function (BABYLON) {
  53614. var StandardRenderingPipeline = (function (_super) {
  53615. __extends(StandardRenderingPipeline, _super);
  53616. /**
  53617. * @constructor
  53618. * @param {string} name - The rendering pipeline name
  53619. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53620. * @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)
  53621. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  53622. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53623. */
  53624. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  53625. var _this = this;
  53626. if (originalPostProcess === void 0) { originalPostProcess = null; }
  53627. _super.call(this, scene.getEngine(), name);
  53628. this.downSampleX4PostProcess = null;
  53629. this.brightPassPostProcess = null;
  53630. this.gaussianBlurHPostProcesses = [];
  53631. this.gaussianBlurVPostProcesses = [];
  53632. this.textureAdderPostProcess = null;
  53633. this.textureAdderFinalPostProcess = null;
  53634. this.lensFlarePostProcess = null;
  53635. this.lensFlareComposePostProcess = null;
  53636. this.depthOfFieldPostProcess = null;
  53637. // Values
  53638. this.brightThreshold = 1.0;
  53639. this.blurWidth = 2.0;
  53640. this.gaussianCoefficient = 0.25;
  53641. this.gaussianMean = 1.0;
  53642. this.gaussianStandardDeviation = 1.0;
  53643. this.exposure = 1.0;
  53644. this.lensTexture = null;
  53645. this.lensColorTexture = null;
  53646. this.lensFlareStrength = 20.0;
  53647. this.lensFlareGhostDispersal = 1.4;
  53648. this.lensFlareHaloWidth = 0.7;
  53649. this.lensFlareDistortionStrength = 16.0;
  53650. this.lensStarTexture = null;
  53651. this.lensFlareDirtTexture = null;
  53652. this.depthOfFieldDistance = 10.0;
  53653. // IAnimatable
  53654. this.animations = [];
  53655. this._depthRenderer = null;
  53656. // Getters and setters
  53657. this._depthOfFieldEnabled = true;
  53658. this._lensFlareEnabled = true;
  53659. // Initialize
  53660. this._scene = scene;
  53661. // Create pass post-processe
  53662. if (!originalPostProcess) {
  53663. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  53664. }
  53665. else {
  53666. this.originalPostProcess = originalPostProcess;
  53667. }
  53668. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  53669. // Create down sample X4 post-process
  53670. this._createDownSampleX4PostProcess(scene, ratio / 2);
  53671. // Create bright pass post-process
  53672. this._createBrightPassPostProcess(scene, ratio / 2);
  53673. // Create gaussian blur post-processes (down sampling blurs)
  53674. this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  53675. this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  53676. this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  53677. this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  53678. // Create texture adder post-process
  53679. this._createTextureAdderPostProcess(scene, ratio);
  53680. // Create depth-of-field source post-process
  53681. 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);
  53682. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  53683. // Create lens flare post-process
  53684. this._createLensFlarePostProcess(scene, ratio);
  53685. // Create gaussian blur used by depth-of-field
  53686. this._createGaussianBlurPostProcesses(scene, ratio / 2, 5);
  53687. // Create depth-of-field post-process
  53688. this._createDepthOfFieldPostProcess(scene, ratio);
  53689. // Finish
  53690. scene.postProcessRenderPipelineManager.addPipeline(this);
  53691. if (cameras !== null) {
  53692. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53693. }
  53694. // Deactivate
  53695. this.LensFlareEnabled = false;
  53696. this.DepthOfFieldEnabled = false;
  53697. }
  53698. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  53699. get: function () {
  53700. return this._depthOfFieldEnabled;
  53701. },
  53702. set: function (enabled) {
  53703. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  53704. if (enabled && !this._depthOfFieldEnabled) {
  53705. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  53706. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  53707. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  53708. this._depthRenderer = this._scene.enableDepthRenderer();
  53709. }
  53710. else if (!enabled && this._depthOfFieldEnabled) {
  53711. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  53712. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  53713. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  53714. }
  53715. this._depthOfFieldEnabled = enabled;
  53716. },
  53717. enumerable: true,
  53718. configurable: true
  53719. });
  53720. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  53721. get: function () {
  53722. return this._lensFlareEnabled;
  53723. },
  53724. set: function (enabled) {
  53725. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  53726. if (enabled && !this._lensFlareEnabled) {
  53727. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  53728. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  53729. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  53730. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  53731. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  53732. }
  53733. else if (!enabled && this._lensFlareEnabled) {
  53734. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  53735. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  53736. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  53737. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  53738. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  53739. }
  53740. this._lensFlareEnabled = enabled;
  53741. },
  53742. enumerable: true,
  53743. configurable: true
  53744. });
  53745. // Down Sample X4 Post-Processs
  53746. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  53747. var _this = this;
  53748. var downSampleX4Offsets = new Array(32);
  53749. 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);
  53750. this.downSampleX4PostProcess.onApply = function (effect) {
  53751. var id = 0;
  53752. for (var i = -2; i < 2; i++) {
  53753. for (var j = -2; j < 2; j++) {
  53754. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  53755. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  53756. id += 2;
  53757. }
  53758. }
  53759. effect.setArray2("dsOffsets", downSampleX4Offsets);
  53760. };
  53761. // Add to pipeline
  53762. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  53763. };
  53764. // Brightpass Post-Process
  53765. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  53766. var _this = this;
  53767. var brightOffsets = new Array(8);
  53768. 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);
  53769. this.brightPassPostProcess.onApply = function (effect) {
  53770. var sU = (1.0 / _this.brightPassPostProcess.width);
  53771. var sV = (1.0 / _this.brightPassPostProcess.height);
  53772. brightOffsets[0] = -0.5 * sU;
  53773. brightOffsets[1] = 0.5 * sV;
  53774. brightOffsets[2] = 0.5 * sU;
  53775. brightOffsets[3] = 0.5 * sV;
  53776. brightOffsets[4] = -0.5 * sU;
  53777. brightOffsets[5] = -0.5 * sV;
  53778. brightOffsets[6] = 0.5 * sU;
  53779. brightOffsets[7] = -0.5 * sV;
  53780. effect.setArray2("dsOffsets", brightOffsets);
  53781. effect.setFloat("brightThreshold", _this.brightThreshold);
  53782. };
  53783. // Add to pipeline
  53784. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  53785. };
  53786. // Create gaussian blur H&V post-processes
  53787. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  53788. var _this = this;
  53789. var blurOffsets = new Array(9);
  53790. var blurWeights = new Array(9);
  53791. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  53792. var callback = function (height) {
  53793. return function (effect) {
  53794. // Weights
  53795. var x = 0.0;
  53796. for (var i = 0; i < 9; i++) {
  53797. x = (i - 4.0) / 4.0;
  53798. blurWeights[i] =
  53799. _this.gaussianCoefficient
  53800. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  53801. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  53802. }
  53803. var lastOutputDimensions = {
  53804. width: scene.getEngine().getRenderWidth(),
  53805. height: scene.getEngine().getRenderHeight()
  53806. };
  53807. for (var i = 0; i < 9; i++) {
  53808. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  53809. blurOffsets[i] = value;
  53810. }
  53811. effect.setArray("blurOffsets", blurOffsets);
  53812. effect.setArray("blurWeights", blurWeights);
  53813. effect.setFloat("blurWidth", _this.blurWidth);
  53814. };
  53815. };
  53816. // Create horizontal gaussian blur post-processes
  53817. 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);
  53818. gaussianBlurHPostProcess.onApply = callback(false);
  53819. // Create vertical gaussian blur post-process
  53820. 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);
  53821. gaussianBlurVPostProcess.onApply = callback(true);
  53822. // Add to pipeline
  53823. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  53824. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  53825. // Finish
  53826. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  53827. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  53828. };
  53829. // Create texture adder post-process
  53830. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  53831. var _this = this;
  53832. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  53833. 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);
  53834. this.textureAdderPostProcess.onApply = function (effect) {
  53835. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  53836. effect.setTexture("lensSampler", _this.lensTexture);
  53837. effect.setFloat("exposure", _this.exposure);
  53838. };
  53839. // Add to pipeline
  53840. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  53841. };
  53842. // Create lens flare post-process
  53843. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  53844. var _this = this;
  53845. 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);
  53846. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, false));
  53847. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  53848. 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);
  53849. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, false));
  53850. var resolution = new BABYLON.Vector2(0, 0);
  53851. // Lens flare
  53852. this.lensFlarePostProcess.onApply = function (effect) {
  53853. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  53854. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  53855. effect.setFloat("strength", _this.lensFlareStrength);
  53856. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  53857. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  53858. // Shift
  53859. resolution.x = _this.lensFlarePostProcess.width;
  53860. resolution.y = _this.lensFlarePostProcess.height;
  53861. effect.setVector2("resolution", resolution);
  53862. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  53863. };
  53864. // Compose
  53865. 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);
  53866. 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);
  53867. this.lensFlareComposePostProcess.onApply = function (effect) {
  53868. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  53869. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  53870. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  53871. // Lens start rotation matrix
  53872. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  53873. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  53874. 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));
  53875. camRot *= 4.0;
  53876. 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);
  53877. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  53878. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  53879. };
  53880. };
  53881. // Create depth-of-field post-process
  53882. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  53883. var _this = this;
  53884. 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);
  53885. this.depthOfFieldPostProcess.onApply = function (effect) {
  53886. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  53887. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  53888. effect.setFloat("distance", _this.depthOfFieldDistance);
  53889. };
  53890. // Add to pipeline
  53891. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  53892. };
  53893. // Dispose
  53894. StandardRenderingPipeline.prototype.dispose = function () {
  53895. for (var i = 0; i < this._scene.cameras.length; i++) {
  53896. var camera = this._scene.cameras[i];
  53897. this.originalPostProcess.dispose(camera);
  53898. this.downSampleX4PostProcess.dispose(camera);
  53899. this.brightPassPostProcess.dispose(camera);
  53900. this.textureAdderPostProcess.dispose(camera);
  53901. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  53902. this.gaussianBlurHPostProcesses[j].dispose(camera);
  53903. }
  53904. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  53905. this.gaussianBlurVPostProcesses[j].dispose(camera);
  53906. }
  53907. this.textureAdderFinalPostProcess.dispose(camera);
  53908. this.lensFlarePostProcess.dispose(camera);
  53909. this.lensFlareComposePostProcess.dispose(camera);
  53910. this.depthOfFieldPostProcess.dispose(camera);
  53911. }
  53912. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53913. _super.prototype.dispose.call(this);
  53914. };
  53915. return StandardRenderingPipeline;
  53916. }(BABYLON.PostProcessRenderPipeline));
  53917. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  53918. })(BABYLON || (BABYLON = {}));
  53919. 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\n#ifdef VERTEXCOLOR\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}","legacydefaultPixelShader":"#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..3]\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 REFLECTION\nvarying vec3 vReflectionUVW;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\nuniform vec2 vReflectionInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\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 REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\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#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 normalW=normalize(vNormalW);\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\nglossiness=vSpecularColor.a;\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..3]\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\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);\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha=vDiffuseColor.a;\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\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).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 SPECULARTERM\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor=texture2D(specularSampler,vSpecularUV).rgb*vSpecularInfos.y;\n#endif\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\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}","legacydefaultVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\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\nuniform mat4 world;\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#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform mat4 reflectionMatrix;\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 coords=vec3(view*vec4(worldNormal,0.0));\nreturn vec3(reflectionMatrix*vec4(coords,1.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 position;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\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 REFLECTION\nvReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),vNormalW);\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#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\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","legacypbrPixelShader":"precision mediump float;\n\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vAlbedoColor;\nuniform vec3 vReflectionColor;\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\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)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#ifdef CAMERACOLORGRADING\nuniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;\n#endif\n\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\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\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).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);\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 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.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\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\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\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 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\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,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance,alpha);\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor,cameraColorGrading2DSampler,vCameraColorGradingInfos,vCameraColorGradingScaleOffset);\n#endif\ngl_FragColor=finalColor;\n}","legacypbrVertexShader":"precision mediump float;\n\nattribute vec3 position;\nattribute vec3 normal;\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\nuniform mat4 world;\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#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\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#if defined(REFLECTIVITY)\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#include<clipPlaneVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\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)\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 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)\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)\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];\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]*2.0,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*2.0,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*2.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*2.0))*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;\ngl_FragColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nfloat hash(vec2 p) {\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) {\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) {\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}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec4 result=vec4(0.0);\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*float(i));\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=texture2D(textureSampler,offset)*weight;\n}\nfloat patternWeight=0.4*length(vec2(0.5)-uv);\nresult=mix(result,result*vec4(pattern(uv),1.0),0.6);\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-vUV)/length(vec2(0.5))));\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,5.0);\nvec4 halo=texture2D(textureSampler,uv+haloVec)*weight;\ngl_FragColor=(result+halo)*strength;\n}\n#endif\n#if defined(LENS_FLARE_SHIFT)\nuniform vec2 resolution;\nuniform float distortionStrength;\nvoid main(void)\n{\nconst float dispersion=0.15;\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-vUV);\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec2 direction=vec2(normalize(ghostDir));\nvec4 rgbShift=vec4(\ntexture2D(textureSampler,vUV+direction*distortion.r).r,\ntexture2D(textureSampler,vUV+direction*distortion.g).g,\ntexture2D(textureSampler,vUV+direction*distortion.b).b,\n1.0\n);\ngl_FragColor=rgbShift;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 viewMatrix;\nuniform mat3 scaleBias1;\nuniform mat3 scaleBias2;\nvoid main(void)\n{\nvec3 camerax=viewMatrix[0].xyz;\nvec3 cameraz=viewMatrix[1].xyz;\nfloat camRot=dot(camerax,vec3(0.0,0.0,1.0))+dot(cameraz,vec3(0.0,1.0,0.0));\nmat3 rotation=mat3(\ncos(camRot),-sin(camRot),0.0,\nsin(camRot),cos(camRot),0.0,\n0.0,0.0,1.0\n);\nmat3 lensMatrix=scaleBias2*rotation*scaleBias1;\nvec2 lensFlareCoords=(lensMatrix*vec3(vUV,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,lensFlareCoords);\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}"};
  53920. 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"};
  53921. 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=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,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.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()||[])}},t}();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,n){void 0===n&&(n=1.401298e-45);var r=t-i;return-n<=r&&r<=n},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,n){return void 0===i&&(i=0),void 0===n&&(n=1),Math.min(n,Math.max(i,t))},t}();t.MathTools=i;var n=function(){function n(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return n.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},n.prototype.getClassName=function(){return\"Color3\"},n.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},n.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},n.prototype.toColor4=function(t){return void 0===t&&(t=1),new r(this.r,this.g,this.b,t)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},n.prototype.multiply=function(t){return new n(this.r*t.r,this.g*t.g,this.b*t.b)},n.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},n.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},n.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},n.prototype.scale=function(t){return new n(this.r*t,this.g*t,this.b*t)},n.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},n.prototype.add=function(t){return new n(this.r+t.r,this.g+t.g,this.b+t.b)},n.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},n.prototype.subtract=function(t){return new n(this.r-t.r,this.g-t.g,this.b-t.b)},n.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},n.prototype.clone=function(){return new n(this.r,this.g,this.b)},n.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},n.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},n.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)},n.prototype.toLinearSpace=function(){var t=new n;return this.toLinearSpaceToRef(t),t},n.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},n.prototype.toGammaSpace=function(){var t=new n;return this.toGammaSpaceToRef(t),t},n.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},n.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new n(0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return n.FromInts(i,r,o)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1],t[i+2])},n.FromInts=function(t,i,r){return new n(t/255,i/255,r/255)},n.Lerp=function(t,i,r){var o=t.r+(i.r-t.r)*r,e=t.g+(i.g-t.g)*r,s=t.b+(i.b-t.b)*r;return new n(o,e,s)},n.Red=function(){return new n(1,0,0)},n.Green=function(){return new n(0,1,0)},n.Blue=function(){return new n(0,0,1)},n.Black=function(){return new n(0,0,0)},n.White=function(){return new n(1,1,1)},n.Purple=function(){return new n(.5,0,.5)},n.Magenta=function(){return new n(1,0,1)},n.Yellow=function(){return new n(1,1,0)},n.Gray=function(){return new n(.5,.5,.5)},n}();t.Color3=n;var r=function(){function t(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}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,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var n=parseInt(i.substring(1,3),16),r=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(n,r,o,e)},t.Lerp=function(i,n,r){var o=new t(0,0,0,0);return t.LerpToRef(i,n,r,o),o},t.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},t.FromArray=function(i,n){return void 0===n&&(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.FromInts=function(i,n,r,o){return new t(i/255,n/255,r/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},t}();t.Color4=r;var o=function(){function n(t,i){this.x=t,this.y=i}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},n.prototype.getClassName=function(){return\"Vector2\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},n.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},n.prototype.addVector3=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},n.prototype.multiplyByFloats=function(t,i){return new n(this.x*t,this.y*i)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},n.prototype.negate=function(){return new n((-this.x),(-this.y))},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t)},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},n.prototype.clone=function(){return new n(this.x,this.y)},n.Zero=function(){return new n(0,0)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},n.CatmullRom=function(t,i,r,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+r.x)*e+(2*t.x-5*i.x+4*r.x-o.x)*s+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*e+(2*t.y-5*i.y+4*r.y-o.y)*s+(-t.y+3*i.y-3*r.y+o.y)*h);return new n(a,u)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>r.y?r.y:e,e=e<i.y?i.y:e,new n(o,e)},n.Hermite=function(t,i,r,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+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y;return new n(c,p)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,e=t.y+(i.y-t.y)*r;return new n(o,e)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y},n.Normalize=function(t){var i=t.clone();return i.normalize(),i},n.Minimize=function(t,i){var r=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new n(r,o)},n.Maximize=function(t,i){var r=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new n(r,o)},n.Transform=function(t,i){var r=n.Zero();return n.TransformToRef(t,i,r),r},n.TransformToRef=function(t,i,n){var r=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];n.x=r,n.y=o},n.PointInTriangle=function(t,i,n,r){var o=.5*(-n.y*r.x+i.y*(-n.x+r.x)+i.x*(n.y-r.y)+n.x*r.y),e=o<0?-1:1,s=(i.y*r.x-i.x*r.y+(r.y-i.y)*t.x+(i.x-r.x)*t.y)*e,h=(i.x*n.y-i.y*n.x+(i.y-n.y)*t.x+(n.x-i.x)*t.y)*e;return s>0&&h>0&&s+h<2*o*e},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.DistanceOfPointFromSegment=function(t,i,r){var o=n.DistanceSquared(i,r);if(0===o)return n.Distance(t,i);var e=r.subtract(i),s=Math.max(0,Math.min(1,n.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return n.Distance(t,h)},n}();t.Vector2=o;var e=function(){function n(t,i,n){this.x=t,this.y=i,this.z=n}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},n.prototype.getClassName=function(){return\"Vector3\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.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},n.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=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=r*s,t.y=-o*s,t.z=n*e,t.w=i*e,t},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z)},n.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},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z)},n.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},n.prototype.subtractFromFloats=function(t,i,r){return new n(this.x-t,this.y-i,this.z-r)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},n.prototype.negate=function(){return new n((-this.x),(-this.y),(-this.z))},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)},n.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z)},n.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},n.prototype.multiplyByFloats=function(t,i,r){return new n(this.x*t,this.y*i,this.z*r)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z)},n.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},n.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},n.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},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},n.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},n.prototype.clone=function(){return new n(this.x,this.y,this.z)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},n.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},n.GetClipFactor=function(t,i,r,o){var e=n.Dot(t,r)-o,s=n.Dot(i,r)-o,h=e/(e-s);return h},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromFloatArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},n.Zero=function(){return new n(0,0,0)},n.Up=function(){return new n(0,1,0)},n.Forward=function(){return new n(0,0,1)},n.Right=function(){return new n(1,0,0)},n.Left=function(){return new n((-1),0,0)},n.TransformCoordinates=function(t,i){var r=n.Zero();return n.TransformCoordinatesToRef(t,i,r),r},n.TransformCoordinatesToRef=function(t,i,n){var r=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];n.x=r/s,n.y=o/s,n.z=e/s},n.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var e=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],s=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=e/a,o.y=s/a,o.z=h/a},n.TransformNormal=function(t,i){var r=n.Zero();return n.TransformNormalToRef(t,i,r),r},n.TransformNormalToRef=function(t,i,n){var r=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];n.x=r,n.y=o,n.z=e},n.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},n.CatmullRom=function(t,i,r,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+r.x)*e+(2*t.x-5*i.x+4*r.x-o.x)*s+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*e+(2*t.y-5*i.y+4*r.y-o.y)*s+(-t.y+3*i.y-3*r.y+o.y)*h),m=.5*(2*i.z+(-t.z+r.z)*e+(2*t.z-5*i.z+4*r.z-o.z)*s+(-t.z+3*i.z-3*r.z+o.z)*h);return new n(a,u,m)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>r.y?r.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>r.z?r.z:s,s=s<i.z?i.z:s,new n(o,e,s)},n.Hermite=function(t,i,r,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+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y,f=t.z*a+r.z*u+i.z*m+o.z*y;return new n(c,p,f)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,e=t.y+(i.y-t.y)*r,s=t.z+(i.z-t.z)*r;return new n(o,e,s)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},n.Cross=function(t,i){var r=n.Zero();return n.CrossToRef(t,i,r),r},n.CrossToRef=function(t,i,n){M.Vector3[0].x=t.y*i.z-t.z*i.y,M.Vector3[0].y=t.z*i.x-t.x*i.z,M.Vector3[0].z=t.x*i.y-t.y*i.x,n.copyFrom(M.Vector3[0])},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Project=function(t,i,r,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=n._viewportMatrixCache?n._viewportMatrixCache:n._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=n._matrixCache?n._matrixCache:n._matrixCache=new u;return i.multiplyToRef(r,y),y.multiplyToRef(m,y),n.TransformCoordinates(t,y)},n.UnprojectFromTransform=function(t,r,o,e,s){var h=n._matrixCache?n._matrixCache:n._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/r*2-1,t.y=-(t.y/o*2-1);var a=n.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},n.Unproject=function(t,r,o,e,s,h){var a=n._matrixCache?n._matrixCache:n._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new n(t.x/r*2-1,(-(t.y/o*2-1)),t.z),y=n.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},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.RotationFromAxis=function(t,i,r){var o=n.Zero();return n.RotationFromAxisToRef(t,i,r,o),o},n.RotationFromAxisToRef=function(r,o,e,s){var h=r.normalize(),a=e.normalize(),u=p.X,m=p.Y,y=0,c=0,f=0,x=0,l=0,z=0,w=0,v=-1,d=0,g=M.Vector3[0],R=0,T=M.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(),n.CrossToRef(h,T,g),g.normalize(),n.Dot(a,g)<0&&(v=1),R=n.Dot(h,T),R=Math.min(1,Math.max(-1,R)),f=Math.acos(R)*v,n.Dot(T,u)<0&&(f=Math.PI+f,T=T.scaleInPlace(-1),d++);var _=M.Vector3[2],A=M.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(),n.CrossToRef(_,T,A),A.normalize(),n.CrossToRef(a,_,g),g.normalize(),n.Dot(T,g)<0&&(v=1),R=n.Dot(a,_),R=Math.min(1,Math.max(-1,R)),c=Math.acos(R)*v,n.Dot(A,m)<0&&(c=Math.PI+c,d++),v=-1,n.CrossToRef(u,T,g),g.normalize(),n.Dot(g,m)<0&&(v=1),R=n.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=f},n}();t.Vector3=e;var s=function(){function n(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},n.prototype.getClassName=function(){return\"Vector4\"},n.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)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.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},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},n.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},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},n.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},n.prototype.subtractFromFloats=function(t,i,r,o){return new n(this.x-t,this.y-i,this.z-r,this.w-o)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},n.prototype.negate=function(){return new n((-this.x),(-this.y),(-this.z),(-this.w))},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t,this.w*t)},n.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},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)&&i.WithinEpsilon(this.w,n.w,r)},n.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},n.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},n.prototype.multiplyByFloats=function(t,i,r,o){return new n(this.x*t,this.y*i,this.z*r,this.w*o)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},n.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},n.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},n.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},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},n.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},n.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},n.prototype.clone=function(){return new n(this.x,this.y,this.z,this.w)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},n.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2],t[i+3])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},n.Zero=function(){return new n(0,0,0,0)},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return n*n+r*r+o*o+e*e},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n}();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,n){return new t(this.width*i,this.height*n)},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 n=new t(this.width+i.width,this.height+i.height);return n},t.prototype.substract=function(i){var n=new t(this.width-i.width,this.height-i.height);return n},t.Lerp=function(i,n,r){var o=i.width+(n.width-i.width)*r,e=i.height+(n.height-i.height)*r;return new t(o,e)},t}();t.Size=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}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,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,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 n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-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(n,r,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 n=this.x,r=this.y,o=this.z,e=this.w,s=n*n,h=-2*(s+r*r)+1,a=2*(o*n+e*r),u=-2*(o*r-e*n),m=2*(n*r+e*o),y=-2*(o*o+s)+1;return u=u>1?1:u,u=u<-1?-1:u,t.x=Math.asin(u),t.z=Math.atan2(m,y),t.y=Math.atan2(a,h),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=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*(n+r),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*(r+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*(n+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 n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],e=r[4],s=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(s-m)*n,i.z=(h-e)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(e+h)/n,i.z=(s+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(s-m)/n,i.x=(e+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-e)/n,i.x=(s+m)/n,i.y=(u+y)/n,i.z=.25*n)},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,n){return t.RotationAxisToRef(i,n,new t)},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(i/2);return t.normalize(),n.w=Math.cos(i/2),n.x=t.x*r,n.y=t.y*r,n.z=t.z*r,n},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,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);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),e=.5*(n-t),s=.5*i;r.x=Math.cos(e)*Math.sin(s),r.y=Math.sin(e)*Math.sin(s),r.z=Math.sin(o)*Math.cos(s),r.w=Math.cos(o)*Math.cos(s)},t.Slerp=function(i,n,r){var o,e,s=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.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}return new t(e*i.x+o*n.x,e*i.y+o*n.y,e*i.z+o*n.z,e*i.w+o*n.w)},t}();t.Quaternion=a;var u=function(){function t(){this.m=new Float32Array(16)}return t.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])},t.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],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=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]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*e)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*e)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;t<16;t++)this.m[t]=0;return this},t.prototype.add=function(i){var n=new t;return this.addToRef(i,n),n},t.prototype.addToRef=function(t,i){for(var n=0;n<16;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;i<16;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=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),b=1/(i*T+n*_+r*M+o*A),F=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,D=s*y-h*m,q=e*c-a*u,V=e*y-h*u,N=e*m-s*u;return t.m[0]=T*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=A*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*d+o*g)*b,t.m[9]=-(i*w-n*d+o*R)*b,t.m[13]=(i*v-n*g+r*R)*b,t.m[2]=(n*F-r*L+o*C)*b,t.m[6]=-(i*F-r*P+o*Z)*b,t.m[10]=(i*L-n*P+o*S)*b,t.m[14]=-(i*C-n*Z+r*S)*b,t.m[3]=-(n*I-r*H+o*D)*b,t.m[7]=(i*I-r*q+o*V)*b,t.m[11]=-(i*H-n*q+o*N)*b,t.m[15]=(i*D-n*V+r*N)*b,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var n=new t;return this.multiplyToRef(i,n),n},t.prototype.copyFrom=function(t){for(var i=0;i<16;i++)this.m[i]=t.m[i];return this},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;n<16;n++)t[i+n]=this.m[n];return this},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),\nthis},t.prototype.multiplyToArray=function(t,i,n){var r=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],b=t.m[8],F=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[n]=r*v+o*T+e*b+s*P,i[n+1]=r*d+o*_+e*F+s*Z,i[n+2]=r*g+o*M+e*L+s*S,i[n+3]=r*R+o*A+e*C+s*I,i[n+4]=h*v+a*T+u*b+m*P,i[n+5]=h*d+a*_+u*F+m*Z,i[n+6]=h*g+a*M+u*L+m*S,i[n+7]=h*R+a*A+u*C+m*I,i[n+8]=y*v+c*T+p*b+f*P,i[n+9]=y*d+c*_+p*F+f*Z,i[n+10]=y*g+c*M+p*L+f*S,i[n+11]=y*R+c*A+p*C+f*I,i[n+12]=x*v+l*T+z*b+w*P,i[n+13]=x*d+l*_+z*F+w*Z,i[n+14]=x*g+l*M+z*L+w*S,i[n+15]=x*R+l*A+z*C+w*I,this},t.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]},t.prototype.clone=function(){return t.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])},t.prototype.getClassName=function(){return\"Matrix\"},t.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;i<16;i++)t=397*t^(this.m[i]||0);return t},t.prototype.decompose=function(n,r,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 n.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z?(r.x=0,r.y=0,r.z=0,r.w=1,!1):(t.FromValuesToRef(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1,M.Matrix[0]),a.FromRotationMatrixToRef(M.Matrix[0],r),!0)},t.FromArray=function(i,n){var r=new t;return n||(n=0),t.FromArrayToRef(i,n,r),r},t.FromArrayToRef=function(t,i,n){for(var r=0;r<16;r++)n.m[r]=t[r+i]},t.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;o<16;o++)r.m[o]=t[o+i]*n},t.FromValuesToRef=function(t,i,n,r,o,e,s,h,a,u,m,y,c,p,f,x,l){l.m[0]=t,l.m[1]=i,l.m[2]=n,l.m[3]=r,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},t.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])},t.prototype.setRow=function(t,i){if(t<0||t>3)return this;var n=4*t;return this.m[n+0]=i.x,this.m[n+1]=i.y,this.m[n+2]=i.z,this.m[n+3]=i.w,this},t.FromValues=function(i,n,r,o,e,s,h,a,u,m,y,c,p,f,x,l){var z=new t;return z.m[0]=i,z.m[1]=n,z.m[2]=r,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},t.Compose=function(i,n,r){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),e=t.Identity();return n.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(r),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var n=new t;return t.RotationXToRef(i,n),n},t.Invert=function(i){var n=new t;return i.invertToRef(n),n},t.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,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},t.RotationY=function(i){var n=new t;return t.RotationYToRef(i,n),n},t.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,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},t.RotationZ=function(i){var n=new t;return t.RotationZToRef(i,n),n},t.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,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},t.RotationAxis=function(i,n){var r=t.Zero();return t.RotationAxisToRef(i,n,r),r},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),n.m[0]=t.x*t.x*e+o,n.m[1]=t.x*t.y*e-t.z*r,n.m[2]=t.x*t.z*e+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*e+t.z*r,n.m[5]=t.y*t.y*e+o,n.m[6]=t.y*t.z*e-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*e-t.y*r,n.m[9]=t.z*t.y*e+t.x*r,n.m[10]=t.z*t.z*e+o,n.m[11]=0,n.m[15]=1},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},t.Scaling=function(i,n,r){var o=t.Zero();return t.ScalingToRef(i,n,r,o),o},t.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t.Translation=function(i,n,r){var o=t.Identity();return t.TranslationToRef(i,n,r,o),o},t.TranslationToRef=function(i,n,r,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,n,r,1,o)},t.Lerp=function(i,n,r){for(var o=t.Zero(),e=0;e<16;e++)o.m[e]=i.m[e]*(1-r)+n.m[e]*r;return o},t.DecomposeLerp=function(i,n,r){var o=new e(0,0,0),s=new a,h=new e(0,0,0);i.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);n.decompose(u,m,y);var c=e.Lerp(o,u,r),p=a.Slerp(s,m,r),f=e.Lerp(h,y,r);return t.Compose(c,p,f)},t.LookAtLH=function(i,n,r){var o=t.Zero();return t.LookAtLHToRef(i,n,r,o),o},t.LookAtLHToRef=function(i,n,r,o){n.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,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,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.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)},t.LookAtRH=function(i,n,r){var o=t.Zero();return t.LookAtRHToRef(i,n,r,o),o},t.LookAtRHToRef=function(i,n,r,o){i.subtractToRef(n,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,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,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.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)},t.OrthoLH=function(i,n,r,o){var e=t.Zero();return t.OrthoLHToRef(i,n,r,o,e),e},t.OrthoLHToRef=function(i,n,r,o,e){var s=2/i,h=2/n,a=1/(o-r),u=r/(r-o);t.FromValuesToRef(s,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,e)},t.OrthoOffCenterLH=function(i,n,r,o,e,s){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,n,r,o,e,s,h),h},t.OrthoOffCenterLHToRef=function(t,i,n,r,o,e,s){s.m[0]=2/(i-t),s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2/(r-n),s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=1/(e-o),s.m[8]=s.m[9]=s.m[11]=0,s.m[12]=(t+i)/(t-i),s.m[13]=(r+n)/(n-r),s.m[14]=-o/(e-o),s.m[15]=1},t.OrthoOffCenterRH=function(i,n,r,o,e,s){var h=t.Zero();return t.OrthoOffCenterRHToRef(i,n,r,o,e,s,h),h},t.OrthoOffCenterRHToRef=function(i,n,r,o,e,s,h){t.OrthoOffCenterLHToRef(i,n,r,o,e,s,h),h.m[10]*=-1},t.PerspectiveLH=function(i,n,r,o){var e=t.Zero();return e.m[0]=2*r/i,e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2*r/n,e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-o/(r-o),e.m[8]=e.m[9]=0,e.m[11]=1,e.m[12]=e.m[13]=e.m[15]=0,e.m[14]=r*o/(r-o),e},t.PerspectiveFovLH=function(i,n,r,o){var e=t.Zero();return t.PerspectiveFovLHToRef(i,n,r,o,e),e},t.PerspectiveFovLHToRef=function(t,i,n,r,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=r/(r-n),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=-(n*r)/(r-n)},t.PerspectiveFovRH=function(i,n,r,o){var e=t.Zero();return t.PerspectiveFovRHToRef(i,n,r,o,e),e},t.PerspectiveFovRHToRef=function(t,i,n,r,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=r/(n-r),o.m[11]=-1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=n*r/(n-r)},t.PerspectiveFovWebVRToRef=function(t,i,n,r,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);r.m[0]=u,r.m[1]=r.m[2]=r.m[3]=r.m[4]=0,r.m[5]=m,r.m[6]=r.m[7]=0,r.m[8]=(h-a)*u*.5,r.m[9]=-((e-s)*m*.5),r.m[10]=-n/(i-n),r.m[11]=1,r.m[12]=r.m[13]=r.m[15]=0,r.m[14]=i*n/(i-n)},t.GetFinalMatrix=function(i,n,r,o,e,s){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.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 n.multiply(r).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.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]])},t.Transpose=function(i){var n=new t;return n.m[0]=i.m[0],n.m[1]=i.m[4],n.m[2]=i.m[8],n.m[3]=i.m[12],n.m[4]=i.m[1],n.m[5]=i.m[5],n.m[6]=i.m[9],n.m[7]=i.m[13],n.m[8]=i.m[2],n.m[9]=i.m[6],n.m[10]=i.m[10],n.m[11]=i.m[14],n.m[12]=i.m[3],n.m[13]=i.m[7],n.m[14]=i.m[11],n.m[15]=i.m[15],n},t.Reflection=function(i){var n=new t;return t.ReflectionToRef(i,n),n},t.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,e=-2*n,s=-2*r,h=-2*o;i.m[0]=e*n+1,i.m[1]=s*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=e*r,i.m[5]=s*r+1,i.m[6]=h*r,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},t.FromXYZAxesToRef=function(t,i,n,r){r.m[0]=t.x,r.m[1]=t.y,r.m[2]=t.z,r.m[3]=0,r.m[4]=i.x,r.m[5]=i.y,r.m[6]=i.z,r.m[7]=0,r.m[8]=n.x,r.m[9]=n.y,r.m[10]=n.z,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t._tempQuaternion=new a,t._xAxis=e.Zero(),t._yAxis=e.Zero(),t._zAxis=e.Zero(),t}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new e(t,i,n),this.d=r}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 n=u.Transpose(i),r=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=r*n.m[0]+o*n.m[1]+e*n.m[2]+s*n.m[3],a=r*n.m[4]+o*n.m[5]+e*n.m[6]+s*n.m[7],m=r*n.m[8]+o*n.m[9]+e*n.m[10]+s*n.m[11],y=r*n.m[12]+o*n.m[13]+e*n.m[14]+s*n.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,n){var r,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.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 r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,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 n=e.Dot(this.normal,t);return n<=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,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(n,i)+r},t}();t.Plane=m;var y=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i,n){return new t(this.x*i,this.y*n,this.width*i,this.height*n)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;r<6;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},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,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var p=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=p;var f=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var e=1-3*r+3*i,s=3*r-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*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=f,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var x=t.Orientation,l=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,n){var r=n.subtract(i),o=Math.atan2(r.y,r.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=l;var z=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,s=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-n.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-n.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.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?x.CW:x.CCW,this.angle=l.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=z;var w=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 n=new o(t,i),r=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(r).length(),this},t.prototype.addArcTo=function(t,i,n,r,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(n,r),u=new z(s,h,a),m=u.angle.radians()/e;u.orientation===x.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],n=this._points[0];t+=n.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(),n=0,r=0;r<this._points.length;r++){var e=(r+1)%this._points.length,s=this._points[r],h=this._points[e],a=h.subtract(s),u=a.length()+n;if(i>=n&&i<=u){var m=a.normalize(),y=i-n;return new o(s.x+m.x*y,s.y+m.y*y)}n=u}return o.Zero()},t.StartingAt=function(i,n){return new t(i,n)},t}();t.Path2=w;var v=function(){function n(t,i,n){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 r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return n.prototype.getCurve=function(){return this._curve},n.prototype.getTangents=function(){return this._tangents},n.prototype.getNormals=function(){return this._normals},n.prototype.getBinormals=function(){return this._binormals},n.prototype.getDistances=function(){return this._distances},n.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},n.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 n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(n,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()},n.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},n.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},n.prototype._normalVector=function(n,r,o){var s,h=r.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(r.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(r.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(r.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(r,a)}else s=e.Cross(r,o),e.CrossToRef(s,r,s);return s.normalize(),s},n}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;a<=o;a++)s.push(new e(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(s)},t.CreateCubicBezier=function(i,n,r,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,n,r,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return e},u=0;u<=s;u++)h.push(new e(a(u/s,i.x,n.x,r.x,o.x),a(u/s,i.y,n.y,r.y,o.y),a(u/s,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,s){for(var h=new Array,a=1/s,u=0;u<=s;u++)h.push(e.Hermite(i,n,r,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 n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)r.push(o[e].subtract(o[0]).add(n));var s=new t(r);return s},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=d;var g=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,n){var r=new e(i.r,i.g,i.b),o=r.scale(n);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=g;var R=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 n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=R;var T=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=T;var _=function(){function t(t,i,n){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===n&&(n=o.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Color3=[n.Black(),n.Black(),n.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],t.Vector4=[s.Zero(),s.Zero(),s.Zero()],t.Quaternion=[new a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  53922. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  53923. module.exports = BABYLON;
  53924. };